Reputation: 23
I keep getting the IndexError: string index out of range
, and am wondering what I'm doing wrong with the code.
inFile=open('pa7.cards','r')
cardnum=inFile.readline().strip()
def main():
while cardnum!='99999':
Step1(cardnum)
def CheckLen(num):
if len(num)>=13 and len(num)<=16:
return True
else:
return False
def Step1(num):
total=0
for i in range(len(num)-2,0,-2):
if eval(num[i]*2)>=10:
i=eval(num[i])*2
i=str(i)
i=eval(i[0])+eval(i[1])
total+=i
else:
total+=i
return total
def Step2(num):
total=0
for i in range(len(num)-1,0,-2):
total+=i
return total
def Step3(num):
total=Step1(num)+Step2(num)
if total%10==0:
return True
else:
return False
##def DetermineType(num):
main()
This is what the input file looks like:
4388576018402626
4388576018410707
37271983
99999
This is the error:
Traceback (most recent call last):
File "C:/Users/Andrew/Desktop/pa7.py", line 47, in <module>
main()
File "C:/Users/Andrew/Desktop/pa7.py", line 18, in main
Step1(cardnum)
File "C:/Users/Andrew/Desktop/pa7.py", line 30, in Step1
i=eval(i[0])+eval(i[1])
IndexError: string index out of range
Upvotes: 0
Views: 54
Reputation: 23
def Step1(num):
total=0
for digit in num[-2:0:-2]:
digit=int(digit)
if int(num[digit])*2>=10:
x=int(num[digit])*2
x1=str(x)
x2=int(x1[0])+int(x1[1])
total+=x2
else:
x=int((num[digit]))
total+=x
return total
Upvotes: 0
Reputation: 336138
You're doing a few Bad ThingsTM there.
The source of your error is that i
is built by taking a digit from your "number string", doubling it and converting it back to a string (so "8"
becomes "16"
).
Then you try and access i[1]
- which is out of range if i
is only 1 character long.
But there are more problems - reusing the name i
within the for
loop, using eval()
(shudder!) where int()
would do, iterating over a string using range()
instead of slices...
For example,
for i in range(len(num)-2,0,-2):
should be
for digit in num[-2:0:-2]:
Upvotes: 1