Python for Data Analysis

Module 1 solutions (lists)


Exercise 1

In [1]:
a=[1,2,3,4,5,6,7,8,9,10]
In [2]:
print(a[2]) #(a)
print(a[2:6]) #(b)
print(a[-1]) #(c)
3
[3, 4, 5, 6]
10

Exercise 2

A function is a reusable sequence of statements that performs a computation. A method is a function defined for an object and that operates on that object. Below, append and remove are methods since they are inherent to list objects.

In [12]:
stocks=[]
stocks.append('IBM')
stocks.append('AAPL')
stocks.append('MSFT')
print(stocks)
['IBM', 'AAPL', 'MSFT']
In [13]:
stocks.remove('IBM')
print(stocks)
['AAPL', 'MSFT']

Exercise 3

In [14]:
def middle(x):
    return x[1:-1]
print(middle([1,2,3,4]))
[2, 3]

Exercise 4

In [19]:
def chop(x):
    del(x[0])
    del(x[-1])

a=[1,2,3,4]
chop(a)
print(a)
[2, 3]

The difference is that chop modifies the list in place, while middle returns a copy of a slice of the original list.

Exercise 5

In [21]:
def is_sorted(x):
    return x==sorted(x)

print(is_sorted([1,2,3,4,5]))
print(is_sorted(['a','b','e','d']))
True
False

Exercise 6

In [3]:
def k_largest(numbers,k):
    ranked=sorted(numbers, reverse=True)
    return ranked[:k]
In [8]:
a=[1,10,6,3,2,100,0.5]
print(k_largest(a,3))
[100, 10, 6]
In [ ]:
Alternatively:
In [31]:
def k_largest(numbers,k):
    ranked=sorted(numbers)
    ranked.reverse()
    return ranked[:k]
In [32]:
a=[1,10,6,3,2,100,0.5]
print(k_largest(a,3))
[100, 10, 6]

Exercise 7

In [34]:
def is_anagram(word1,word2):
    return sorted(word1.lower())==sorted(word2.lower()) #converts all characters to lower case

print(is_anagram('listen','silent'))
print(is_anagram('Hamlet','amleth'))
True
True

Exercise 8

In [35]:
def largest_of_three(x,y,z):
    return sorted([x,y,z])[-1] #converts all characters to lower case

largest_of_three(20,40,10)
Out[35]:
40

Exercise 9

In [33]:
def first_k_digits(x, k):
    y=list(str(x))
    y.remove('.')
    return y[:k]
In [36]:
import math
print(math.pi)
print(first_k_digits(math.pi,5))
3.141592653589793
['3', '1', '4', '1', '5']
In [7]:
y.remove('.')

Exercise 10

Simple solution (assuming an odd list size):

In [ ]:
def median(x):
    return y[int((len(y)-1)/2)] 

Note that we need to do a type conversion since the list index needs to be an integer, but the division makes Python assume that the result is a float.

Full solution:

In [46]:
def median(x):
    y=sorted(x)
    if (len(x) % 2)==0: # % is the remainder
        return 0.5*(y[int(len(y)/2-1)]+y[int(len(y)/2)])
    else:
        return y[int((len(y)-1)/2)]
In [47]:
print(median([1,2,3,4]))
2.5
In [ ]:
print(median([1,2,3,4,5]))