0
The following code examine three variables -- x, y, and z -- and prints the largest odd number among them. If none of them is o
if x % 2 == 1 : if y % 2 == 1 and x >= y : if z % 2 == 1 and x >= z : print(x) elif y % 2 == 1 : if x % 2 == 1 and y >= x : if z % 2 == 1 and x >= z : print(y) elif z % 2 == 1 : if x % 2 == 1 and z >= x : if y % 2 == 1 and z >= y : print(z) else : print('All three numbers are even') Don't the if statements in these questions result in the interpreter never reaching the else statement?
5 odpowiedzi
+ 3
print(max(filter(lambda x:x%2!=0,(x,y,z))))
+ 2
Do you really have to use all those if...elif...else block? there is an alternative by using tuple comprehension with odd number filter, tollowed by use of built-in max() on the tuple to find largest number.
+ 2
x, y, z = 10, 14, 76
# create a tuple of odd numbers
odds = tuple( n for n in (x, y, z ) if n & 1 )
# <result> is max of tuple elements (if there is anything in the tuple). Otherwise None.
result = max( odds ) if odds else None
print( result )
+ 1
Ipang Great. How can I do that?
0
import timeit
start=timeit.default_timer()
print(max(n for n in (1,2,3) if n & 1))
print(timeit.default_timer()-start)
start=timeit.default_timer()
print(max(filter(lambda x:x%2==1,(1,2,3))))
print(timeit.default_timer()-start)
start=timeit.default_timer()
print(max(n for n in (1,2,3) if n%2==1))
print(timeit.default_timer()-start)