George Jacob Flamburis George Jacob Flamburis - 22 days ago 6
Python Question

list Index error on "Risk" dice game

I'm trying to make a function that gives the win/loss ratio of a roll of number of dice in the game of Risk.

For those who don't know, in Risk there's an attacker and defender where the attackers maximum die is compared to maximum die of the defender, and this repeats for each pair of dice until the defender no longer has dice left. If the attacker wins, the defender loses 1 army, and if the defenders die is equal or greater, the attacker loses 1 army.

So if I run the code I should get

result([1, 4, 5], [3, 2])

(0, -2)

where the attacker lost two because 5>3 and 4>2.

When I try and run my code, I get a list index error, any help in fixing the error is greatly appreciated.

def result(n,m):
while len(n)>len(m):
n = n[:-1]
while True:
for i in m:
if n[i] > m[i]:
second -= 1
elif n[i] <= m[i]:
first -= 1
return (first,second)


In your for i in m loop, the values of i are the contents of m, not the indices of m. In your example, the first time through that loop i is the first value of m, which is 3, so your conditional if n[i] > m[i] is doing if n[3] > m[3]. 3 is out of the range of indices of m, hence IndexError.