Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a code to obtain the lowest values of each list within a list in python?

I need help writing a code that will help me obtain the lowest number of the each list within a list in python. And then out of the lowest values obtained I must somehow find the highest number of the lowest numbers. I am not allowed to call the built-in functions min or max, or use any other functions from pre-written modules. How can I go about doing this? I have already tried using the following code:

for list in ells:
    sort.list(ells)
like image 284
Tasdid Sarker Avatar asked Oct 13 '18 03:10

Tasdid Sarker


2 Answers

Since you are not allowed to use built-in functions, you can instead use a variable to keep track of the lowest number you find so far while you iterate through the sublists, and another to keep track of the highest of the lowest numbers you find so far you iterate through the list of lists:

l = [
    [2, 5, 7],
    [1, 3, 8],
    [4, 6, 9]
]
highest_of_lowest = None
for sublist in l:
    lowest = None
    for item in sublist:
        if lowest is None or lowest > item:
            lowest = item
    if highest_of_lowest is None or highest_of_lowest < lowest:
        highest_of_lowest = lowest
print(highest_of_lowest)

This outputs: 4

like image 158
blhsing Avatar answered Nov 15 '22 00:11

blhsing


You can iterate through your lists and compare to a variable, here using lo, if the item is less than the current amount then assign that as the new lo. After repeat the process but with hi and opposite logic.

lst = [[1, 2, 3], [4, 5, 6,], [7, 8, 9]]

lows = []
for i in lst:
    lo = None
    for j in i:
        if lo == None: # to get initial lo
            lo = j
        elif j < lo:
            lo = j
    lows.append(lo)

hi = 0
for i in lows:
    if i > hi:
        hi = i

print(hi)
like image 43
vash_the_stampede Avatar answered Nov 15 '22 01:11

vash_the_stampede