- 1
How to write a program that returns the largest even number in the list of integers.
If there is no even number in the input, print "No even element".
24 Respostas
+ 2
Lalit kumar here is a quick fix on your code:
If any questions please ask.
https://code.sololearn.com/cw2xZgles6no/?ref=app
+ 4
If you like this also: (list comprehension with max() function and if condition)
print(max([i for i in range(38) if i%2 == 0]))
+ 4
You could also try:
max(lst, key=lambda n: n*(n%2==0))
+ 4
yaseer, thatās a really nice code!
+ 3
Thanks Lothar
+ 3
Rohan Agrawal absolutely agree
+ 2
Did you try yourself?
+ 2
Post your try here and people will be glad to help you.
+ 2
ravindu poorna this will throw an error if there is no even number in given input
+ 2
ravindu poorna No Problem :)
+ 1
You're welcome.
+ 1
Try this logic:
- create a variable "largest" and initialize it with the value -1.
- iterate over the list and for each element, check if it's even.
- if it is even, compare it with the variable "largest" and if the element is greater than "largest", then assign that element to largest.
- when the loop ends, the largest even number will be stored in "largest".
- check if "largest" is equal to -1. If it is, the list contains no even number.
Try yourself once before checking the code.
Code for reference:
https://code.sololearn.com/cc6n7B40hqG7/?ref=app
A more advanced logic:
- use 'filter' to obtain a list of only even integers.
- 'filter' takes first argument as an anonymous function.
- check if length of new list is 0. If it is, no even number exists.
- else use 'max' to find largest number in the list.
Code for reference:
https://code.sololearn.com/cx6K8KTk1wVO/?ref=app
+ 1
max(list) - returns the largest number in a list of integers
+ 1
#this will return the highest even number
#this will take the user input and make a list
inputNumbers = input ("enter your numbers ")
inputList = list(inputNumbers)
#this will convert the str list into int
for i in range(0,len(inputList)):
inputList[i] = int(inputList[i])
#ths will check for the even numbers
even = list (filter(lambda x:x%2==0,inputList))
if len(even) != 0:
print (max(even))
else:
print ("there is no even numbers")
+ 1
George Pavlov this won't give the "largest even" number. It simply gives the "largest" number irrespective of whether it's odd or even.
+ 1
Rohan Agrawal I did fix the problem. Thank you.
+ 1
George Pavlov check out my answer if you face any trouble.
Happy coding! :)
+ 1
numbers = list(range(0,10,2))
print(max(numbers))
0
I tried but not getting the same result
0
lst=eval(input ("Enter list:"))
length=len(lst)
pos=0
largest=0
while pos<length:
if lst[pos]%2==0:
largest=lst[i]
print(largest even no. is :'')
else:
print ("No even element ")