Python basic exercises Chap 6

The introductory work on Python Chapter 6 has some code exercises:

Exercise: Write a function that takes a string that is a presidents name, and returns their birth state. Use a data dictionary like so: {‘George Walker Bush’:’Connecticut’…..}

My Solution: This was pretty straight forward… just take the parameter and return the parameter[key], to they the value returned.

def birth_state(x):
    dic_pres = {'Barack Hussein Obama II':'Hawaii',
 'George Walker Bush':'Connecticut',
 'William Jefferson Clinton':'Arkansas'}
    return dic_pres[x]

print(birth_state("George Walker Bush"))

Exercise: Write a function that takes a phrase and returns a count of the words in the phrase.

Solution:

def wordcount(phrase):
    counter={}
    word_list = phrase.split(" ")
    for word in word_list:
        print(word)
        if word in counter:
            counter[word] += 1
        else:
            counter[word] = 1
    return counter

print(wordcount("all animals are equal but some animals are more equal than others"))

Exercise: Write a function that takes a dictionary with a tuple for the last name,first name as the key and the value is a phone number. The function should prompt the user for the first name & last name and return the phone number.

For example:
phonebook = {(‘Anna’,’Karenina’):'(123)456-7890′,(‘Warner’,’Brian’):’222-333-4444′}
lookup(phonebook)
What is the First name? Brian
What is the Last name? Warner
[output]: 222-333-4444

My Solution:

def lookup(x):
    name_dict = x
    first_n = input("What is the First name? ")
    last_n = input("What is the Last name? ")
    n_key= (last_n,first_n)
    return name_dict[n_key]

phonebook = {('Anna','Karenina'):'(123)456-7890',('Warner','Brian'):'222-333-4444'}
print(lookup(phonebook))

I had a mistake on this one… initially I had the function take **x (a dictionary.) But I got an error on that, so I removed the ** and just used lookup(x) instead. Then it worked. I thought since I was passing in a dictionary it would have to be typed as a dictionary in the function. I was wrong.

Exercise: Remove duplicate values in a list

This actually isn’t a formal exercise but it is so useful, I am adding it as an exercise.

my_list = [2, 4, 6, 7, 2, 10, 20, 6, 7, 20, 20, 20, 10]
print(list(set(my_list)))

By using the set class, we can call our list and we’ll have all duplicates removed… this is due to the immutable nature of the set class.

Exercise: Create a random number guessing game. Prompt the user for a number and if it matches, they won, if it is too low tell them, if it is too high tell them. Repeat until the user wins.

My Solution: I also provided the user to add the range of the game. So if they call guess(10) 10 sets the range from 0 to 10.

import random
def guess(x):
    my_num = random.randrange(0,int(x))

    while True:
        computer = int(input("Enter your guess: "))
        if computer == my_num:
            print("You WON!")
            break
        elif computer > my_num:
            print("Too High")
        else:
            print("Too Low")
guess(10)

I did get caught on one small issue, input gets a string. I googled how to get that as an int and found I should wrap the input with an int function.

Randomness
While not an exercise it’s pretty interesting. Python has some specific functions for random. Here’s some cool ones:

random.shuffle(my_list) where my_list is your list, will rearrange the items in a list.

random.choice(my_list) where my_list will return one random item from the list.

random.sample(my_list, 5) where my_list is a list and the number after it is the samples we want returned. If my_list was a list of 100 objects, it would return 5 random ones from the list.

Leave a Reply

Your email address will not be published. Required fields are marked *