Python程序未提供输出

时间:2020-10-24 23:26:56

标签: python python-3.x

我一直在尝试写出一个问题出生日。假设人们进入一个空房间直到一对人过生日。平均而言,一场比赛之前,有多少人必须进入?编写一个程序Birthday.py,该程序接受试验(int)作为命令行参数,运行试验实验以估计此数量-每个实验都涉及对个体进行采样直到一对 他们中的一个人过生日,并将值写到标准输出中。我的麻烦一直是获得输出。如果我在命令终端中输入1000,则应该输出24,但它不会给出任何信息。

DAYS_PER_YEAR = 365
    
    # Accept trials (int) as command-line argument.
    trials = int(sys.argv[1])
    
    # Set count, denoting the total number of individuals sampled across the trials number of
    # experiments, to 0.
    total = 0
    
    for i in range(trials):
        # Perform trials number of experiments, where each experiment involves sampling individuals
        # until a pair of them share a birthday...
    
        # Setup a 1D list birthdaysSeen of DAYS_PER_YEAR Booleans, all set to False by default. This
        # list will keep track of the birthdays encountered in this experiment.
        birthdaysSeen = stdarray.create1D(DAYS_PER_YEAR, False)
        while True:
            # Sample individuals until match
            n = stdrandom.uniformInt(0, 364)
            # Increment count by 1.
            total += 1
    
            # Set birthday to a random integer from [0, DAYS_PER_YEAR).
            birthday = stdrandom.uniformInt(0, DAYS_PER_YEAR)
    
            if birthdaysSeen[birthday]:
                # If birthday has been encountered, abort this experiment, ie, break.
                break
        else:
            # Record the fact that we are seeing this birthday for the first time.
            birthdaysSeen[birthday] = True
    # Write to standard output the average number of people that must be sampled before a match,
    # as an int.
    stdio.writeln(count // trials)

4 个答案:

答案 0 :(得分:1)

在Python中,您可以

print(count // trials)

几乎所有数据结构都定义了__repr__()__str()__方法。

由于counttrials应该是纯数字数据类型,因此print()应该可以解决问题

答案 1 :(得分:1)

您的while循环有一个else,它将变成无限循环。选中此行以与if而不是while匹配:

    else:
        # Record the fact that we are seeing this birthday for the first time.
        birthdaysSeen[birthday] = True

此外,结尾处的打印文字应该是total // trials而不是count // trials

答案 2 :(得分:1)

我建议使用print()代替stdio.writeln()

答案 3 :(得分:0)

stdio.writeln不是内置的Python函数。使用print或从sys模块导入stdout并像这样写:

from sys import stdout

stdout.write(count // trials + "\n")

\n是换行符。 print自动添加换行符。 sys.stdout.write不会。