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?

29th Sep 2020, 10:40 PM
Ali Rezaei
Ali Rezaei - avatar
5 ответов
+ 3
print(max(filter(lambda x:x%2!=0,(x,y,z))))
29th Sep 2020, 11:27 PM
Abhay
Abhay - avatar
+ 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.
29th Sep 2020, 11:00 PM
Ipang
+ 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 )
29th Sep 2020, 11:51 PM
Ipang
+ 1
Ipang Great. How can I do that?
29th Sep 2020, 11:02 PM
Ali Rezaei
Ali Rezaei - avatar
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)
30th Sep 2020, 12:04 AM
Abhay
Abhay - avatar