我在前缀和算法中有一个问题

问题描述 投票:0回答:1
import time,random

n=int(input("put your number:"))

X=[random.randint(-999,999) for i in range(n)]

print(X)
#pr1 start
before1 = time.clock()
def prefixSum1(X, n):   # code for prefixSum1
    for i = 0 to n-1 do
        S[i] = 0
        for j = 0 to i do
            S[i]=S[i]+X[j]      
    return (S)
after1 = time.clock()
#pr2 start
before2 = time.clock()
def prefixSum2(X, n):   # code for prefixSum2
    S[0]= X[0]
    for i = 1 to n-1 do
        S[i]=S[i-1]+X[i]
    return (S)
after2 = time.clock()
#
random.seed()   
print(after1 - before1)
print(after2 - before2)

这是我的代码,我想做的是,我从-999到999随机生成数组X,并检查两种算法的时间。但是每当我运行代码时,它就会显示>

Makefile:6: recipe for target 'py3_run' failed
    make: *** [py3_run] Error 1
      File "Main.out", line 11
        for i = 0 to n-1 do
              ^

SyntaxError: invalid syntax

我不知道我的代码有什么问题。我试图在互联网上找到,但似乎它们和我一样...

python algorithm prefix
1个回答
1
投票

您的代码未对for循环使用有效的python语法; for语句的文档中清楚地描述了语法。简而言之,您需要更改

for

to

for i = 0 to n-1 do

for i in range(n - 1):

to

for i = 1 to n-1 do

您可以查看for i in range(1, n - 1): 的文档以了解其工作原理。

© www.soinside.com 2019 - 2024. All rights reserved.