Problem scenario
You need to write a Python program to see if a list of unique integers is in order. You can copy the list and sort it to compare the ideal state to the list provided. The program must print out a relevant message if a swap of two numbers can place those two numbers in the correct order. The program must print out if a given number is already in order.
Here are the requirements of the Python program:
- generate a list of numbers (either by random or hard-code a list)
- sort the list
- find if incorrectly placed numbers share a spot with another number that if swapped, both would be in order
Solution
import random
def diff_finder(array):
unsorted_list = array[:]
array.sort()
counter = 0
for i in range(len(array)):
if array[i] != unsorted_list[i]:
if unsorted_list[array.index(unsorted_list[i])] == array[i]:
# if the integer in this position (the array.index(unsorted_list[i]) returns the position of the value of the wrong integer),
# is the value of the correctly-ordered integer in the sorted array
print("ONE SWAP WOULD CORRECTLY PLACE TWO NUMBERS!")
else:
print("It will take more than one swap with this number to get the list in order: " + str(unsorted_list[i]) )
else:
print(str(array[i]) + " is in correct order")
a_list = []
for i in range(10):
a_list.append(random.randint(1,10))
print("This list we are dealing with is " + str(a_list))
diff_finder(a_list)