Home > database >  Print out the index of the value that satisfy the list's condition
Print out the index of the value that satisfy the list's condition

Time:11-28

I am having trouble figuring out how to come up with the correct code for this particular problem that involving list. So the question is: We have n fruit baskets, with some apples and oranges in them. We want to select the basket that have the most apples, but if there are several baskets with the same amount (biggest) of apples, we will then pick the one that has more oranges in it. (Harry has 2 fruit basket. - The first basket contains 2 apples and 3 oranges. - The second basket contains 1 apple and 4 oranges. - The third basket contains 2 apples and 5 oranges. We see that the first and third basket have the most apples of 2. But among these 2 baskets, the third basket have more oranges than the first basket. So Harry chooses the third one.)

I have thought of making two separate list for apple and orange and then find the max value of each list. But I haven't figured out how to return the correct basket (or index of the value of the list). Here is my code, please help if you can, thank you! (I have not learn panda or lambda yet, so just pure Python)

n = int(input())
a = []
b = []
for i in range(n):
    x,y = map(int,input().split())
    a.append(x)
    b.append(y)
app = max(a)
oran = max(b)
idx = 0
for num in range(len(a)):
    if a[num] < app:
        continue
    
    if a[num] == app:
        
        if b[num] < oran:
            idx = a.index(a[num])
        elif b[num] == oran:
            idx = b.index(oran)
        
        
print(idx 1)

CodePudding user response:

Your problem is in this section:

    if a[num] == app:
        if b[num] < oran:
            idx = a.index(a[num])
        elif b[num] == oran:
            idx = b.index(oran)

When you find the max number of ranges with if b[num] == oran, you set idx to the index of the first occurance of oran in b, not num. Also, you keep iterating and checking, so if you were to find another b[num] < oran, that value would get overridden again - your logic there is flawed in several ways.

Something like this would be better:

b_max = 0
...
    if a[num] == app:
        if b[num] > b_max:
            idx, b_max = num, b[num]

However, the entire solution is very complicated for what is required:

n = int(input())
apples, oranges = zip(*(map(int, input().split()) for _ in range(n)))
idx, ma, mo = 0, 0, 0
for i, (a, o) in enumerate(zip(apples, oranges)):
    if a > ma or (a == ma and o > mo):
        idx, ma, mo = i, a, o

print(idx   1)

Whether you consider this more readable or less depends on who your audience is, but I provided the example because you seemed to be combining some operations in one-liners already.

  • Related