for n in [2, 4, 6, 8]:
print(n * 5)
10 20 30 40
# Don't run this cell until after you've guessed what it does!
actions = ["ate", "slept", "drank"]
feelings = ["happy", "energized", "confused"]
for k in range(len(actions)):
print("I " + actions[k] + " and I am " + feelings[-k-1] + ".")
I ate and I am confused. I slept and I am energized. I drank and I am happy.
def missing_number(nums):
for n in range(1, len(nums) + 2):
if n not in nums:
return n
# Should be 3
missing_number([1, 2, 6, 4, 5])
3
# Should be 6
missing_number([7, 2, 3, 5, 9, 8, 4, 1])
6
# Ignore this code
def int_to_list(n):
return [int(i) for i in str(n)]
int_to_list(5457623898234113)
[5, 4, 5, 7, 6, 2, 3, 8, 9, 8, 2, 3, 4, 1, 1, 3]
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))
True
What if I accidentally swap two digits?
luhns_algorithm(int_to_list(5475623898234113))
False
Now Luhn's algorithm can tell me the credit card number is invalid, which likely means I made a typo.