Write recursive code for the following problem using python 3.2+. Define a funct
ID: 3828088 • Letter: W
Question
Write recursive code for the following problem using python 3.2+.
Define a function named q2() that accepts a Dictionary of characters as a parameter and returns a List of the keys from the Dictionary, sorted in descending order based on their corresponding values (largest to smallest). The q2() function should complete this without using .sort() or sorted() or any other built-in Python sorting function. Some examples of the q2() function: q2 ({' Bar: 20, 'Handle': 40, 'Steps': 30, 'Spokes': 10, 'Gears' " 60}) ['Gears', 'Handle', 'Steps', 'Bar', 'Spokes'] q2 ({'Q': 120, 'L': 300, 'M': 80, 'D': 299}) ['L', 'D', 'Q', 'M']Explanation / Answer
def q2(array="# REPLACE WITH THE ARRAY : array"):
keys = list(array.keys())
values = list(array.values())
(keys,values) = zip(*array.items())
less = []
lesskey=[]
equal = []
equalkey=[]
greater = []
greaterkey=[]
if len(values) > 1:
pivot = values[0]
for x in 0:len(values):
if values[x] < pivot:
less.append(values[x])
lesskeys.append(keys[x])
if values[x] == pivot:
equal.append(values[x])
equalkeys.append(keys[x])
if values[x] > pivot:
greater.append(values[x])
greaterkeys.append(keys[x])
# Don't forget to return something!
return q2(dict(zip(less,lesskey)))+dict(zip(equal,equalkey))+q2(dict(zip(greater,greaterkeys))) # Just use the + operator to join lists
# Note that you want equal ^^^^^ not pivot
else: # You need to hande the part at the end of the recursion - when you only have one element in your array, just return the array.
return array
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.