Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
not_terribly_fast solution in Clear category for Absolute Sorting by dannystaple
def checkio(numbers_array):
# The cheeky short fast thing
# return sorted(numbers_array, key=abs)
if len(numbers_array) == 0:
return []
output = list(numbers_array)
offset = 0
changed = True
# We keep going if there's still digits, or something changed
# Turn on the print statements to see it working.
while changed or offset < len(output) - 1:
# print("Looping with portion {p}, whole {o}".format(
# p=output[offset:],
# o=output))
# Nothings changed in this loop
changed = False
# We're going to check all the items after the current one
for index in range(offset + 1, len(output)):
# If it's greater than that item
if abs(output[offset]) > abs(output[index]):
# Swap it
# print("Making swap")
temp = output[offset]
output[offset] = output[index]
output[index] = temp
changed = True
break
if not changed:
# print("No swap made. Advancing")
offset += 1
# Using offsets since we are mutating the copied output.
# Slicing creates copies - not references.
return output
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
def check_it(array):
if not isinstance(array, (list, tuple)):
raise TypeError("The result should be a list or tuple.")
return list(array)
assert check_it(checkio((-20, -5, 10, 15))) == [-5, 10, 15, -20], "Example" # or (-5, 10, 15, -20)
assert check_it(checkio((1, 2, 3, 0))) == [0, 1, 2, 3], "Positive numbers"
assert check_it(checkio((-1, -2, -3, 0))) == [0, -1, -2, -3], "Negative numbers"
Oct. 30, 2016