I am having a difficulty with my socks program and getting the following error.
Traceback (most recent call last):
File "/home/latchwood/socks.py", line 39, in <module>
total += how_many(num_pairs)
File "/home/latchwood/socks.py", line 13, in how_many
sock_index = random.randint(0, len(all_socks) - 1)
File "/usr/lib/python3.5/random.py", line 218, in randint
return self.randrange(a, b+1)
File "/usr/lib/python3.5/random.py", line 196, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0,0, 0)
It is supposed to count the number of socks that you need to choose to get a certain number of pairs. Then you do repeated experiments and take the average. Normally the first experiment or two works, and then the error comes up.
Example input.
How many pairs do you want? 2
How many experiments to perform? 10
Here is the code.
import random
sock_drawer = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] * 4
def how_many(num_pairs_wanted,
all_socks=sock_drawer):
print('start of experiment')
unpaired_socks = []
number_chosen = 0
pairs = 0
while True:
number_chosen += 1
sock_index = random.randint(0, len(all_socks) - 1)
color = all_socks.pop(sock_index)
print('sock number: ', number_chosen)
print('chose: ', color)
if color in unpaired_socks:
pairs += 1
print('PAIR!', color)
print('number of pairs: ', pairs)
unpaired_socks.remove(color)
if pairs == num_pairs_wanted:
print('You have enough pairs.')
print('Total socks chosen was ', number_chosen)
print()
return number_chosen
else:
unpaired_socks.append(color)
print('unpaired socks', unpaired_socks)
print()
num_pairs = int(input('How many pairs do you want? '))
num_experiments = int(input('How many experiments to perform? '))
total = 0
for experiment in range(num_experiments):
total += how_many(num_pairs)
print('Average number of socks ', total / num_experiments)
What can I do to fix this please?
Here is the example of one of the successful experiments before it starts to fail.
start of experiment
sock number: 1
chose: yellow
unpaired socks ['yellow']
sock number: 2
chose: purple
unpaired socks ['yellow', 'purple']
sock number: 3
chose: red
unpaired socks ['yellow', 'purple', 'red']
sock number: 4
chose: red
PAIR! red
number of pairs: 1
unpaired socks ['yellow', 'purple']
sock number: 5
chose: green
unpaired socks ['yellow', 'purple', 'green']
sock number: 6
chose: green
PAIR! green
number of pairs: 2
You have enough pairs.
Total socks chosen was 6
Aucun commentaire:
Enregistrer un commentaire