Skip to content

Instantly share code, notes, and snippets.

@Fredpwol
Last active May 18, 2021 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fredpwol/3aa69dad0f58905431aeba1e3472600f to your computer and use it in GitHub Desktop.
Save Fredpwol/3aa69dad0f58905431aeba1e3472600f to your computer and use it in GitHub Desktop.
Class Shuffle problem
from collections import deque
def shuffleClass(arr, n):
if arr is None or len(arr) == 0: return []
if n is None: return arr
arr = deque(arr)
if n >= 0:
for _ in range(n % len(arr)):
arr.appendleft(arr.pop())
else:
for _ in range(abs(n) % len(arr)):
arr.append(arr.popleft())
return list(arr)
print(shuffleClass([2,3], 3))
@meekg33k
Copy link

Hello @Fredpwol, thank you for participating in Week 6 of #AlgorithmFridays.

Not a bad attempt at a solution for Apex College; I like your use of the deque data structure - for more efficient removal/insertion operations. However, your solution failed the following test cases:

  • When arr is an empty list and n has a negative value. Ideally your solution should return an empty list but it throws a IndexError: pop from an empty deque error on line 14.

  • The other test your solution doesn't pass is for cases where n has a value greater than the size of the arr. For such cases, your solution returns the arr. For example, shuffleClass([2, 3], 3); // yours would return [2, 3] instead of [3, 2]. The expectation is that when the value of n is greater than the arr, you should think of it as shuffling the entire pupils list for as many times as is possible until n becomes less than the size of arr. In mathematical terms, that would be n= n % arr.length.

I understand that this solution was made with a lot of assumptions of how certain things should be implemented but I think it's always best to check in with your interviewer before making assumptions on how edge cases should be implemented. I wrote about that in this article, you might find it helpful.

Apart from that, this was a decent attempt. Please let me know your thoughts.

@Fredpwol
Copy link
Author

Hello @meekg33k, thanks for the feedback I really appreciate it, and I've updated my code to handle edge cases where I failed at. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment