Skip to content

Latest commit

 

History

History
87 lines (62 loc) · 2.94 KB

File metadata and controls

87 lines (62 loc) · 2.94 KB

The Two Sum Problem

So, this problem is available on LeetCode.

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice.

Some pointers

Iterating a list

You can loop through the content of a list called nums with:

for number in nums:
    # Do something
    print(f"This element of the list is {number}")

for loop docs

Iterating a list and tracking the index

You can iterate through the items in a list whilst also tracking the index with the enumerate function:

for index, number in enumerate(nums):
    # Do something
    print(f"The element at index {index} is {number}")

enumerate doc

Checking whether something is in a list

If you want to check whether a number is in a list, you can use the in keyword. You can check the opposite by prepending in with the keyword not:

a_list = [1, 2, 3, 4, 5]
if 1 in a_list:
    print("1 is in here!")
else:
    print("1 is not in here! :(")

if 'elephant' not in a_list:
    print("There's no elephant!")
else:
    print("There IS an elephant")

Official lists tutorial

Checking the index of a value

If you want to know where something is in a list you use the .index function on a list:

a_list = [1, 2, 3, 'elephant', 4, 5]
if 'elephant' in a_list:
    index = a_list.index('elephant')
    print(f"The elephant is in index {index}")

The docs for a list aren't straightforward. Lists have their own method at the top of it's doc, it's also a sequence and so shares the common sequence methods, and it's a mutable sequence so it shares the mutable sequence methods. Just be careful with things like .sort and .reverse, those are 'in place' methods that don't return anything.

Checking equality and inequality

If you want to check that stuff we have the usual suite of logical operators:

if 1 != 2:  # not equal
    print("obvo!")

if 1 == 2:  # equal
    print("major surprise!")

# < is less than
# <= is less than or equal
# > is greater than
# >= is greater than or equal

# Python will let you handle a more mathematically framed logical
# expression like this:
x = 3
if 1 <= x < 4:
    print("x is in range [1, 4)")

You could read about it if you wanted but there's not a lot in there because there's not a lot to say