用 10 次掷骰子填充列表(掷骰子可以通过获取 1 到 6 之间的随机整数来模拟)
Fill a list with 10 rolls of a dice (the roll of a dice can be simulated by getting random integer between 1 and 6)
作业说我必须显示:
Display all 10 rolls
Display all 10 rolls in backwards order
Display the first and last rolls
Display the sum of the rolls
Display the min and the max value rolled.
我的代码有点用,但我不知道如何让其他代码显示。我不断收到错误代码。这是我目前所拥有的,我删除了一些因为我感到沮丧:
import random
def roll(sides=6):
numRolled = random.randint(1,sides)
return num_rolled
def rollDice():
sides = 6
rolling = True
diceList=[]
while rolling:
numRolled = random.randint(1,sides)
diceList.append(numRolled)
print (numRolled, end="")
if len(diceList) == 10:
rolling = False
return diceList
def main ():
print (rollDice())
print (diceList)
print (rolldice.sort())
print (rollDice[0],rolldice[9])
print (rolldice.min,rolldice.max)
print (rolldice.sum)
main()
您可以使用列表理解来生成一个包含 10 个骰子的列表填充。然后return你想要的结果。
ten_roll_of_dice = [random.randint(1, 6) for _ in range(10)]
print "Display all 10 rolls: ", ten_roll_of_dice
print "Display all 10 rolls in backwards order: ", ten_roll_of_dice[::-1]
print "Display the first and last rolls: %d, %d" % (ten_roll_of_dice[0], ten_roll_of_dice[-1])
print "Display the sum of the rolls: ", sum(ten_roll_of_dice)
print "Display the min and the max value rolled: %d, %d" % (min(ten_roll_of_dice), max(ten_roll_of_dice))
作业说我必须显示:
Display all 10 rolls
Display all 10 rolls in backwards order
Display the first and last rolls
Display the sum of the rolls
Display the min and the max value rolled.
我的代码有点用,但我不知道如何让其他代码显示。我不断收到错误代码。这是我目前所拥有的,我删除了一些因为我感到沮丧:
import random
def roll(sides=6):
numRolled = random.randint(1,sides)
return num_rolled
def rollDice():
sides = 6
rolling = True
diceList=[]
while rolling:
numRolled = random.randint(1,sides)
diceList.append(numRolled)
print (numRolled, end="")
if len(diceList) == 10:
rolling = False
return diceList
def main ():
print (rollDice())
print (diceList)
print (rolldice.sort())
print (rollDice[0],rolldice[9])
print (rolldice.min,rolldice.max)
print (rolldice.sum)
main()
您可以使用列表理解来生成一个包含 10 个骰子的列表填充。然后return你想要的结果。
ten_roll_of_dice = [random.randint(1, 6) for _ in range(10)]
print "Display all 10 rolls: ", ten_roll_of_dice
print "Display all 10 rolls in backwards order: ", ten_roll_of_dice[::-1]
print "Display the first and last rolls: %d, %d" % (ten_roll_of_dice[0], ten_roll_of_dice[-1])
print "Display the sum of the rolls: ", sum(ten_roll_of_dice)
print "Display the min and the max value rolled: %d, %d" % (min(ten_roll_of_dice), max(ten_roll_of_dice))