Week 3: Homework Solutions

3.

# To calculate the Hamming distance between two strings
string_1 = input("First string: ")
string_2 = input("Second string: ")
distance = 0
i = 0
# We are assuming the strings are of the same length
while i < len(string_1):
    if string_1[i] != string_2[i]:
        distance = distance + 1
    i = i + 1
print("The Hamming distance is", distance)

Here is a modified version of the program that copes with strings of different lengths:

# To calculate the Hamming distance between two strings
string_1 = input("First string: ")
string_2 = input("Second string: ")
distance = 0
i = 0
# Swap strings if necessary, so len(string_1) <= len(string_2)
if len(string_1) > len(string_2):
    string_1, string_2 = string_2, string_1
while i < len(string_1):
    if string_1[i] != string_2[i]:
        distance = distance + 1
    i = i + 1
# Account for any additional characters in string_2
while i < len(string_2):
    distance = distance + 1
    i = i + 1
print("The Hamming distance is", distance)

4.

# To play the game Fizz Buzz
n = int(input("Which number do you wish to go up to? "))
count = 1
while count <= n:
    rintout = ""
    if ("5" in str(count)) or (count % 5 == 0):
        printout = "fizz "
    if ("7" in str(count)) or (count % 7 == 0):
        printout = printout + "buzz"
    if printout == "":
        printout = str(count)
    print(printout)
    count = count + 1