Skip to main content

Exercises 7.24 Exercises

1.

What do these evaluate to?
  1. 'Python'[1]
  2. 'Strings are sequences of characters.'[5]
  3. len('wonderful')
  4. "Mystery"[:4]
  5. 'p' in 'Pineapple'
  6. 'apple' in 'Pineapple'
  7. 'pear' not in 'Pineapple'
  8. 'apple' > 'pineapple'
  9. 'pineapple' < 'Peach'
Solution.
  1. 'Python'[1]'P'
  2. 'Strings are sequences of characters.'[5]'g'
  3. len('wonderful') → 9
  4. "Mystery"[:4]'Myst'
  5. 'p' in 'Pineapple'True
  6. 'apple' in 'Pineapple'True
  7. 'pear' not in 'Pineapple'True
  8. 'apple' > 'pineapple'False
  9. 'pineapple' < 'Peach'False

2.

In Robert McCloskey’s book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop tries to output these names in order.
prefixes = "JKLMNOPQ"
suffix = "ack"

for p in prefixes:
    print(p + suffix)
Of course, that’s not quite right because Ouack and Quack are misspelled. Can you fix it?

3.

Assign to a variable in your program a triple-quoted string that contains your favorite paragraph of text - perhaps a poem, a speech, instructions to bake a cake, some inspirational verses, etc.
Write a function that counts the number of alphabetic characters in your text and then keeps track of how many are the letter ’e’. Your function should print an analysis of the text like this:
Your text contains 243 alphabetic characters, of which 109 (44.8%) are 'e'.
Solution.
def count(paragraph):
    number_of_e = 0
    total_chars = 0
    for a_char in paragraph:
        if a_char.isalpha():
            total_chars = total_chars + 1
            if a_char == 'e':
                number_of_e = number_of_e + 1

    percent_with_e = (number_of_e / total_chars)
    print(f"Your text contains {total_chars} alphabetic characters of which {number_of_e} ({percent_with_e:.2%}) are 'e'.")



para = '''
"If the automobile had followed the same development cycle as the computer, a
Rolls-Royce would today cost $100, get a million miles per gallon, and explode
once a year, killing everyone inside."
-Robert Cringely
'''

count(para)

4.

Write a function that will return the number of digits in an integer.
Solution.
def numDigits(n):
    n_str = str(n)
    return len(n_str)


print(numDigits(50))
print(numDigits(20000))
print(numDigits(1))

5.

Write a function that reverses its string argument.

6.

Write a function that removes all occurrences of a given letter from a string.

7.

A palindrome is a word that is spelled the same backwards and forwards. For example, “racecar” and “madam” are palindromes. Write a function that recognizes palindromes. (Hint: use your reverse function to make this easy!).
Solution.
def reverse(my_str):
    reversed = ''
    for char in my_str:
        reversed = char + reversed
    return reversed

def is_palindrome(my_str):
    """Returns True if my_str is same forward as backward."""
    if my_str == reverse(my_str):
        return True
    else:
        return False

print(is_palindrome('racecar')) # True
print(is_palindrome('pacecar')) # False
print(is_palindrome('straw warts')) # True
print(is_palindrome('a')) # True
print(is_palindrome('')) # True

8.

Write a function that removes the first occurrence of a string from another string. For example, remove("on", "London") would return "Ldon". Hint: use slices.
Solution.
def remove(substr,theStr):
    index = theStr.find(substr)
    if index < 0: # substr doesn't exist in theStr
        return theStr
    return_str = theStr[:index] + theStr[index+len(substr):]
    return return_str

# These should all print True
print(remove('an', 'banana') == 'bana')
print(remove('cyc', 'bicycle') == 'bile')
print(remove('iss', 'Mississippi') == 'Missippi')
print(remove('egg', 'bicycle') == 'bicycle')

9.

Write a function that removes all occurrences of a string from another string. For example, remove_all("on", "London") would return "Ld"

10.

Write a function that implements a substitution cipher. In a substitution cipher one letter is substituted for another to garble the message. For example A -> Q, B -> T, C -> G etc. Your function should take two parameters: the message you want to encrypt, and a string that represents the mapping of the 26 letters in the alphabet. This mixed-up alphabet is called the cipher. Your function should return a string that is the encrypted version of the message. If a character isn’t in the alphabet, it should remain as is in the encrypted version.

11.

Write a function that decrypts the message from the previous exercise. It should also take two parameters. The encrypted message, and the mixed up alphabet. The function should return a string that is the same as the original unencrypted message.
Solution.
def encrypt(message, cipher):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    encrypted = ''
    for char in message:
        if char in alphabet:
            pos = alphabet.index(char)
            encrypted = encrypted + cipher[pos]
        else:
            encrypted = encrypted + char
    return encrypted

def decrypt(encrypted, cipher):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    decrypted = ''
    for char in encrypted:
        if char in alphabet:
            pos = cipher.index(char)
            decrypted = decrypted + alphabet[pos]
        else:
            decrypted = decrypted + char
    return decrypted


cipher = "badcfehgjilknmporqtsvuxwzy"

encrypted = encrypt('hello world', cipher)
print(encrypted)

decrypted = decrypt(encrypted, cipher)
print(decrypted)

12.

Write a function called remove_dups that takes a string and creates a new string by only adding those characters that are not already present. In other words, there will never be a duplicate letter added to the new string.

13.

Modify this code so it prints each subtotal, the total cost, and average price to exactly two decimal places. Hint: use f-strings.