How do i return more than one result from this if the input have similar value

45 views Asked by At

E.g.: In this scenario, most expensive items are needed.

d= (('Shirts',40000),('trousers',40000),('provisions',34000),('others',34000))

def pick_the_most_expensive_from_my_list(d):
    material = '' 
    price = None
    for x,y in d:
        if price is None:
            price= y
            material= x
        while y > price:
            price = y                           
            material= x
        
    return material,price
3

There are 3 answers

1
Chris On BEST ANSWER

You could find the max price first, then return pairs that have that price.

d= (('Shirts',40000),('trousers',40000),('provisions',34000),('others',34000))

def pick_the_most_expensive_from_my_list(d):
    return [pair for pair in d if pair[1]==max([item[1] for item in d])]

Output

[('Shirts', 40000), ('trousers', 40000)]
0
sahasrara62 On

you need to find the maximum price first and then filter the value having that much price.

d= (('Shirts',40000),('trousers',40000),('provisions',34000),('others',34000))

def pick_the_most_expensive_from_my_list(d):
    if not d:
        return None
    max_v = max(d, key=lambda x:x[1])[-1]
    return list(filter(lambda x: x[1]==max_v, d))
    
print(pick_the_most_expensive_from_my_list(d))

output

[('Shirts', 40000), ('trousers', 40000)]

or using dictionary

d= (('Shirts',40000),('trousers',40000),('provisions',34000),('others',34000))

def pick_the_most_expensive_from_my_list(d):
    if not d:
        return None
    price = {}
    
    for i in d:
        if i[1] not in price:
            price[i[1]] = [i]
        else:
            price[i[1]].append(i)
    
    return price.get(max(price))
    
print(list(pick_the_most_expensive_from_my_list(d)))
0
Abid On

def mostExpensiveItems():
    items = [''] 
    prices = [0] 
    for currentItems, currentPrices in items:  
        if currentPrices > prices[-1]: 
            items.append(currentItems)
            prices.append(currentPrices)
        elif currentPrices == prices[-1]:
            items.append(currentItems)
            prices.append(currentPrices)
    print(items)
    print(prices)