Click here to Skip to main content
15,881,600 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Write a python program to define a tuple to accept 3 food product details such as Products name with their Price and Expiry date in a sub tuple then,arrange the tuple of tuple elements based on their price in ascending order.
I should not use lambda or sorted function, i can use bubble sort,insertion sort and selection sort

def sort(lst):
for i in range(0,len(lst)):
for j in range(0,len(lst)-i-1):
if lst[j][0]<lst[j+1][0]:
key="lst[j]
" lst[j]="lst[j+1]
" lst[j+1]="key
return" tuple(lst)
lst="list(t)
sort(lst)

<b">What I have tried:

see above pls
t=('CAKE', (748.0, '08-09-2020'), 'JELLY', (12.0, '08-09-2020'), 'CREAM', (244.0, '03-11-2020'))
Posted
Updated 2-Sep-20 5:11am
v3

1 solution

Using Bubble sort, it would be something like:
Python
def sortTuple(t):  
    for i in range(0, len(t)):  
        for j in range(0, len(t)-i-1):  
            if (t[j][1] > t[j + 1][1]):  #notice here, I have used index 1 to use price as the value
                temp = t[j]  
                t[j]= t[j + 1]  
                t[j + 1]= temp  
    return t  
   
ex = [('apple', 10, '1/1/2021'), ('banana', 5,'1/1/2021'), ('mango', 20,'1/1/2021')] 
print(sortTuple(ex))

Output : [('banana', 5,'1/1/2021'), ('apple', 10, '1/1/2021'), ('mango', 20,'1/1/2021')]
So, all you need is to:
1. extract the price data out from tuple
2. use that data in a simple bubble sort algorithm

More about tuples: Python - Tuples - Tutorialspoint[^]
 
Share this answer
 
v2
Comments
CPallini 2-Sep-20 10:40am    
5.
Member 14928977 2-Sep-20 11:17am    
but price and enquiry date is a sub tuple
Sandeep Mewara 2-Sep-20 23:23pm    
def sortTuple(t):  
    for i in range(0, len(t)):  
        for j in range(0, len(t)-i-1):  
            if (t[j][1] > t[j + 1][1]):  #notice here, I have used index 1 to get sub tuple
                # print(t[j][1][0]) if you explicitly need to work with price
                # subtuples with price first is good enough in itself for comparison - they will sort properly
                temp = t[j]  
                t[j]= t[j + 1]  
                t[j + 1]= temp  
    return t  
   
ex = [('apple', (10, '10/1/2021')), ('banana', (5,'5/1/2024')), ('mango', (20,'1/1/2021'))] 
print(sortTuple(ex))
Sandeep Mewara 2-Sep-20 23:24pm    
You have to try. Attempt and play to learn and see how it works.
Member 14928977 3-Sep-20 4:04am    
THANKS, IT WORKED

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900