Polygon Calculator - resetting contents

Hi,

I am having a strange issue with the Polygon calculator. It works if you run an unlimited amount of tests individually, but cycling through the tests with an experiment cycle it fails on anything over 2 cycles.

I can see that it is altering the variable hat.contents. However when I add in line 41 to reset it I can then do 3 cycles, but no more. I have been looking at it for a while, so any fresh eyes would be appreciated.

import copy
import random

class Hat():

	def __init__(self,**kwargs):
		self.contents=[]
		'''converting dictionary of colours to list of colours'''
		for k, v in kwargs.items():
			for i in range(v):
				self.contents.append(str(k))

	def draw(self, draw_amount):
		self.draw_amount=draw_amount
		self.drawnballs=[]
		'''each seperate drawing of a ball, taking off contents, putting on drawnballs list'''
		for i in range(self.draw_amount):
			number=random.randint(0,len(self.contents)-1)
			self.ball=self.contents.pop(number)
			self.drawnballs.append(self.ball)

		return(self.drawnballs)

	def __str__(self):
		return(str(self.contents))

def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
	results=[]
	success=0
	failed=0
	colours=[]
	'''creating what is supposed to be unchanging version of contents'''
	experiment.contents=hat.contents.copy()

	for k,v in expected_balls.items():
		for i in range(v):
			colours.append(k)

	for i in range(num_experiments):
		hat.draw(num_balls_drawn)
		hat.contents=experiment.contents
		if results==expected_balls:
			success+=1
		else:
			failed+=1

	return(success)


hat = Hat(black=6, red=4, green=3)


probability = experiment(hat=hat, 
                  expected_balls={"red":2,"green":1},
                  num_balls_drawn=5,
                  num_experiments=3)
print(probability)

Take a closer look at how experiment function should work. Remember that it’s supposed to run num_experiments number of experiments, and each of them should be performed in the same way, with only difference coming from the randomness of which balls are actually drawn this time.

Hi, thanks for the response. I can’t say I completely understood what you meant. I managed to get it working though, so its all good.

thank you