python-checkio/IceBase/count-inversions.py

26 lines
967 B
Python
Raw Normal View History

2020-01-02 17:30:27 +01:00
def count_inversion(sequence):
"""
Count inversions in a sequence of numbers
"""
sequence = list(sequence)
ordered_sequence = sorted(sequence)
inversions = 0
for index, number in enumerate(ordered_sequence):
if sequence.index(number) == index:
continue
inversions += sequence.index(number) - index
sequence.insert(index, sequence.pop(sequence.index(number)))
return inversions
if __name__ == '__main__':
print("Example:")
print(count_inversion([1, 2, 5, 3, 4, 7, 6]))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert count_inversion((1, 2, 5, 3, 4, 7, 6)) == 3, "Example"
assert count_inversion((0, 1, 2, 3)) == 0, "Sorted"
assert count_inversion((5, 3, 2, 1, 0)) == 10, "Reversed"
assert count_inversion((99, -99)) == 1, "Two numbers"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")