所以我是一名初学程序员,我正在尝试计算两个骰子加起来的总数为11的卷数。这是我试过的代码,但每次运行时,它给我输出'无'。我在这做错了什么?
from random import randint
def die_roll1():
return(randint(1, 6))
def die_roll2():
return(randint(1,6))
def roll_sum():
sum = die_roll1() + die_roll2()
count = 2
if sum == 11:
return(count)
else:
count +=2
roll_sum()
print("The number of rolls are: ", roll_sum())
答案 0 :(得分:0)
您未在 select
S.code
, S.classname
, S.teacher_.passport as T_PP
, S.teacher_.something as T_ST
, S.teacher_.another as T_AO
, S.maximumpupils as max_p
, S.maximumhours as max_h
from subjectclass S ;
-- result
CODE CLASSNAME T_PP T_ST T_AO MAX_P MAX_H
1 class1 AA1100BB something1 another1 100 16
2 class2 BB2211CC something2 another2 120 25
块中返回roll_sum()
的结果。但是,请考虑使用else
循环,因为简单案例的递归通常是单步的:
while
输出:
import random
tries = 1
while True:
a, b = random.randint(1, 6), random.randint(1, 6)
if a + b == 11:
winning = [a, b]
break
tries += 1
答案 1 :(得分:0)
技术上,您只需要在 else 部分之后返回计数。如果你滚动两个非11,那么结果永远不会递归地通过所有函数调用,所以它会在limbo中丢失并返回 None 。
但是,在这种情况下,您的代码永远不会生成4以外的数字,因为每次滚动11时,您都会将 count 变量重置为2。
这可以通过将计数变量全局(在函数外部),然后在函数内递增来解决。这也可以通过在 while 循环之外声明变量来修复。
答案 2 :(得分:0)
迭代程序几乎总是比递归程序更具可读性,并且你的程序对于这个问题肯定应该是迭代的。其他答案为您提供了迭代解决方案。 但由于没有人告诉你如何纠正自己的(递归)程序,我会这样做。我认为从长远来看,你可以学到一些对你(和其他初学者)有帮助的东西。
这是更正后的代码。
from random import randint
def die_roll():
return(randint(1, 6))
def roll_sum(count):
sum = die_roll() + die_roll()
if sum == 11:
return(count)
else:
count += 2
return roll_sum(count)
# Call roll_sum with 2 as your initial count
roll_sum(2)
<强>解释强>
roll1 = die_roll() roll2 = die_roll() sum = roll1 + roll2
一切顺利!
答案 3 :(得分:0)
以下是几个简单的解决方案,用于计算两个骰子滚动中每个和发生的次数。要回答您的特定问题,您只需要使用“特定解决方案”代替下面的“常规解决方案”。
dice1 = [1,2,3,4,5,6]
dice2 = [1,2,3,4,5,6]
totals = []
for num in dice1:
for roll in dice2:
sumz = str(num+roll)
if [sumz, 0] not in totals:
temp = [sumz, 0]
totals.append(temp)
for item in totals:
for num in dice1:
for roll in dice2:
# General Solution - sum of all roles
sumz2 = str(num+roll)
if sumz2 == item[0]:
item[1] += 1
# Specific Solution - only count number of 11's rolled
if sumz2 == '11':
if item[0] == '11':
item[1] += 1
print(totals)
# Using a dictionary to count
totals = {}
for num in dice1:
for roll in dice2:
sumz = str(num+roll)
if sumz not in totals:
totals[sumz] = 1
else:
totals[sumz] += 1
print(totals)
# using collections
from collections import Counter
# temp list to hold all sumz, including multiple entries of same value
temp = []
for num in dice1:
for roll in dice2:
temp.append(num+roll)
# unsorted dictionary of key value pairs
d = Counter(temp)
list_sorted_by_key = []
for i in sorted (d):
temp2 = (i, d[i])
list_sorted_by_key.append(temp2)
print(list_sorted_by_key)