我正在为一个类运行一些代码,我不知道该做什么,我提交了作业,但是如果我最后不知道该做什么,那是没有帮助的。下面是我正在运行的代码,以尝试跟踪这些测试。这样做的目的是看看你需要多少个孩子才能生下至少一个性别的孩子。然后,程序应该将其存储到一个列表值中,作为boysandgirls_statsx。问题是它不能存储所有的测试。它只记录了大约40 / 100或200 / 1000。我不知道其他测试储存在哪里。我们必须从我们正在使用的一本书中使用stdarray。它跟踪测试的方式类似于python中的列表,但并没有很好地向我解释。谢谢!
import stdio
import random
import sys
import stdarray
numTrials = int(sys.argv[1])
boysandgirls_stats = stdarray.create1D(4, 0)
boys = 0
girls = 0
children = 0
totalChildren = 0
for x in range(numTrials): # Simulation to determine sex
childType = random.randint(0, 1)
if childType == 0:
boys += 1
children += 1
totalChildren += 1
else:
girls += 1
children += 1
totalChildren += 1
for x in range(numTrials): # Keeps track of amount of children needed
if (boys >= 1) and (girls >= 1):
if children <= 5:
boysandgirls_stats[children - 2] += 1
boys = 0
girls = 0
children = 0
else:
boysandgirls_stats[3] += 1
boys = 0
girls = 0
children = 0
avgChildren = totalChildren / numTrials # Calculation for average children
stdio.writeln('Avg # of children: ' + str(avgChildren))
for x in range(len(boysandgirls_stats)):
stdio.writeln(str(x+2) + ' children ' + str(boysandgirls_stats[x]))
发布于 2022-01-31 04:39:41
import sys
import random
## let's put the test inside a function:
def child_test():
girl = False
boy = False
total_children = 0
while not (boy and girl):
total_children += 1
if random.randint(0, 1) == 0:
boy = True
else:
girl = True
return total_children
## now the statistics:
# get the number of trials from user command:
num_trials = int(sys.argv[1])
# for every number of children, log the associated number of tests:
total = 0
indexed_count = {}
for i in range(num_trials):
num_children = child_test()
if num_children not in indexed_count:
indexed_count[num_children] = 0
indexed_count[num_children] += 1
total += num_children
# calculate and output the average:
average = total / num_trials
print(f'average is : {average}')
# show tries per number of children
sorted_indexed_count = sorted(indexed_count.items(), key = lambda x: x[1], reverse = True)
for t in sorted_indexed_count:
print(f' {t[0]} children : {t[1]} tests')
产出:
$ python3 so.py 100000
average is : 3.00812
2 children : 49702 tests
3 children : 25238 tests
4 children : 12401 tests
5 children : 6314 tests
6 children : 3159 tests
7 children : 1528 tests
8 children : 840 tests
9 children : 410 tests
10 children : 214 tests
11 children : 99 tests
12 children : 53 tests
13 children : 18 tests
14 children : 10 tests
15 children : 6 tests
16 children : 6 tests
18 children : 1 tests
17 children : 1 tests
https://stackoverflow.com/questions/70921272
复制相似问题