def print_primes(limit):
for i in range(2, limit+1):
if is_prime(i):
print i
But how do we implement is_prime?
def is_prime(n):
found_factor = False
possible_factor = 2
while not found_factor and not too_large(n, possible_factor):
if divisible_by(n, possible_factor):
found_factor = True
else:
possible_factor = possible_factor + 1
return not found_factor
But what about divisible_by and too_large?
def divisible_by(n, d):
return (n % d) == 0
def too_large(n, d):
return d * d > n
>>> chr(65)
'A'
>>> ord('B')
66
x = 'hello' >>> for i in range(len(x)): ... print 'The character at position %d is %s' % (i, x[i]) ... The character at position 0 is h The character at position 1 is e The character at position 2 is l The character at position 3 is l The character at position 4 is o
def is_palindrome(s):
return s == reverse(s)
>>> is_palindrome('uneven')
False
>>> is_palindrome('amanaplanacanalpanama')
True
But how do we implement reverse?
def reverse(s):
reversal = ''
for c in s:
reversal = c + reversal
return reversal
>>> shift_cipher('HELLO', 3)
'KHOOR'
>>> shift_cipher('KHOOR', -3)
'HELLO'
How do we implement shift_cipher?
def shift_cipher(s, shift_amount):
shifted = ''
for c in s:
shifted = shifted + shift_letter(c, shift_amount)
return shifted
And how about shift_letter?
# assumes that letter is uppercase
def shift_letter(letter, shift_amount):
position = ord(letter) - ord('A')
shifted = (position + shift_amount) % 26
return chr(shifted + ord('A'))