Respuesta :
Answer:
Hi Zoom! Good question. This is particularly useful for learning sorting functions in arrays and user input handling as well. Please find the implementation below.
Explanation:
I have implemented the code in Python 2+. You can save the below code into a file called ArrayDemo.py and then run it from the command line with the command "python ArrayDemo.py". I have declared the demo_array in the code to an array of 10 unsorted integer values to test this. You can change the code if needed to have this array input by user as well and it should work fine.
Note: if you're using Python 3+ then you'll need to change the "raw_input" in the code to just "input" to make it work.
ArrayDemo.py
demo_array = [2,1,3,4,5,7,6,8,10,9]
option = 0
while (option != 4):
option = raw_input("Enter 1 to view list in ascending order, 2 to view list in descending order, 3 to choose specific poisition to view, 4 to quit the application: ")
try:
option = int(option)
if option == 1:
sort_by = 'asc'
print(sorted(demo_array, reverse=False))
elif option == 2:
sort_by = 'desc'
print(sorted(demo_array, reverse=True))
elif option == 3:
position = raw_input("Enter specific position to view (0-9): ")
try:
position = int(position)
if position < 0 or position > 9:
print("Position does not exist")
else:
print(demo_array[position])
except ValueError:
print("Position does not exist!")
elif option == 4:
break
else:
break
except ValueError:
print("Invalid input!")