How to use list comprehension here to find the min and max value without using numpy | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to use list comprehension here to find the min and max value without using numpy

https://code.sololearn.com/cTAJPQmovByo/?ref=app

2nd Jun 2021, 4:45 AM
Jace🎭
Jace🎭 - avatar
10 Answers
+ 6
""" firstly, to use the random module, you must import it (or rather only import the required randint function from it) ^^ you could find min and max of the randomly generated matrix using list comprehension much simpler: """ from random import randint row = 5 col = 10 matrix = [[randint(1,100) for c in range(col)] for r in range(row)] print(*matrix,sep="\n") mn = min(*[min(*matrix[r]) for r in range(row)]) mx = max(*[max(*matrix[r]) for r in range(row)]) print("min:",mn,"max:",mx) """ * here is the destructuring operator: it pass all values in iterable as argument 'sep' keyword argument in print is used to overide the default space separator by the new line char between each argument of the print function """
2nd Jun 2021, 5:07 AM
visph
visph - avatar
+ 5
there is no difference to maximum of list. maximum is 0 at the beginning and if you find a greater number, this is maximum. shortpath: filasmax = list(map(max,a)) totalmax=(max(filasmax))
2nd Jun 2021, 6:49 AM
Oma Falk
Oma Falk - avatar
+ 4
visph you can make it faster by just destructuring the generators directly instead of creating a temporary list: #your code mn = min(*(min(*r) for r in range(row))) mx = max(*(max(*r) for r in range(row))) #rest of the code
2nd Jun 2021, 7:10 AM
Bot
Bot - avatar
+ 3
and now the oneliner amin, amax=(min(map(min, a)), max(map(max, a)))
2nd Jun 2021, 7:21 AM
Oma Falk
Oma Falk - avatar
+ 2
yes: destructuring is kind of value collect... as example with a list print(*[1,2,3]), will act as print(1,2,3)
2nd Jun 2021, 3:11 PM
visph
visph - avatar
+ 1
P.M. you're right... and you make me see a mistake now corrected (but not in your code sample): the inner *r should be *matrix[r] ;P
2nd Jun 2021, 7:20 AM
visph
visph - avatar
+ 1
visph P.M. guys I'm not yet familiar with deconstruct operators but researching I've found * is used to callect values... Still I don't see the reason to be used here since I've run the code multiple times and it still gives me the values I need. Does it have something to do with them being passed as arguments?
2nd Jun 2021, 3:08 PM
Jace🎭
Jace🎭 - avatar
+ 1
no it just makes the code more elegant/faster
2nd Jun 2021, 3:11 PM
Bot
Bot - avatar
0
print(max(list)) try this
3rd Jun 2021, 5:41 PM
Somil Khandelwal
0
Somil Khandelwal you are half right only: max and min built-in function accept iterable as argument, but would fail in some corner cases... try this: m = [ [1,2,3], [2,1,3], [2,2,2] ] print(max(m)) # [2,2,2] print(max(max(m))) # 2
3rd Jun 2021, 6:06 PM
visph
visph - avatar