[英]Python Arithmetic Sequence Sum
How do I make a code that follows this?如何制作遵循此的代码? 1⋅2+2⋅3+3⋅4+…+(n−1)⋅n
For example, if n=5
, the answer is 1⋅2+2⋅3+3⋅4+4⋅5=40.
例如,如果n=5
,则答案是1⋅2+2⋅3+3⋅4+4⋅5=40.
n
cannot be less than or equal to two or more or equal to 1000 n
不能小于或等于 2 或大于或等于 1000
This is my code for now but it doesn't work.这是我现在的代码,但它不起作用。
n = int(input())
if n>= 2 and n<=1000:
sum = 0;
numbers = range(1, n+1)
for amount in numbers:
if (amount % 2 == 1):
sum *= amount
else:
sum += amount
print(sum)
For every number between 1
and n-1
(inclusive), you need to multiply it by the following number, and then sum them all.对于1
到n-1
(含)之间的每个数字,您需要将其乘以以下数字,然后将它们全部相加。 The easiest way to represent this is with a comprehension expression over a range
call:表示这一点的最简单方法是使用range
调用上的理解表达式:
result = sum(i * (i + 1) for i in range(1, n))
You need to reproduce exactly the scheme you give您需要准确复制您给出的方案
def compute(n):
if 2 <= n <= 1000:
total = 0
for amount in range(1, n + 1):
total += amount * (amount - 1)
print(total)
But that's the same as multiplying each with itself+1, if you change the bound to get one step less但这与将每个乘以自身+1 相同,如果您更改界限以减少一步
for amount in range(1,n):
total += amount * (amount + 1)
Then you can use builtin methos sum
and a generator syntax然后你可以使用内置方法sum
和生成器语法
def compute(n):
if 2 <= n <= 1000:
total = sum(nb * (nb + 1) for nb in range(1,n))
print(total)
If you try to approach it mathematically, you can have the answer in a single expression.如果您尝试以数学方式处理它,您可以在一个表达式中得到答案。
Dry run your code.干运行你的代码。 You will see that for n = 5, you are doing as follows:您将看到对于 n = 5,您正在执行以下操作:
Num of Iterations = 6 (1 -> 5+1)
Iteration 1
sum = 0 + 1 = 1
Iteration 2
sum = 1 * 2 = 2
Iteration 3
sum = 2 + 3 = 5
Iteration 4
sum = 5 * 4 = 20
Iteration 5
sum = 20 + 5 = 25
Iteration 6
sum = 25 * 6 = 150
In this, you are completely disregarding the BODMAS/PEMDAS rule of multiplication over addition in the process of regenerating and calculating the series在此,您在重新生成和计算级数的过程中完全无视 BODMAS/PEMDAS 乘法而不是加法的规则
What you need to do is你需要做的是
Iteration 1:
sum = 0 + 2 * 1 = 2
Iteration 2:
sum = 2 + 3 * 2 = 8
Iteration 3:
Sum = 8 + 4*3 = 20
Iteration 4:
Sum = 20 + 5*4 = 40
Here, We have broken the step as follows:在这里,我们将步骤分解如下:
For each iteration, take the product of (n) and (n-1) and add it to the previous value
Also note that in the process, we are first multiplying and then adding.还要注意,在这个过程中,我们是先乘然后加。 ( respecting BODMAS/PEMDAS rule ) So, you need to go from n = 2 to n = 5 and on each iteration you need to do (n-1)*(n) (尊重 BODMAS/PEMDAS 规则)所以,你需要 go 从 n = 2 到 n = 5 并且在每次迭代中你需要做 (n-1)*(n)
As mentioned earlier, the loop is as follows:如前所述,循环如下:
## Checks for n if any
sum = 0
for i in range(2, n):
sum = sum + (i-1)*i
print(sum)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.