Q. Write a code that reduces number of comparisons in above code while creating sequence B.
Answer =
A = eval(input("Enter a list :- ")) user = input("Enter order you want (Asc/Dsc):- ") B = [ ] length = len(A) for i in range(1,length): temp = A[i] j = i-1 if user == "Asc" or user == "asc" : while j>=0 and temp < A[ j ]: A[ j+1] = A[j] j = j -1 else : A[ j+1] = temp elif user == "Dsc" or user == "Dsc" : while j>=0 and temp > A[ j ]: A[ j+1] = A[j] j = j -1 else : A[ j+1] = temp for i in A : B += [ i ] print(B)
Output :-
Enter a list :- [2,1,8,7,6,4,3,9,5]
Enter order you want (Asc/Dsc):- asc
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
Enter a list :- [2,1,8,7,6,4,3,9,5]
Enter order you want (Asc/Dsc):- Dsc
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>>
Enter a list :- [7,8,6,4,2,9,5,1,3,4,7,8,9,5,6,4,1,2,3]
Enter order you want (Asc/Dsc):- Asc
[1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]
>>>
Post a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )