Intro Python: Please help me fix my code; this is a bubble sort recursion proble
ID: 3913105 • Letter: I
Question
Intro Python: Please help me fix my code; this is a bubble sort recursion problem and my output is supposed to look like this: [('4213', 'STEM Center', 0), ('4201', 'Foundations Lab', 1), ('4204', 'CS Lab', 2), ('4218', 'Workshop Room', 3), ('4205', 'Tiled Room', 4), ('Out', 'Outside', 5)] [('4201', 'Foundations Lab', 1), ('4204', 'CS Lab', 2), ('4205', 'Tiled Room', 4), ('4213', 'STEM Center', 0), ('4218', 'Workshop Room', 3), ('Out', 'Outside', 5)] [('4204', 'CS Lab', 2), ('4201', 'Foundations Lab', 1), ('Out', 'Outside', 5), ('4213', 'STEM Center', 0), ('4205', 'Tiled Room', 4), ('4218', 'Workshop Room', 3)] [('4204', 'CS Lab', 2), ('4201', 'Foundations Lab', 1), ('Out', 'Outside', 5), ('4213', 'STEM Center', 0), ('4205', 'Tiled Room', 4), ('4218', 'Workshop Room', 3)] instead it looks like this: [('4213', 'STEM Center', 0), ('4218', 'Workshop Room', 3), ('4201', 'Foundations Lab', 1), ('4205', 'Tiled Room', 4), ('4204', 'CS Lab', 2), ('out', 'Outside', 5)] None None -------------------------- def recursiveSort(sensor_list,n,t): #Recursive Sort if n == 0: return sensor_list for i in range(n-1): if sensor_list[i][t] > sensor_list[i+1][t]: temp = sensor_list[i] sensor_list[i] =sensor_list[i+1] sensor_list[i+1] = temp return recursiveSort(sensor_list,n-1,t) Dict = {'4213' : ('STEM Center', 0), '4201' : ('Foundations Lab', 1), '4204' : ('CS Lab', 2), '4218' : ('Workshop Room', 3), '4205' : ('Tiled Room', 4), 'out' : ('Outside', 5), } sensor_list=[] [sensor_list.append((key,Dict[key][0],Dict[key][1])) for key in Dict] #Adding values to a dictionary into a tuple using list comprehension print sensor_list print recursiveSort(sensor_list,len(sensor_list), 0) print recursiveSort(sensor_list,len(sensor_list), 1)
Explanation / Answer
you did a small mistake in recursiveSort function you need to put the for loop outside first if of your function : --------->>>>>>>here is the modified code : ----------->>>>>>>>>>
def recursiveSort(sensor_list,n,t): #Recursive Sort
if n == 0:
return sensor_list
for i in range(n-1):
if sensor_list[i][t] > sensor_list[i+1][t]:
temp = sensor_list[i]
sensor_list[i] =sensor_list[i+1]
sensor_list[i+1] = temp
return recursiveSort(sensor_list,n-1,t)
Dict = {'4213' : ('STEM Center', 0),
'4201' : ('Foundations Lab', 1),
'4204' : ('CS Lab', 2),
'4218' : ('Workshop Room', 3),
'4205' : ('Tiled Room', 4),
'out' : ('Outside', 5),
}
sensor_list=[]
[sensor_list.append((key,Dict[key][0],Dict[key][1])) for key in Dict]
#Adding values to a dictionary into a tuple using list comprehension
print sensor_list
print recursiveSort(sensor_list,len(sensor_list), 0)
print recursiveSort(sensor_list,len(sensor_list), 1)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.