总和最大路径算法提供了意外的解决方案

时间:2019-05-02 22:33:16

标签: python python-3.x algorithm graph

在我的输入numbers[3][2] == 62中,一切正常的算法都能正常工作 但是numbers[3][2] == 63算法给我带来意想不到的结果,我无法理解这个原因。 我尝试设计这样的算法,您只能输入非素数,并且只能走root > leftchildroot > rightchild 一些例子:

10
20 23
40 50 60
65  60 69 80

10 +20+50+69 = 149对一个 10 +0(23) + 60+80 = 150错了,我们不能走素数!

我尝试调试该算法的几乎所有部分,但我不明白问题的原因


import sys


numbers = [
       [10],
     [20, 23],
    [40, 50, 60],
  [10, 20, 63, 80]
]


def IsNotPrime(a ): # 
    sayac = 0
    if(a == 0 or a == 1 ):
        sayac = sayac +1
    else:
        for i in range(2,a):
            if(a % i == 0 ):
                sayac = sayac +1
            else:
                sayac = sayac
    if(sayac == 0):
        return False# prime
    else:
        return True # non prime

def bigger(a,b):
    if(a>b ):
        return a
    elif(b>=a ):
        return b


for i in range((len(numbers)-2),-1,-1): 
    for j in range (0,(len(numbers[i]))):
        a = numbers[i][j]#root
        b = numbers[i+1][j]#left chield
        c = numbers[i+1][j+1]#right chield
        if( IsNotPrime(a) and IsNotPrime(b) and IsNotPrime(c) ):
            numbers[i][j] = (a + bigger(b,c))

        elif(IsNotPrime(a) and IsNotPrime(b)):
               numbers[i][j] = (a + b)

        elif( IsNotPrime(a) and IsNotPrime(c) ):
               numbers[i][j] = (a + c)


print( numbers[0][0])

代码给出结果90,但 在这种情况下,我期望结果为143 10+20+50+63 = 143(最大总和路径只能从根到点运行,并且不能行走素数)。

1 个答案:

答案 0 :(得分:0)

您没有检查单个数字是否为质数。您正在检查运行总计。 50 + 63 = 113(这是质数),因此不允许使用该路径。