1

Here is my program I want to find the weather it is a sum string or not based on the following condition 1)the string length must be >3 example:"12358" --- 1+2=3,2+3=5,3+5=8 I tried this program I am getting the index error please help me.Thank you in adavnce.

Given below is my code:

y="12358"
for i in range(len(y)-1):
    if y[i]+y[i+1]==y[i+2]:
        print "sum stringgg"
1

1 Answer 1

1

The upper bound of the range should be the length of y minus 2 instead to accommodate the comparison with the item of the index plus 2. You should also convert each character in the string to an integer for arithmetic addition and comparison. Finally, you should use the for-else construct to break whenever the former two digits do not add up to the latter digit, and only output 'sum string' if the loop finishes without break:

y = "12358"
digits = list(map(int, y))
for i in range(len(digits) - 2):
    if digits[i] + digits[i + 1] != digits[i + 2]:
        break
else:
    print('sum string')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.