Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: 'string index out of range'

Tags:

python

I had a quick search but couldn't find anything that helped my problem.

I'm trying to make a program that takes the first 5 numbers and sources their product, and if that product is the largest found thus far it is set as such.

My code is:

string = str(integer)

x = 0
largest = 0
stringlength = len(string)

while x < stringlength:
    a = int(string[x])
    b = int(string[x+1])
    c = int(string[x+2])
    d = int(string[x+3])
    e = int(string[x+4])
    if (a*b*c*d*e > largest):
        largest = a*b*c*d*e
        print(largest)
    x += 1

print(largest)

I excluded the integer value itself, but for reference it is 1000 digits long. Whenever I try to run this code I get "IndexError: string index out of range". Can anyone help?

like image 786
ApocalypticNut Avatar asked Dec 07 '25 22:12

ApocalypticNut


1 Answers

string = str(integer)

x = 0
largest = 0
stringlength = len(string)

while x < stringlength-4: # going to -5 would be out of rangue
    a = int(string[x])
    b = int(string[x+1])
    c = int(string[x+2])
    d = int(string[x+3])
    e = int(string[x+4])
    if (a*b*c*d*e > largest):
        largest = a*b*c*d*e
        print(largest)
    x += 1

print(largest)
like image 104
Benjamin Toueg Avatar answered Dec 10 '25 10:12

Benjamin Toueg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!