Reputation: 1332
I have an equation and want to sum it's results with different values. I enter a number using Number = input()
and the equation takes numbers from the input according to an index. The wanted indices are from i = 1 to i = 4.
The equation is : Number[i] + Number[i+1]*3 + i
So for example, if my input is Number = 879463
, then firstly for i = 1
: Number[1] + Number[2]*3 + 1
, which equals to 8 + 7*3 + 1 = 30
Then for i = 2
: Number[2] + Number[3]*3 + 2
.. and so on, until i = 4
.
At the end, sum the results and store in total
.
Here is my code:
Number = input()
total = 0
def equation(i,Number):
x = (Number[i] + Number[i+1]*3 + i)
return x
for i in range(len(Number)):
total += equation(i,Number)
print(total)
For this code I get the error:
IndexError: string index out of range
Am I even in the right direction here ?
Upvotes: 0
Views: 132
Reputation: 26
# input is a string
number = input("Enter a number: ")
# Two lists to store values, results and list of numbers
list_of_numbers = []
total = []
# List to store string values to integers
for i in number:
list_of_numbers.append(int(i))
print(f'List = {list_of_numbers}')
# List to store values to total
for i in range(1, len(list_of_numbers)):
result_equation = list_of_numbers[i - 1] + list_of_numbers[i] * 3 + i
print(f'For i = {i}, {list_of_numbers[i - 1]} + {list_of_numbers[i]}*3 + {i} = {result_equation}')
total.append(result_equation)
# Sum values
print(f'Total = {sum(total)}')
# Observation: Most of this code can be erased as it is only used to print values on the screen.
Upvotes: 1