Python for Business Analytics

Exercises: loops and conditionals


In this proble set you will be practicing loops and conditionals, which are some of the most useful tools of programming. The following cells review the basic syntax.

In [1]:
import numpy as np

def heads_or_tails():
    u=np.random.uniform()
    if u> 0.5:
        print('heads')
    else:
        print('tails')

heads_or_tails()
heads
In [2]:
def countdown(n):
    i=n
    while i>0:
        print(i)
        i-=1 # this the same as i=i-1
    print('Go!')

countdown(5)
5
4
3
2
1
Go!
In [3]:
for i in range(1,6):
    print(i)
1
2
3
4
5
In [4]:
cities=['Sydney', 'Melbourne', 'Brisbane', 'Adelaide', 'Perth']
for city in cities:
    print(city)
Sydney
Melbourne
Brisbane
Adelaide
Perth

Exercise 1

This is a warm-up exercise. Write a function that takes a string as an input and calculates the number of capital letters in the string.

In [ ]:
 

Exercise 2

In numerical analysis, there are several algorithms to compute the square root of a number. Calculating the square root of a number $Z$ is equivalent to solving the equation $x^2-Z=0$ for $x$.

We can then use a root finding algorithm to solve the equation. You may be familiar with some of them if you have taken Management Science and/or have used the Excel solver. Newtown's method solves the equation as follows:

  1. Start with an initial guess $x_0$.
  2. Update $x_1=\frac{x_0+Z/x_0}{2}$.
  3. Continue in this way with sucessive updates $x_{n+1}=\frac{x_n+Z/x_n}{2}$.
  4. Stop the computation reaches a specified precision $|x_{n+1}-x_n|<\epsilon$.

(a) Write a function that implements Newton's method for finding a square root. You will need to use a while loop for this.

(b) Write a code that computes the square root of $1,2,\ldots,10$ in a loop. Compare the result with the math.sqrt functions. Build a table to display the results. The table can be a NumPy arrray, or even better a

This exercise is based on Think Python.

In [ ]:
 

Exercise 3

(a) Write a function that gets a text and a word as inputs and returns True if the word appears in the text, and false otherwise. The following methods are useful for this task:

  1. The string lower method.
  2. The string replace method to remove special characters.
  3. The string split method.

You can text your function with Shakespeare:

We are such stuff as dreams are made on; and our little life is rounded with a sleep.

Beyond the exercise, the Python Natural Language Toolkit has functions for text processing tasks of this type.

(b) Use pandas to load the Twitter US Airline Sentiment dataset from the Tweets.csv file. Display the first five rows of the data and print the first tweet in the dataset. Write a function that takes an word as an input (say, 'excellent') and loops over the tweets (the text column) to count how many tweets contain that word.

(c) Choose a word that reflects a positive or negative sentiment. Write a function that takes a word as an input and computes the proportion of tweets that were classified as positive, negative, and neutral, among tweets that contain that word.