Last answered:

11 Oct 2021

Posted on:

08 Oct 2021

0

Is this also a valid solution?

def two_sum(l, target):
    '''Two sum'''

for i in range(len(l)):
        for j in range(len(l)):
            if i == j:
                continue
            elif l[i] + l[j] == target:
                return [i,j]

1 answers ( 0 marked as helpful)
Instructor
Posted on:

11 Oct 2021

1

Hello Nadezhda,

In the beginning of the solution video, Giles speaks of exactly this 'brute force' approach. Writing some code to test whether it works is therefore further practice and it serves you well.

Have you tried testing it yourself - writing the code in a Jupyter Notebook cell, running it and trying with some sample data? (after all, testing your code for flaws is an integral part of programming). The comforting news is that - yes, indeed - the code works and delivers the necessary solution. Nevertheless, part of becoming a skilled programmer is to be able to work on your solution and better it, if possible. To that end, here are two suggestions --

  1. Instead of having two for-loops from 1 to len(l), you can have the outer loop from 1 to len(l) and the inner loop from i+1 to len(l). This would mean you no longer need the first if-check (i == j). Moreover, your code checks every pair of numbers in the list two times (why is that? - you can use a small example and convince yourself that is the case) and that is more computationally expensive - one check is enough. Try putting this advice to code.

  2. It is strongly recommended to pay attention to Giles's solution, as it is an optimal solution to the task. After watching the lecture videos on Big-O notation, you can determine that the brute force solution is O(n^2) and Giles' solution is much better - O(n).

Hope that has helped!

Best,
A. The 365 Team

Submit an answer