name = 'billy'
name = name + name
name
Let's try something cool!
f = open('data/words.txt', 'r')
dictionary = f.read().split('\n')
user_word = input('Enter a word (or hit enter to stop): ')
in_count = 0
out_count = 0
while user_word:
if user_word in dictionary:
print(user_word + ' is in the dictionary!\n')
in_count += 1
else:
print(user_word + ' is not in the dictionary.\n')
out_count += 1
user_word = input('Enter a word (or hit enter to stop): ')
print(f'\nWord(s) in dictionary: {in_count}\nWord(s) not in dictionary: {out_count}')
i = 0
while i < 10:
print(i)
i = i + 1
print('blastoff!')
sum_first_n
¶def sum_first_n(n):
j = 1
total = 0
while j <= n:
total += j
j += 1
return total
# 1 + 2 + 3 + 4
sum_first_n(4)
sum_first_n_no_threes
¶def sum_first_n_no_threes(n):
j = 1
total = 0
while j <= n:
# If j is not a multiple of 3
if j % 3 != 0:
total += j
j += 1
return total
# 1 + 2 + 4 + 5
sum_first_n_no_threes(6)
def doubling_time(pop, r):
start = ...
t = 0
while start < 2 * pop:
start = ...
t += 1
return t
def fib(n):
prev, curr = 0, 1
i = 1
while i < n:
prev, curr = curr, prev + curr
i += 1
return curr
fib(7)
fib(243)
It turns out there's a formula that we can use to compute the $n$-th Fibonacci number, without iteration:
$$F_n = \frac{\phi^{n} - (1 - \phi)^{n}}{\sqrt{5}}$$where $\phi = \frac{1 + \sqrt{5}}{2}$ is the "Golden Ratio".
golden = (1 + 5**0.5) / 2
golden
def fib_no_iteration(n):
return int((golden**n - (1 - golden)**n) / (5**0.5))
fib_no_iteration(7)
Let's first define smallest_factor
, a function that takes in a positive integer n
and returns the smallest factor of n
. (This number is prime!)
# One implementation
def smallest_factor(n):
k = 2
while k <= n:
if n % k == 0:
return k
k += 1
# An equivalent implementation
def smallest_factor(n):
k = 2
while n % k != 0:
k += 1
return k
smallest_factor(5)
smallest_factor(24)
Now, let's define prime_factors
, a function that takes in a positive integer n
and prints all of the prime factors of n
.
def prime_factors(n):
while n > 1:
k = smallest_factor(n)
print(k)
n = n // k
prime_factors(22)
prime_factors(144)
name = input('Enter your name: ')
print('Hi, ' + name + '!')
user_word = input('Enter a word (or hit enter to stop): ')
in_count = 0
out_count = 0
while user_word:
if user_word in dictionary:
print(user_word + ' is in the dictionary!\n')
in_count += 1
else:
print(user_word + ' is not in the dictionary.\n')
out_count += 1
user_word = input('Enter a word (or hit enter to stop): ')
print(f'\nWord(s) in dictionary: {in_count}\nWord(s) not in dictionary: {out_count}')