Discussion about this post

User's avatar
psiro's avatar

class Found(Exception): pass

def makesum (target: int, nums: list[int]) :

..try:

....for i in range (len(nums)):

......for j in range (i+1,len(nums)):

........if nums[i]+nums[j] == target :

..........raise Found

..except Found :

....return i,j

..return None,None #not reachable as there IS a solution

target = 27

nums = [2,7,11,15,16]

i,j = makesum(target,nums)

print(f"[{i},{j}]")

Python

Bottom up

No calcs repeated (as inner loop always forward of outer loop index)

Considered skipping addition if either number > target, but the addition takes less CPU cycles than the x2 compares.

Breaks as soon as answer found

No posts

Ready for more?