After reviews of my previous codes 1st, 2nd learned many new things. So with those in mind, this is my solution for another question.
Question: Write a program that ask user for list size and values and find largest and smallest no, even no, odd no?
Expected output: For user defined list,
[13, 7, 19, 21, 3, 4, 27, 47, 50, 11] -> 50, 3, 50, 4, 47, 3
[2, 4, 6, 8, 10] -> 10, 2, 10, 2, None, None
[1, 3, 5, 7, 9] -> 9, 1, None, None, 9, 1
Format:
largest_no, smallest_no, largest_even, smallest_even, largest_odd, smallest_odd
My solution:
def largest_and_smallest(given_list):
"""Extracts required numbers from given_list.
>>> largest_and_smallest([13, 7, 19, 21, 3, 4, 27, 47, 50, 11])
(50, 3, 50, 4, 47, 3)
>>> largest_and_smallest([2, 4, 6, 8, 10])
(10, 2, 10, 2, None, None)
>>> largest_and_smallest([1, 3, 5, 7, 9])
(9, 1, None, None, 9, 1)
"""
sorted_list = sorted(given_list)
largest_no = max(sorted_list)
smallest_no = min(sorted_list)
list_of_even = [even_no for even_no in sorted_list if ((even_no % 2) == 0)]
if len(list_of_even) == 0:
largest_even = None
smallest_even = None
else:
largest_even = max(list_of_even)
smallest_even = min(list_of_even)
list_of_odd = [odd_no for odd_no in sorted_list if ((odd_no % 2) != 0)]
if len(list_of_odd) == 0:
largest_odd = None
smallest_odd = None
else:
largest_odd = max(list_of_odd)
smallest_odd = min(list_of_odd)
return largest_no, smallest_no, largest_even, smallest_even, largest_odd, smallest_odd
def input_handler():
"""Checks validity of input. Any mistakes causes the program to stops."""
size = input("Enter a size of list?\n>")
if size.strip() == "":
exit("Program Terminated. (No Input)")
elif size.isdigit():
list_size = int(size)
list_of_no = [int(input("Enter value:")) for _ in range(list_size)] # bad input causes error.
return list_size, list_of_no
else:
exit("Program Terminated. (Bad Input)")
def main():
print("All input should be integers.")
list_size, list_of_no = input_handler()
l_no, s_no, l_even, s_even, l_odd, s_odd = largest_and_smallest(list_of_no)
print()
print(f"From provided values of list of a size {list_size}:")
print(f"Largest no.: {l_no}, Smallest no.: {s_no}, Largest even no.: {l_even}, "
f"Smallest even no.: {s_even}, Largest odd no.: {l_odd}, Smallest odd no.: {s_odd}")
return
if __name__ == '__main__':
import doctest
doctest.testmod(main())
So, from this review I would like to know:
I have used list comprehension as per suggestion in previous code, have I used that correctly? For example, I made separate list for even and odd numbers could I have done that in different way?
I made a separate function to handle input is that a bad practice? What is the best way to handle inputs, that checks different corner cases?
If there is any recommendations going forward from this will help me a lot.