My function is set to return a dictionary. When called, it returns the dictionary. However, if I call the function from within another function, it returns a list.
`
def draw(self, num: int) -> dict:
drawn_dict = {}
if num > len(self.contents):
return self.contents
else:
while num >= 1:
drawn_num = self.contents.pop(random.randint(0, len(self.contents) - 1))
drawn_dict.setdefault(drawn_num, 0)
drawn_dict[drawn_num] =1
num -= 1
return drawn_dict
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
matches = 0
full_match = 0
count = 0
print(hat.draw(num_balls_drawn))
print(hat.draw(5))
`
When I call the draw function and print the result, I get the dictionary as expected. But when the draw function is called and result is printed within the experiment function, I get a list.
CodePudding user response:
What is a type of the self.contents
? I thing it is the list
and this is answer to your question :-)
def draw(self, num: int) -> dict:
drawn_dict = {}
if num > len(self.contents):
return self.contents # <- THIS
else:
while num >= 1:
drawn_num = self.contents.pop(random.randint(0, len(self.contents) - 1))
drawn_dict.setdefault(drawn_num, 0)
drawn_dict[drawn_num] =1
num -= 1
return drawn_dict
CodePudding user response:
I realized the issue. I was calling the draw function before experiment function, and by calling draw, I was editing the self.contents list which affected its length thereby triggering the "if num> len(self.contents)". So function works as expected when I don't modify the list before actually using it!