Last active
August 29, 2015 14:27
-
-
Save onyekaa/42d7ae3dbfed2f353b35 to your computer and use it in GitHub Desktop.
Get the highest and lowest possible number if you could only swap one number at a time.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def swap(num): | |
# convert the number to a string so that we can split into a list | |
# and get the index for each | |
old_arr = list(str(num)) | |
# empty list where we'll push the newly swapped numbers for comparison | |
new_arr = [] | |
# we then loop through the length of the list of numbers and get the | |
# index, pairing it up with the next index in line | |
# for instance: for index 0, we pair it with 1, then 0 with 2 etc. | |
for i, val in enumerate(old_arr): | |
for j, val in enumerate(old_arr): | |
if i != j: | |
# as long as i and j aren't the same e.g 0,0 we copy the | |
# initial list (so that our swaps don't affect it) | |
new_list = list(old_arr) | |
# pythonic method for swapping list positions using indexes | |
new_list[i], new_list[j] = new_list[j], new_list[i] | |
# get rid of any number-string whose first index is 0 | |
if new_list[0] != '0': | |
# We then join the split arrays and convert them back to integers | |
new_arr.append(int(''.join(new_list))) | |
# now we check that the highest number in the list is not the original | |
if max(new_arr) == num: | |
print "The highest possible swap is already {} but the lowest swap is {}".format(num, min(new_arr)) | |
elif min(new_arr) == num: | |
print "The lowest possible swap is already {} but the highest swap is {}".format(num, max(new_arr)) | |
# if the input is not the highest or the lowest we go ahead to print: | |
else: | |
print "The lowest possible swap is {} and the highest swap is {}".format(min(new_arr), max(new_arr)) | |
# example for running the file directly | |
swap(10900) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment