0

我应该编写一个程序来掷骰子五次,但我不能有任何冗余,也不能使用任何类型的循环。我将在此处粘贴练习中的文本。“构建一个 Python 应用程序,以便提示用户输入骰子的面数(龙与地下城式骰子!)之后,它将用该面数掷骰子五次,并将所有五个结果输出到用户掷骰子五次将需要五个重复的代码块——通过使用用户定义的函数掷骰子来消除这种冗余

谁能帮我?

import random

def main():

    diceType = int(input("Enter how many sides the dices will have: "))

    diceRoll1 = random.randint(1,diceType)
    diceRoll2 = random.randint(1,diceType)
    diceRoll3 = random.randint(1,diceType)
    diceRoll4 = random.randint(1,diceType)
    diceRoll5 = random.randint(1,diceType)

    print("The dices read", diceRoll1, diceRoll2, diceRoll3, diceRoll4, diceRoll5)

main()
4

4 回答 4

2

注意:这是一种糟糕的方法。循环的目的是消除冗余。如果没有任何类型的循环,所有解决方案都将是 hacky、难以阅读并且可能效率低下。

import random

def roll5(diceType, remaining_roll=5):

    if remaining_roll == 0:
        return []

    retval = roll5(diceType, remaining_roll - 1)
    retval.append(random.randint(1,diceType))
    return retval

diceType = int(input("Enter how many sides the dices will have: "))

diceRoll1, diceRoll2, diceRoll3, diceRoll4, diceRoll5 = roll5(diceType)
print("The dices read", diceRoll1, diceRoll2, diceRoll3, diceRoll4, diceRoll5)
于 2018-09-28T18:09:00.307 回答
1

使用理解列表

import random
randomList = [random.randint(1,diceType) for _ in range(5)]
diceRoll1, diceRoll2, diceRoll3, diceRoll4, diceRoll5 = randomList
于 2018-09-28T18:16:09.923 回答
0

我会使用该itertools模块。

>>> from itertools import islice, imap, repeat
>>> from random import randint
>>> diceType = 5
>>> list(islice(imap(random.randint, repeat(1), repeat(diceType)), 5))
[5, 5, 4, 5, 4]

repeat创建 1 和diceTypes 的无限序列。imap创建调用结果的无限序列(每次调用都会拉取andrandint(1, diceType)的下一个值作为参数。创建一个仅采用无限序列的前 5 个元素的有限迭代器,并且实际上从有限迭代器中获取值。repeat(1)repeat(diceType)islicelist

同样,不使用itertools,如下(map为简单起见,使用 Python 2 的版本):

map(lambda f: f(1, diceType), [randint]*5)

这将创建一个包含 5 个单独引用的列表,然后映射一个函数,该函数在 1 和该列表randint上调用其参数。diceType

(实际上,itertools可以使用相同的方法简化版本:

list(islice(map(lambda f: f(1, diceType), repeat(randint)), 5))

)

于 2018-09-28T18:12:49.143 回答
0

就个人而言,如果我不能使用任何循环,我会使用一个列表来跟踪已使用和未使用的内容。

diceType = int(input("Enter how many sides the dices will have: "))
lyst = range(1,diceType+1)

diceRoll1 = random.choice(lyst)
lyst.remove(diceRoll1)
diceRoll2 = random.choice(lyst)
lyst.remove(diceRoll2)
diceRoll3 = random.choice(lyst)
lyst.remove(diceRoll3)
diceRoll4 = random.choice(lyst)
lyst.remove(diceRoll4)
diceRoll5 = random.choice(lyst)
lyst.remove(diceRoll5)

print("The dices read", diceRoll1, diceRoll2, diceRoll3, diceRoll4, diceRoll5)

这不是最优雅的解决方案,但我喜欢它的可读性。您从列表中选择了某些内容,然后将其删除。然后再做4次。

于 2018-09-28T18:16:43.347 回答