我有一个函数,它有时返回 True,有时返回 False。我如何计算 True 和 False?

时间:2021-06-18 21:36:31

标签: python function count

TLDR: 添加

打印(百())

到这段代码,你会看到函数有时返回True,有时返回False。我如何用循环计算这些?如果我使用 if 语句,它会在所有迭代中返回全部 True 或全部 False... >

我已经为此奋斗了 3 天。这是关于 Automate Boring Stuff 的硬币翻转问题。已经“编程”了 1 个月左右,之前没有经验。

所以,这是返回 False 或 True 的函数。我需要能够以某种方式计算它们。 所以,如果函数被调用 10 次(迭代变量),我需要每次它返回 True 来计算它们。我尝试了 while 循环、if 语句、for 循环,我不明白为什么它不起作用......真的卡住了。

import random


headtails = ['H', 'T']
resultlist = []
current = 1
total = []
count = 0
countlist = []
tries = 1


def hundred():
    global resultlist, current, total, count, countlist, tries, headtails
    for i in range(100):
        x = random.choice(headtails)
        resultlist.append(x)
        if resultlist[i] != resultlist[i-1]:
            current = 0
        else:
            current = current +1
            if current >= 6:
                total.append(current)
                current = 0
    if len(total) != 0:
        return True
    else:
        return False

# function ends here, now we need to call it and count Trues and Falses. 
# How do I do it? This doesn't work:

iterations = 0
number_of_true = 0
overalls = 0

while iterations < 10:
    iterations += 1

    if hundred():
        number_of_true += 1
        overalls += 1
    elif hundred() is False:
        overalls += 1
print(number_of_true, overalls)

好的,我找到了问题但没有解决。如果多次调用该函数

print(hundred())
print(hundred())
print(hundred())
print(hundred())

它们都将是 False 或 True,这意味着它们都指向内存中的相同值。所以,不可能以任何方式迭代它的结果......该死,我该怎么办。只有当我运行/停止程序时才会得到新的结果。

1 个答案:

答案 0 :(得分:1)

每次您想检查 hundred() 是否返回 TrueFalse 时,您都对 overalls 进行了两次调用,这意味着您实际上检查的不是一个结果,而是两个结果。您的 while 循环似乎也没有任何结束条件。此外,您的循环变量不存在,因此您的脚本会引发错误。最后,据我所知,iterations 是不必要的,因为 while iterations < 10: iterations += 1 result = hundred() if result: number_of_true += 1 print(number_of_true, iterations) 无论如何都会跟踪那个数字。我认为最后一部分应该是这样的:

10 10

运行脚本时,它会给出 0 10hundred(),我不确定这是您想要的,但至少循环部分是正确的。如果您对 .conjugate() 有疑问,那么我建议您专门询问另一个问题。我认为它的问题是由于您使用了太多全局变量,其中一些需要在每次调用该函数时重置。

相关问题