Advanced Functions Test

For this test, you should use the built-in functions to be able to write the requested functions in one line.

Problem 1

Use map to create a function which finds the length of each word in the phrase (broken by spaces) and return the values in a list.

The function will have an input of a string, and output a list of integers.


In [31]:
def word_lengths(phrase):
    return map(lambda x: len(x), phrase.split())

In [32]:
word_lengths('How long are the words in this phrase')


Out[32]:
[3, 4, 3, 3, 5, 2, 4, 6]

Problem 2

Use reduce to take a list of digits and return the number that they correspond to. Do not convert the integers to strings!


In [194]:
def digits_to_num_w_strings(digits):
    return int(reduce(lambda x,y: str(x) + str(y), digits))

def digits_to_num(digits):
    return reduce(lambda x, y: x*10+y, digits)

In [195]:
digits_to_num([3,4,3,2,1]) # should output 34321


Out[195]:
34321

Problem 3

Use filter to return the words from a list of words which start with a target letter.


In [81]:
def filter_words(word_list, letter):
    return filter(lambda x: x[0] is letter, word_list)

In [82]:
l = ['hello','are','cat','dog','ham','hi','go','to','heart']
filter_words(l,'h')


Out[82]:
['hello', 'ham', 'hi', 'heart']

Problem 4

Use zip and list comprehension to return a list of the same length where each value is the two strings from L1 and L2 concatenated together with connector between them. Look at the example output below:


In [83]:
def concatenate(L1, L2, connector):
    return [elem1 + connector + elem2 for elem1, elem2 in zip(L1, L2)]

In [84]:
concatenate(['A','B'],['a','b'],'-') # expected output: ['A-a', 'B-b']


Out[84]:
['A-a', 'B-b']

Problem 5

Use enumerate and other skills to return a dictionary which has the values of the list as keys and the index as the value. You may assume that a value will only appear once in the given list.


In [192]:
def d_list(L):
    return_dic = {}
    for i,v in enumerate(L):
        return_dic[v] = i
    return return_dic

def d_list_one_zip(L):
    # the trick is that you can create a dict from a list of tuple
    return dict(zip(L, range(0,len(L))))

def d_list_one(L):
    return dict([(v,i) for i,v in enumerate(L)])

In [193]:
d_list_one(['a','b','c']) # expected output: {'a':0, 'b':1, 'c':2}


Out[193]:
{'a': 0, 'b': 1, 'c': 2}

Problem 6

Use enumerate and other skills from above to return the count of the number of items in the list whose value equals its index.


In [155]:
def count_match_index(L):
    print len([vals for vals in enumerate(L) if vals[0] == vals[1]])

In [156]:
count_match_index([0,2,2,1,5,5,6,10]) # should output 4


4

Great Job!