Home > database >  IndexError: string index out of range even though the point exists in the given string
IndexError: string index out of range even though the point exists in the given string

Time:11-13

The program receives an input of a number containing 6 symbols, and if the sum of the first three digits is the same as the sum of the second three digits, then the number is considered lucky.

This is the code I have now, and it works with every number except those that start with 0 and I'm not sure how to fix it:

a = int(input())
n = str(a)
m = (n[0]), (n[1]), (n[2])
s = (n[3]), (n[4]), (n[5])
if  str(sum(int(x) for x in m)) == str(sum(int(x) for x in s)):
    print('Lucky')
else:
    print('Regular')

CodePudding user response:

When you convert a number with leading zeros to an integer and then back to a string, you get the integer represented in standard base-10 notation...without leading zeros:

>>> n = '012345'
>>> str(int(n))
'12345'

Instead, convert the digits of the string to integers to maintain the length and leading zeros:

>>> a = '012345'
>>> n = [int(d) for d in a]
>>> n
[0, 1, 2, 3, 4, 5]

As an aside, you can then check for the sums with list slicing:

if sum(n[:3]) == sum(n[3:]):

CodePudding user response:

Just take the input directly as a string, without str and int:

n = input()

m, s = n[:3], n[3:]
if  sum(map(int, m)) == sum(map(int, s)):
    print('Lucky')
else:
    print('Regular')
  • Related