python函数有时会工作,而其他时候也无法工作

时间:2018-06-01 09:37:47

标签: python eclipse

我在不久前写下了这段代码,然后也遇到了这个问题。我当时忽略了这一点,当我问一位专家'看看它,它工作正常。

问题是,有时程序似乎无法在我的笔记本电脑上运行main(),可能是由于算法有多重。有没有解决的办法?我不想将来继续遇到这个问题。相同的代码在我有限访问的另一台计算机上完美运行。

(P.S。笔记本电脑的问题是MacBook Air 2015,运行程序应该没有问题。而且,它在打印后停止"嗨")

它没有给出错误信息,它只是没有从main()打印任何东西。它应该打印一系列字符串,这些字符串逐渐收敛到"它就像一个黄鼠狼"。在eclipse中,它表明代码仍在处理中,但它不会输出它应该

的任何内容
import random

def generateOne(strlen):
    alphabet = "abcdefghijklmnopqrstuvwxyz "
    res = ""
    for i in range(strlen):
        res = res + alphabet[random.randrange(27)]
    return res

def score(goal, teststring):
    numSame = 0
    for i in range(len(goal)):
        if goal[i] == teststring[i]:
            numSame = numSame + 1
    return numSame / len(goal)

def main():
    goalstring = "methinks it is like a weasel"
    chgoal = [0]*len(goalstring)
    newstring = generateOne(28)
    workingstring = list(newstring)
    countvar = 0
    finalstring = ""
    while score(list(goalstring), workingstring) < 1:
        if score(goalstring, newstring) > 0:
            for j in range(len(goalstring)):
                if goalstring[j] == newstring[j] and chgoal[j] == 0:
                    workingstring[j] = newstring[j]
                    chgoal[j] = 1
                    finalstring = "".join(workingstring)
                    countvar = countvar + 1
                    print(finalstring)
        newstring = generateOne(28)
    finalstring = "".join(workingstring)
    print(finalstring) 
    print(countvar)

print("hi")
if __name__ == '__main__':
    main()
print("ho")

1 个答案:

答案 0 :(得分:1)

你可以优化一下。字符串是不可变的 - 每次将一个字符串附加到字符串时,都会创建一个新字符串并替换旧字符串。使用字符列表 - 如果您可以通过分解和“”分隔符打印字符列表,也不要一直使用"".join()进行打印:

import random

def generateOne(strlen):
    """Create one in one random-call, return as list, do not iterativly add to string"""
    alphabet = "abcdefghijklmnopqrstuvwxyz "
    return random.choices(alphabet,k=strlen)

def score(goal, teststring):
    """Use zip and generator expr. for summing/scoring"""
    return sum(1 if a==b else 0 for a,b in zip(goal,teststring))/len(goal)

def main():
    goalstring = list("methinks it is like a weasel") # use a list
    newstring = generateOne(28) # also returns a list
    workingstring = newstring [:] # copy
    countvar = 0
    while score(goalstring, workingstring) < 1:
        if score(goalstring, newstring) > 0:
            for pos,c in enumerate(goalstring): # enumerate for getting the index
                # test if equal, only change if not yet ok
                if c == newstring[pos] and workingstring[pos] != c: 
                    workingstring[pos] = newstring[pos] # could use c instead
                    countvar += 1
                    print(*workingstring, sep="") # print decomposed with sep of ""  
                                                  # instead of "".join()
        newstring = generateOne(28)

    finalstring = "".join(workingstring) # create result once ... 
                                         # although its same as goalstring
                                         # so we could just assing that one
    print(finalstring) 
    print(countvar)

print("hi")
if __name__ == '__main__':
    s = datetime.datetime.now()
    main()
    print(datetime.datetime.now()-s)
print("ho")

带打印输出的计时非常难以理解。如果我评论print打印中间步骤到最终解决方案并使用`random.seed(42)' - 我得到了我的:

0:00:00.012536
0:00:00.012664
0:00:00.008590
0:00:00.012575
0:00:00.012576

和你的:

0:00:00.017490
0:00:00.017427
0:00:00.013481
0:00:00.017657
0:00:00.013210

我很确定这不会解决你的笔记本电脑问题,但仍然 - 它有点快。