Probability Calculator - IndexError: Cannot choose from an empty sequence

My code is here.

Console output is:

Probability: 0.179
..E
======================================================================
ERROR: test_prob_experiment (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/probability-calculator-Geoffrey/test_module.py", line 28, in test_prob_experiment
    probability = prob_calculator.experiment(hat=hat, expected_balls={"yellow":2,"blue":3,"test":1}, num_balls_drawn=20, num_experiments=100)
  File "/home/runner/probability-calculator-Geoffrey/prob_calculator.py", line 39, in experiment
    drawn_balls = hat.draw(num_balls_drawn)
  File "/home/runner/probability-calculator-Geoffrey/prob_calculator.py", line 26, in draw
    drawn = random.choice(list(self.contents))
  File "/usr/lib/python3.8/random.py", line 290, in choice
    raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence

----------------------------------------------------------------------
Ran 3 tests in 0.186s

FAILED (errors=1)

I should mention that switching between using the hat passed as an arg and using a deep-copy so-far hasn’t affected the results of running the code.

This test uses a hat with 19 balls and tries to draw 20. Your code in your draw method does move everything from the possible balls to the contents, but then it draws the balls. That means that you move all 19 to the contents, draw them, and then try to draw the twentieth which fails because the list is empty. You need a better way to handle the draw more than available situation. The spec says to return all the balls in this situation; it does not say you have to draw them individually first.

Copying the hat would have no effect on this problem.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.