写一个 Sigma 方程
Write a Sigma equation
我有一个等式,想用不同的值对它的结果求和。我使用 Number = input()
输入一个数字,方程根据索引从输入中获取数字。想要的索引是从 i = 1 到 i = 4。
等式是:Number[i] + Number[i+1]*3 + i
例如,如果我的输入是 Number = 879463
,那么首先 i = 1
: Number[1] + Number[2]*3 + 1
,等于 8 + 7*3 + 1 = 30
然后 i = 2
: Number[2] + Number[3]*3 + 2
.. 等等,直到 i = 4
。
最后将结果求和存入total
.
这是我的代码:
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)
对于这段代码,我得到错误:
IndexError: string index out of range
我的方向是否正确?
# 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.
我有一个等式,想用不同的值对它的结果求和。我使用 Number = input()
输入一个数字,方程根据索引从输入中获取数字。想要的索引是从 i = 1 到 i = 4。
等式是:Number[i] + Number[i+1]*3 + i
例如,如果我的输入是 Number = 879463
,那么首先 i = 1
: Number[1] + Number[2]*3 + 1
,等于 8 + 7*3 + 1 = 30
然后 i = 2
: Number[2] + Number[3]*3 + 2
.. 等等,直到 i = 4
。
最后将结果求和存入total
.
这是我的代码:
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)
对于这段代码,我得到错误:
IndexError: string index out of range
我的方向是否正确?
# 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.