0

so this program predicts the first winning move of the famous Game of Nim. I just need a little help figuring out this problem in the code. The input file reads something like this.

3
13 4 5
29 5 1
34 4 50

The first number would represent the number of lines following the first line that the program has to read. So if the case was

2
**13 4 5
29 5 1** 
34 4 50

it would only read the next two lines following it.

So far this has been the progress of my code

def main ():

nim_file = open('nim.txt', 'r')
first_line = nim_file.readline()
counter = 1
n = int (first_line)
for line in nim_file:
    for j in range(1, n):
        a, b, c = [int(i) for i in line.split()]
        nim_sum = a ^ b ^ c
        if nim_sum == 0:
            print ("Heaps:", a, b, c, ": " "You Lose!")
        else:
            p = a ^ nim_sum
            q = b ^ nim_sum 
            r = c ^ nim_sum
            if p < a:
                 stack1 = a - p
                 print ("Heaps:", a, b, c, ": " "remove", stack1, "from Heap 1")
            elif q < b:
                 stack2 = b - q
                 print ("Heaps:", a, b, c, ": " "remove", stack2, "from Heap 2")
            elif r < c:
                 stack3 = c - r
                 print ("Heaps:", a, b, c, ": " "remove", stack3, "from Heap 3")
            else:
                 print ("Error")
nim_file.close()

main() 

I converted the first line number to an int and tried to set a while loop at first with a counter to see that the counter wouldn't go above the value of n but that didn't work. So any thoughts?

Suliman Sharif
  • 607
  • 1
  • 9
  • 26

2 Answers2

1

If the file is small, just load the whole thing:

lines = open('nim.txt').readlines()
interesting_lines = lines[1:int(lines[0])+1]

and continue from there.

Thomas Erker
  • 358
  • 1
  • 9
0

Yo have two nested for statement, the second of which doesn't make much sence. You need to leave just one, like this:

for _ in range(n):
    a, b, c = [int(i) for i in nim_file.readline()]

and remove for line in nim_file. Also check out this question and consider using the with statement to handle the file opening/closing.

Community
  • 1
  • 1
Milan Milanov
  • 412
  • 1
  • 8
  • 27