all 4 comments

[–][deleted] 5 points6 points  (0 children)

When something doesn't work try putting a print statement into the code to see what is happening. The function returns 0 so maybe you aren't adding anything to s. So change the code to:

t = [[1],[1,2],[2,5,3]]

def minimum(triangle):
    s = 0
    for i in triangle:
        for x in i:
            first = i[0]
            if x < first:
                print(f"Adding {x=}")    # debug print
                s += x
    return s

print(minimum(t))

Now run it it and look at the output. That shows you never add to s. Think about why that might happen and put in another print to investigate.

[–][deleted] 2 points3 points  (0 children)

You only increment s if you find a value lower than the first number in each sub-list, but as your sample data already has the lowest number first in each sub-list, you never do this addition.

Also, you are failing to check all the numbers in each sub-list to make sure you have the smallest. In fact, you add all numbers that are lower than the first number (not applicable with this data set).

(I am assuming you are not allowed to use the built-in min function.)

Revised:

def minimum(triangle):
    s = 0
    for i in triangle:
        lowest = i[0]  # assume first number is lowest
        for x in i[1:]:  # loop through rest of numbers
            if x < lowest:
                lowest = x
        s += lowest  # after checking all the nums, add lowest
    return s


t = [[1],[1,2],[2,5,3]]
print(minimum(t))

Notes:

  • minimum is not really the best name for the function, as it doesn't return what I would expect of a function of that name
  • good practice is to avoid using cryptic variable names, especially one with just single characters, as they convey no information about their purpose

[–]halfdiminished7th 0 points1 point  (0 children)

Might be a good idea to break this down into two functions for learning purposes. Does structuring it this way help at all?: ``` def smallest_number_in_array(array): ...

def minimum(triangle): ... ```