dimanche 28 février 2021

Return statement being skipped even though line above it is run [duplicate]

I have a strange problem when trying to return a value from a function. Basically my recursive function will enter the "if" when the base case is reached. Otherwise will go through the else statement and call itself again. It will (always) end up reaching the base case after several recursions. So I place the "return"inside the "if" statement.

In the output I see that it correctly enters in the "if" statement, as I can see the value of "MinCutEdges" being printed, from the explicit print(MinCutEdges) sentence. However the ouput of the function call is "None".

def ContractEdges(edgelist):
    if RemovedEdges == EdgesToBeRemoved:
        MinCutEdges = len(edgelist)
        print("MinCutEdges is: %d" % MinCutEdges)   # I can see the correct output
        return MinCutEdges                          # gets skipped (even if i put return "hi") 
    else:
        edge = RandomChooseEdge(edgelist)
        a = len(edgelist)
        min_v = min(edge[0],edge[1])
        k =[]
        for i in range(a):
            if edgelist[i][0] in edge:
                edgelist[i][0] = min_v
                if edgelist[i] == edge or edgelist[i] == reversed(edge):
                    k += [i]
            if edgelist[i][1] in edge:
                edgelist[i][1] = min_v
        reduced = ReduceArray(edgelist, k)
        RemovedEdges += 1
        ContractEdges(reduced)


### Run
print(ContractEdges(edgelist))

Output:

MinCutEdges is 20

None

Aucun commentaire:

Enregistrer un commentaire