您如何确定先前输入中整数的输入数量?骰子游戏

How do you determine the number of inputs from an integer in a prior input? Dice game

问题: 安东尼娅和大卫正在玩游戏。 每个玩家以 100 分开始。 该游戏使用标准的六面骰子并以回合形式进行。在一轮中,每个玩家 掷一个骰子。骰子较低的玩家失去较高骰子上显示的点数。如果 两位玩家掷出相同的数字,任何一位玩家都不会丢失任何分数。 编写程序确定最终分数。

输入规格 输入的第一行包含整数n(1≤n≤15),这是轮次 将播放。在接下来的 n 行中的每一行,将是两个整数:该轮安东尼娅的掷骰, 接着是 space,然后是该轮的 David 掷骰。每个卷将是一个整数 1 到 6(含)之间。 输出规格 输出将由两行组成。在第一行,输出 Antonia 拥有的点数 所有回合结束后。在第二行,输出 David 拥有的点数 所有回合结束后。

我的许多问题之一是使程序列出第一个输入指定的正确输入数。

这是我目前的情况:

rounds = input()
score1 = input()[0:3]
score2 = input()[0:3]
score3 = input()[0:3]
score4 = input()[0:3]

game = [score1, score2, score3, score4]

antonia = 100
david = 100


for scores in game:
    roll = game
    a = game[0]
    d = game[2]
    if a > d:
        antonia -= int(d[0])
    elif d < a:
        david -= int(a[2])
    elif a == d:
        break
print(antonia)
print(david)

我知道我只具体要求一件事,但是有人能完成这个挑战并解释最好的方法吗?

我显然不会为你解决这个类似家庭作业的任务,而是执行 n 轮(在你的情况下
n = rounds) 您应该使用 for 循环,就像您在程序中使用 range:

rounds = input()
for i in range(rounds):
    ...

这将被执行 rounds 次 (0...rounds-1)。 i 将是索引。

一种方法:

rounds = input()

players = [100, 100] 

for round in range(rounds): 
    ri = raw_input() # get the whole line as a string
    # split the input, then convert to int
    scores = [int(i) for i in ri.split()] 
    # compute the players scores
    if scores[0] > scores[1]: players[1] -= scores[0] 
    elif scores[1] > scores[0]: players[0] -= scores[1] 

# print the result
print " ".join(map(str, players)) 
# or simply : 
# print players[0]  
# print players[1]    

这是我的菜鸟回答:

rounds = int(raw_input("Number of rounds: "))
david=[]
antonia=[]


for i in range(rounds):
    score = str(raw_input("Enter Antonia's score, leave a space, \
    enter David's score:"))
    david.append(int(score[0]))
    antonia.append(int(score[2]))

def sum(player):
    s=0
    for i in range(len(player)):
        s+=player[i]
    return s

s1 = sum(david)
s2 = sum(antonia)

for j in range(rounds):
    if david[j] > antonia[j]:
        s1-=david[j]
    elif antonia[j] > david[j]:
        s2-=antonia[j]

print s1
print s2

基本上,每当你不知道你有多少次迭代(你不知道轮数,你只知道它在 1 到 15 之间,我没有考虑)你应该使用一些东西喜欢 while i<nr of rounds,或者正如我们的同事告诉您的那样 for i in range(rounds)

此外,无论何时进行输入,都应使用 raw_input 而不是输入(在 python 2.7 中)。我不认为 [0,3]score1 = input()[0:3] 中是必要的。