George Jacob Flamburis - 8 months ago 42

Python Question

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):`

first=0

second=0

n=(sorted(n))[::-1]

m=(sorted(m))[::-1]

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

else:

break

return (first,second)

Answer

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`

.

Source (Stackoverflow)