Hello World! An Invitation to Computer Science

Lecture Slides

Strings in Python
Thursday April 10, 2008


Key ideas from last time


Prime example continued

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

String


String are compound data


String operations


Palindromes revisited

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

Caesar Cipher

  >>> 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'))