Python Forum
How to resolve Index Error in my code?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to resolve Index Error in my code?
#1
This is the code
MAX, MIN = 1000, -1000


# Returns optimal value for current player
# (Initially called for root and maximizer)
def minimax(depth, nodeIndex, maximizingPlayer,
            values, alpha, beta):
    # Terminating condition. i.e
    # leaf node is reached
    if depth == 3:
        return values[nodeIndex]

    if maximizingPlayer:

        best = MIN

        # Recur for left and right children
        for i in range(0, 2):

            val = minimax(depth + 1, nodeIndex * 2 + i,
                          False, values, alpha, beta)
            best = max(best, val)
            alpha = max(alpha, best)

            # Alpha Beta Pruning
            if beta <= alpha:
                break

        return best

    else:
        best = MAX

        # Recur for left and
        # right children
        for i in range(0, 2):

            val = minimax(depth + 1, nodeIndex * 2 + i,True, values, alpha, beta)
            best = min(best, val)
            beta = min(beta, best)

            # Alpha Beta Pruning
            if beta <= alpha:
                break

        return best

    # Driver Code


if __name__ == "__main__":
    scr = []  # List for Leaf Nodes
    x = int(input("Enter total number of leaf nodes="))
    for i in range(0,x):
        y = int(input("Enter Leaf Value: "))
    scr.append(y)



    print("The optimal value is :", minimax(0, 0, True, scr, MIN, MAX))
I am just trying to modify this code :
https://www.geeksforgeeks.org/minimax-al...a-pruning/
by allowing user to enter the leaf nodes itself.
But I am getting this error : File "C:\Users\Hp\PycharmProjects\lab4\Hilclimbing.py", line 15, in minimax return values[nodeIndex]
IndexError: list index out of range
Reply
#2
(May-21-2021, 11:02 PM)codify110 Wrote: This is the code
MAX, MIN = 1000, -1000


# Returns optimal value for current player
# (Initially called for root and maximizer)
def minimax(depth, nodeIndex, maximizingPlayer,
            values, alpha, beta):
    # Terminating condition. i.e
    # leaf node is reached
    if depth == 3:
        return values[nodeIndex]

    if maximizingPlayer:

        best = MIN

        # Recur for left and right children
        for i in range(0, 2):

            val = minimax(depth + 1, nodeIndex * 2 + i,
                          False, values, alpha, beta)
            best = max(best, val)
            alpha = max(alpha, best)

            # Alpha Beta Pruning
            if beta <= alpha:
                break

        return best

    else:
        best = MAX

        # Recur for left and
        # right children
        for i in range(0, 2):

            val = minimax(depth + 1, nodeIndex * 2 + i,True, values, alpha, beta)
            best = min(best, val)
            beta = min(beta, best)

            # Alpha Beta Pruning
            if beta <= alpha:
                break

        return best

    # Driver Code


if __name__ == "__main__":
    scr = []  # List for Leaf Nodes
    x = int(input("Enter total number of leaf nodes="))
    for i in range(0,x):
        y = int(input("Enter Leaf Value: "))
    scr.append(y)



    print("The optimal value is :", minimax(0, 0, True, scr, MIN, MAX))
I am just trying to modify this code :
https://www.geeksforgeeks.org/minimax-al...a-pruning/
by allowing user to enter the leaf nodes itself.
But I am getting this error : File "C:\Users\Hp\PycharmProjects\lab4\Hilclimbing.py", line 15, in minimax return values[nodeIndex]
IndexError: list index out of range

Well, line 15 in your code is
best = MIN
so I suspect that you have not shown us the relevant code.

What is the size of values? What is the value of nodeIndex? Why do you believe that the index value you are using is valid? Why is "depth == 3" considered the terminating condition? At what level of recursion are you? Why do you think that the computation nodeIndex * 2 + i will always be in range? Have you heard of "code comments"? You give us a piece of code with no overview of what it is trying to do, what values it has, or anything useful, and want us to analyze it?

I'll take a stab at trying to execute this, and if I learn anything, I'll get back to you. But the question is ill-specified.
Reply
#3
I tried running it, and the first thing it did was ask me for the total number of leaf nodes. Since you did not specify what value you gave, no further testing is possible.
Reply
#4
I was playing around with it. Look at line 56. Notice the indentation. That's wrong. Fix it.

Hint: add some print statements to your code. When I printed out the value, it was [n] where n was the last number I had typed. What happened to the others? Well, you wrote the wrong code.

To improve the user experience, I changed the input line to be
y = int(input("Enter Leaf Value "+ str(i + 1) + "/" + str(x) + ": "))
and I added this line just before your line 10 (the if depth == 3 line)
print("minmax(depth=", depth, ", nodeindex=", nodeIndex, ", ", maximizingPlayer, ", ", values, ", ", alpha, ", ", beta, ")"
    )
I still get errors because I have no idea what the purpose of the code is, or what it is working on, but it is clear where your basic error is. Fix that (I did in mine). Here's my output:
Output:
Enter total number of leaf nodes=4 Enter Leaf Value 1/4: 11 Enter Leaf Value 2/4: 12 Enter Leaf Value 3/4: 13 Enter Leaf Value 4/4: 14 minmax(depth= 0 , nodeindex= 0 , True , [11, 12, 13, 14] , -1000 , 1000 ) minmax(depth= 1 , nodeindex= 0 , False , [11, 12, 13, 14] , -1000 , 1000 ) minmax(depth= 2 , nodeindex= 0 , True , [11, 12, 13, 14] , -1000 , 1000 ) minmax(depth= 3 , nodeindex= 0 , False , [11, 12, 13, 14] , -1000 , 1000 ) minmax(depth= 3 , nodeindex= 1 , False , [11, 12, 13, 14] , 11 , 1000 ) minmax(depth= 2 , nodeindex= 1 , True , [11, 12, 13, 14] , -1000 , 12 ) minmax(depth= 3 , nodeindex= 2 , False , [11, 12, 13, 14] , -1000 , 12 ) minmax(depth= 1 , nodeindex= 1 , False , [11, 12, 13, 14] , 12 , 1000 ) minmax(depth= 2 , nodeindex= 2 , True , [11, 12, 13, 14] , 12 , 1000 ) minmax(depth= 3 , nodeindex= 4 , False , [11, 12, 13, 14] , 12 , 1000 )
The last printout shows a node index of 4, which is larger than any valid node index (1..3) of your array of values.
If you really want help, you have to tell us what values you typed in, so we can reproduce your experience. And it is worthwhile to explain what the purpose of the code is, so we know what it should do. It wouldn't hurt if you said "I expected the answer to be <answer value here>, but instead got an exception" so we know what was expected. You might indicate that the nodes form a tree structure, and explain how the index relates to the tree structure.
Reply
#5
I am implementing alpha-beta pruning which is an optimization of the min-max algorithm used in game theory. Alpha-beta pruning helps to reduce computation time.

The code is available here: https://www.geeksforgeeks.org/minimax-al...a-pruning/
I just want the user to enter the leaf node values instead of the fixed values as in the link above.

After the leaf nodes inputs i.e ( 3, 5, 6, 9, 1, 2, 0, -1 }, The code should print value is : 5 .
Reply
#6
Apologies! Let me put the details
Depth 3 is considered as the terminating condition because the tree on which we are implementing this algorithm has a depth of 3. NodeIndex * 2 + i will always be in range because here nodeindex is always zero and only i is incrementing to make nodeindex increase in value.

And sorry index error is initially on line 11.
So for example I put the following inputs :
x = 8 (number of leaf nodes)
scr = { 3, 5, 6, 9, 1, 2, 0, -1 };


1st iteration :

nodeindex=0 , depth = 0, values:[-1]

2nd iteration :

nodeindex=0 , depth = 1, values:[-1]

3rd iteration :

nodeindex=0 , depth = 2, values:[-1]

4th iteration:
nodeindex=0 , depth = 3, values:[-1]

Line 11 runs: return values[nodeIndex]
Value returned to line 20 and finally to line 60.


After this, I see the index error(list out of range) at line 11.
Reply
#7
That helps a lot. I also added statements to print the result on each return statement, and got
Output:
Enter total number of leaf nodes=8 Enter Leaf Value 1/8: 3 Enter Leaf Value 2/8: 5 Enter Leaf Value 3/8: 6 Enter Leaf Value 4/8: 9 Enter Leaf Value 5/8: 1 Enter Leaf Value 6/8: 2 Enter Leaf Value 7/8: 0 Enter Leaf Value 8/8: -1 minimax(depth= 0 , nodeindex= 0 , True , [3, 5, 6, 9, 1, 2, 0, -1] , -1000 , 1000 ) .minimax(depth= 1 , nodeindex= 0 , False , [3, 5, 6, 9, 1, 2, 0, -1] , -1000 , 1000 ) ..minimax(depth= 2 , nodeindex= 0 , True , [3, 5, 6, 9, 1, 2, 0, -1] , -1000 , 1000 ) ...minimax(depth= 3 , nodeindex= 0 , False , [3, 5, 6, 9, 1, 2, 0, -1] , -1000 , 1000 ) ... => [ 0 ] 3 ...minimax(depth= 3 , nodeindex= 1 , False , [3, 5, 6, 9, 1, 2, 0, -1] , 3 , 1000 ) ... => [ 1 ] 5 .. => 5 ..minimax(depth= 2 , nodeindex= 1 , True , [3, 5, 6, 9, 1, 2, 0, -1] , -1000 , 5 ) ...minimax(depth= 3 , nodeindex= 2 , False , [3, 5, 6, 9, 1, 2, 0, -1] , -1000 , 5 ) ... => [ 2 ] 6 .. => 6 . => 5 .minimax(depth= 1 , nodeindex= 1 , False , [3, 5, 6, 9, 1, 2, 0, -1] , 5 , 1000 ) ..minimax(depth= 2 , nodeindex= 2 , True , [3, 5, 6, 9, 1, 2, 0, -1] , 5 , 1000 ) ...minimax(depth= 3 , nodeindex= 4 , False , [3, 5, 6, 9, 1, 2, 0, -1] , 5 , 1000 ) ... => [ 4 ] 1 ...minimax(depth= 3 , nodeindex= 5 , False , [3, 5, 6, 9, 1, 2, 0, -1] , 5 , 1000 ) ... => [ 5 ] 2 .. => 2 . => 2 => 5 The optimal value is : 5
This does not correspond to your output, but since I made no real changes in the code, I'm putting the code here:
MAX, MIN = 1000, -1000
 
def indent(depth):
    for i in range(depth):
       print(".",sep="", end="")

# Returns optimal value for current player
# (Initially called for root and maximizer)
def minimax(depth, nodeIndex, maximizingPlayer,
            values, alpha, beta):

    indent(depth)
    print("minimax(depth=", depth, ", nodeindex=", nodeIndex, ", ", maximizingPlayer, ", ", values, ", ", alpha, ", ", beta, ")"
    )

    # Terminating condition. i.e
    # leaf node is reached
    if depth == 3:
        indent(depth)
        print(" => [", nodeIndex, "] ", values[nodeIndex])
        return values[nodeIndex]
 
    if maximizingPlayer:
 
        best = MIN
 
        # Recur for left and right children
        for i in range(0, 2):
 
            val = minimax(depth + 1, nodeIndex * 2 + i,
                          False, values, alpha, beta)
            best = max(best, val)
            alpha = max(alpha, best)
 
            # Alpha Beta Pruning
            if beta <= alpha:
                break
        indent(depth)
        print(" => ", best)
        return best
 
    else:
        best = MAX
 
        # Recur for left and
        # right children
        for i in range(0, 2):
 
            val = minimax(depth + 1, nodeIndex * 2 + i,True, values, alpha, beta)
            best = min(best, val)
            beta = min(beta, best)
 
            # Alpha Beta Pruning
            if beta <= alpha:
                break
        indent(depth)
        print(" => ", best)
        return best
 
    # Driver Code
 
 
if __name__ == "__main__":
    scr = []  # List for Leaf Nodes
    x = int(input("Enter total number of leaf nodes="))
    for i in range(0,x):
        y = int(input("Enter Leaf Value "+ str(i + 1) + "/" + str(x) + ": "))
        scr.append(y)
 
 
 
    print("The optimal value is :", minimax(0, 0, True, scr, MIN, MAX))
I do not understand why MIN and MAX are global variables, but I didn't try to debug the code. Looking at the output, perhaps you can figure out why it does not deliver the same result as you indicated that it should. I am very suspect of your use of MIN and MAX which you never change. But that's just a guess.

The key takeaway here is the use of print statements to tell you what is really happening.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  pyscript index error while calling input from html form pyscript_dude 2 938 May-21-2023, 08:17 AM
Last Post: snippsat
  Index error help MRsquared 1 739 May-15-2023, 03:28 PM
Last Post: buran
  [split] How to resolve version conflicts in Python? atonalwilson 1 950 May-04-2023, 09:02 AM
Last Post: buran
  How to resolve version conflicts in Python? taeefnajib 0 873 Apr-27-2023, 08:37 PM
Last Post: taeefnajib
  How to resolve my problem in Pycharm? bshoushtarian 0 821 Sep-26-2022, 11:45 AM
Last Post: bshoushtarian
  I'm getting a String index out of range error debian77 7 2,280 Jun-26-2022, 09:50 AM
Last Post: deanhystad
  Solving equation equal to zero: How to resolve the syntax error? alexfrol86 3 1,894 Feb-21-2022, 08:58 AM
Last Post: deanhystad
  Python Error List Index Out of Range abhi1vaishnav 3 2,239 Sep-03-2021, 08:40 PM
Last Post: abhi1vaishnav
  win32com — How to resolve “AttributeError: xlUp” for Excel files? JaneTan 2 4,129 Aug-18-2021, 05:27 AM
Last Post: snippsat
  Index error - columns vs non-column Vinny 3 4,848 Aug-09-2021, 04:46 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020