# lab10.py
# YOUR NAME(S) AND NETID(S) HERE
# DATE COMPLETED HERE
"""Loop functions for lab 10"""
def isprime(p):
"""Returns: True if p a prime, False otherwise
i.e. p is at least 2 and is divisible by only 1 and itself
Precondition: p is an int"""
assert type(p) == int, `p`+' is not an int'
if p < 2:
return False # CHANGE THIS EXPRESSION, IF NECESSARY
if p == 2:
return False # CHANGE THIS EXPRESSION, IF NECESSARY
# Return False if some integer in 2..p-1 divides p
k = 0 # CHANGE THIS EXPRESSION, IF NECESSARY
# inv: p is not divisible by integers in 2..k-1
while k < p:
if False: # CHANGE THIS EXPRESSION
return False
k= k+1
# no integer in 2..p-1 divides p
return False # CHANGE THIS EXPRESSION, IF NECESSARY
# HINT: chr(x) turns an int into a letter
# ord(x) turns a letter into a number
def prime_chars():
"""Returns: a string that contains each capital letter (in 'A'..'Z')
whose numerical representation is prime.
For example, since 67 is a prime, and the letter 'C',
is represented by 67 (since ord('C') is 67), the string should
contain 'C'. But it should not contain 'B", since ord('B') is 66,
not a prime."""
s = NONE # CHANGE THIS EXPRESSION
c = '' # CHANGE THIS EXPRESSION
# inv: string s contains each capital in 'A'..c-1,
# where 'c-1' means the character alphabetically preceding
# c, whose numerical representation is prime
while c <= ' ': # CHANGE THIS EXPRESSION
if False: # CHANGE THIS EXPRESSION
s = s + '' # CHANGE THIS EXPRESSION
# Increment to next letter
# Change to number, increment, and back to letter
c = chr(ord(c) + 1)
# post: s contains each capital in 'A'..'Z' whose rep is a prime
return s
def count_letter(c, s):
"""Returns: number of times character c appears in string s
Precondition: s, c are strings. len(c) == 1"""
assert type(s) == str, `s`+' is not a string'
assert type(c) == str and len(c) == 1, `c`+' is not a character'
# STUB: IMPLEMENT ME
# you must use a while loop and must include its invariant
# (don't use str's count function (except for testing))
return 0 # CHANGE THIS, IF NECESSARY
# OPTIONAL FUNCTION
def count_all_letters(s1, s2):
"""Returns: number of times the characters in s1 appear in s2
Each letter in s1 is treated separately. Duplicates are ignored.
Example: count_all_letters('aaab', 'ac') is 3
Example: count_all_letters('aeiou', word) gives the number of
vowels in string word (for some definitions of vowels)
Precondition: s1, s2 are strings"""
assert type(s1) == str, `s1`+' is not a string'
assert type(s2) == str, `s2`+' is not a string'
# STUB: IMPLEMENT ME
# Hint: Don't nest one while loop in another; use count_letter as
# a helper function
return 0 # CHANGE THIS, IF NECESSARY