You will need to process a (potentially large) list of integers. The goal is to
ID: 3854414 • Letter: Y
Question
You will need to process a (potentially large) list of integers. The goal is to either sort (into descending order) all the even number in the list, or all the odd numbers. Which numbers you need to sort is indicated by the first number of the input. The numbers of the non-indicated parity should be unaltered. E.g, if you are instructed to sort the odd numbers, then print the list with all even numbers (including 0) in their original place in the input and the odd numbers sorted into ascending order.
Input The input consists of 3 lines: -the first line contains the word 'odd' or 'even' and indicates which numbers you need to sort -the second line contains the length of the list you will need to process -the 3rd line contains the list of integers.
Output The processed input with either odd or even numbers sorted.
Why is there no correct answer for this problem posted here: http://www.chegg.com/homework-help/questions-and-answers/problem-1048-title-sort-search-dates-description-input-n-1-q11330321 ?
Explanation / Answer
import operator
type_of_sort = input("enter the type of sort 'even' or 'odd'")
l = int(input("enter the number of values of the list: "))
list_of_values = []
for i in range(l):
try:
list_of_values.append(int(input("Enter a number: ")))
except Exception as e:
print(e)
temp_dict = {}
if type_of_sort == 'odd':
for val in list_of_values:
if val % 2 != 0:
if list_of_values.index(val) not in temp_dict:
temp_dict[list_of_values.index(val)] = val
else:
pass
index_val_list = list(temp_dict.keys())
sorted_dict = sorted(temp_dict.items(), key = operator.itemgetter(1))
sorted_vals = [val[1] for val in sorted_dict]
for i in range(len(index_val_list)):
list_of_values[index_val_list[i]] = sorted_vals[i]
elif type_of_sort == 'even':
for val in list_of_values:
if val % 2 == 0:
if list_of_values.index(val) not in temp_dict:
temp_dict[list_of_values.index(val)] = val
else:
pass
index_val_list = list(temp_dict.keys())
sorted_dict = sorted(temp_dict.items(), key = operator.itemgetter(1))
sorted_vals = [val[1] for val in sorted_dict]
for i in range(len(index_val_list)):
list_of_values[index_val_list[i]] = sorted_vals[i]
else:
print("invalid sort option")
print("Sorted list" , list_of_values)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.