Katkat

Read and Critique a Short Python Function That Randomly Swaps List Elements

EliseAISoftware Engineer · Technical Screen

Last updated

A code-reading exercise: assess a short Python function that walks a list and swaps each element with a randomly chosen position at or before it. Tests tracing unfamiliar code, reasoning about whether every ordering is equally likely, input-type edge cases such as strings, and practical code-review judgment.

At the end of a 30-minute software engineer phone screen, the interviewer shares a short snippet and asks what you think of it. It is reproduced here in Python:

def foo(a):
 for i in range(len(a)):
 j = math.floor(random.random() * (i + 1))
 temp = a[i]
 a[i] = a[j]
 a[j] = temp
 return a

Assume math and random are the Python standard-library modules. Read the function and give your assessment as you would in a code review: what it does, whether it does that correctly, and what you would change.

Clarifying Questions

  • What will callers pass as a: always a list, or sometimes a string or another kind of sequence?
  • Do callers expect their own list to change, or a new object back?
  • What is the result used for? Is it enough that every outcome is equally likely, or must outcomes also be impossible to predict?

Hints

Hint 1

Trace a tiny input: Run the loop by hand on a three-element list and note which values `j` can take at each step.

Hint 2

Count the outcomes: Count how many equally likely sequences of `j` values the loop can produce, and compare that with the number of possible orderings of the input.

Follow-up questions

  • Suppose `j` were drawn from the whole list on every iteration instead of from `0` to `i`. Would every ordering still be equally likely? Why?
  • How would you test, in code, that this function is unbiased?
  • How would you use it to reorder the characters of a string?
  • Would you use it to shuffle the deck in an online card game where players must not be able to predict the order? What would you change?