emaan daavis
emaan daavis

Reputation: 15

Issue in not getting the expected output while iterating through array

I have the following code. The output currently I am receiving is not the expected output. The pseudocode I am trying to solve is described below.

   for each i in 1 · · · N do
         TEi = fmob(Li)
         TCi= fc(Li)
         TUi =fd(Li) 
         return 

enter image description here

Python code

def optimal_partition():                   
 TE=[10,1,3]
 TC=[2,3,1]
 TU=[2,3,1]

 N = len(TU)-1
 SUMS = [0] * N
 for j in range(N):
    for i in range(1, j + 1):
        SUMS[j] += TE[i]
    for k in range(j - 1, N + 1):
        SUMS[j] += TC[k]
    SUMS[j] += TU[j]
 return SUMS.index(min(SUMS))

For the above code, I need the expected output to be [16,15]. Thanks, help is highly appreciated.

Upvotes: 0

Views: 52

Answers (2)

Stuart
Stuart

Reputation: 9868

This is a better implementation of the algorithm using list slices instead of nested loops:

def part_sum(TE, TC, TU, j):
    return sum(TE[:j+1]) + sum(TC[j+1:]) + TU[j]

def optimal_partition(TE, TC, TU):
    return min(range(len(TE)), key=lambda j: part_sum(TE, TC, TU, j)) 

TE = [10,1,3]
TC = [2,3,1]
TU = [2,3,1]
print("The sums are: ", [part_sum(TE, TC, TU, j) for j in range(3)])
print("The optimal partition is at:", optimal_partition(TE, TC, TU))

Note that there are 3 sums, not 2, and that the returned value for j uses zero-based indexing. If you want to return a one-based index then just add 1 to the optimal partition result.

Upvotes: 1

quamrana
quamrana

Reputation: 39414

You are suffering from the 0-based indexing syndrome of computing.

Computer Science sometimes uses 0-based indexing and maths, it seems, uses 1-based indexing.

This program seems to give you the expected output:

def optimal_partition():                   
    TE=[10,1,3]
    TC=[2,3,1]
    TU=[2,3,1]

    N = len(TU) - 1
    SUMS = [0] * N
    for j in range(N):
        for i in range(j + 1):
            SUMS[j] += TE[i]
        for k in range(j + 1, N + 1):
            SUMS[j] += TC[k]
        SUMS[j] += TU[j]
    return SUMS

SUMS = optimal_partition()
print(SUMS)
print(SUMS.index(min(SUMS)))

Output:

[16, 15]
1

Upvotes: 0

Related Questions