for n in [2, 4, 6, 8]:
print(n * 5)
def sum_squares_for(values):
total = 0
for v in values:
total += v**2
return total
# 3^2 + 4^2 + 5^2
sum_squares_for([3, 4, 5])
def sum_squares_while(values):
total = 0
j = 0
while j < len(values):
total += values[j]**2
j += 1
return total
# 3^2 + 4^2 + 5^2
sum_squares_while([3, 4, 5])
def missing_number(nums):
for ...:
if n not in nums:
return n
# Should be 3
missing_number([1, 2, 6, 4, 5])
# Should be 6
missing_number([7, 2, 3, 5, 9, 8, 4, 1])
# Ignore this code
def int_to_list(n):
return [int(i) for i in str(n)]
int_to_list(5457623898234113)
def luhns_algorithm(cc):
# Step 1
check_digit = cc[-1]
even_sum = 0
for i in range(0, len(cc), 2):
# Step 2
even_element = cc[i] * 2
if even_element > 9:
even_element = even_element - 9
# Step 3
even_sum += even_element
# Step 4
odd_sum = 0
for i in range(1, len(cc) - 2, 2):
odd_sum += cc[i]
# Step 5
total_sum = even_sum + odd_sum
# Step 6
return (total_sum + check_digit) % 10 == 0
luhns_algorithm(int_to_list(5457623898234113))
What if I accidentally swap two digits?
luhns_algorithm(int_to_list(5475623898234113))
Now Luhn's algorithm can tell me the credit card number is invalid, which likely means I made a typo.
for x in range(1, 5):
for y in range(1, 5):
print(str(x) + ' x ' + str(y)
+ ' = ' + str(x * y))
movies = [['21 Jump Street', 'Grown Ups', 'Mall Cop'],
['Paranormal Activity', 'Nightmare on Elm Street'],
['Crazy Rich Asians', 'Trainwreck', 'Crazy, Stupid, Love']]
for genre in movies:
for movie in genre:
print(movie)
print('---')
movies[0][2]