Week 5: Exercise Solutions

Exercise 5.1

def hamming_distance(string_1, string_2):
    """Calculate the Hamming distance of two strings."""
    distance = 0
    for i in range(len(string_1)):
        if string_1[i] != string_2[i]:
            distance = distance + 1
    print("The Hamming distance between", string_1,
          "and", string_2, "is", distance)


hamming_distance("great", "groan")
hamming_distance("alpha", "alpha")

Exercise 5.2

def square(n):
    """Calculate the square of a number."""
    return n**2


print("3**2 =", square(3))
print("(-27)**2 =", square(-27))

Exercise 5.3

Here I give two possible solutions.

def string_to_vector_1(string):
    """
    Change a space separated list of
    numbers to a list of floats
    """
    string_list = string.split()
    float_list = []
    for s in string_list:
        float_list.append(float(s))
    return float_list


def string_to_vector_2(string):
    """
    Change a space separated list of
    numbers to a list of floats
    """
    vector_list = string.split()
    for i in range(len(vector_list)):
        vector_list[i] = float(vector_list[i])
    return vector_list


print(string_to_vector_1("1.0 2.0 4.0 5.5 6.786"))
print(string_to_vector_2("1.0 2.0 4.0 5.5 6.786"))