Sunday, 2 September 2018

Python program to find the largest and smallest number in a list

Here we use 2 predefined functions min() and max() which check for the smallest and largest number in a list respectively.

Approach :

  • Read input number asking for length of the list using input() or raw_input().
  • Initialise an empty list lst = [].
  • Read each number using a for loop.
  • In the for loop append each number to the list.
  • Now we use predefined function max() to find the largest element in a list.
  • Similarly we use another predefined function min() to find the smallest element in a list.
  • lst = []
    num = int(input('How many numbers: '))
    for n in range(num):
        numbers = int(input('Enter number '))
        lst.append(numbers)
    print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))
list = [(1,3),(2,5),(2,4),(7,5)]
I need to get the min max value for each position in tuple.
Fox example: The exepected output of alist is
min_x = 1
max_x = 7

min_y = 3
max_y = 5
map(max, zip(*alist))
This first unzips your list, then finds the max for each tuple position
>>> alist = [(1,3),(2,5),(2,4),(7,5)]
>>> zip(*alist)
[(1, 2, 2, 7), (3, 5, 4, 5)]
>>> map(max, zip(*alist))
[7, 5]
>>> map(min, zip(*alist))
[1, 3]

No comments:

Post a Comment