0
How to use list comprehension here to find the min and max value without using numpy
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
"""
+ 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))
+ 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
+ 3
and now the oneliner
amin, amax=(min(map(min, a)), max(map(max, a)))
+ 2
yes: destructuring is kind of value collect... as example with a list print(*[1,2,3]), will act as print(1,2,3)
+ 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
+ 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?
+ 1
no it just makes the code more elegant/faster
0
print(max(list))
try this
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