Last active
May 21, 2021 08:38
-
-
Save toritsejuFO/496fda3b1655eac83ef954048838b27c to your computer and use it in GitHub Desktop.
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
# Required function | |
def shuffle_class(pupils, pupils_to_move): | |
if pupils == None or type(pupils) != list or len(pupils) == 0 or type(pupils_to_move) != int: | |
return [] | |
# For this solution's approach, normally, we would just take the absolute value of the pupils to move, | |
# but we also take the modulus, just in case, to avoid index out of range edge case, and also avoid round trips | |
to_move = abs(pupils_to_move) % len(pupils) | |
if pupils_to_move == 0 or to_move == 0: | |
return pupils | |
back_to_front = True if pupils_to_move > 0 else False | |
length = len(pupils) | |
# We split, join (swapped) and return on the fly | |
if back_to_front: | |
return pupils[ (length - to_move) :] + pupils[ 0 : (length - to_move)] | |
else: | |
return pupils[ to_move : ] + pupils[ 0 : to_move] | |
if __name__ == '__main__': | |
pupils = [8, 5, 3, 7] | |
pupils_to_move = 2 | |
shuffled_pupils = shuffle_class(pupils, pupils_to_move) | |
print(shuffled_pupils) | |
assert shuffled_pupils == [3, 7, 8, 5] | |
pupils_to_move = -1 | |
shuffled_pupils = shuffle_class(pupils, pupils_to_move) | |
print(shuffled_pupils) | |
assert shuffled_pupils == [5, 3, 7, 8] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for your feedback @meekg33k, really appreciate it.
Yes, there are other ways to move the elements around without creating a new array.
I wanted to try something different other than sorting in place, so I used this method because the new array created is returned immediately (ending the function call), and in the scope of the function the
pupils
list passed in would be released when the function ends/exits. It was my thought that that would be optimal enough for space complexity (and this was done because I was trying to avoid tackling time complexity).Thanks for considering my solution for the $20 prize. I've indicated interest in the raffle draw via sending a DM on twitter. Thank you again.