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.
import numpy as np def heads_or_tails(): u=np.random.uniform() if u> 0.5: print('heads') else: print('tails') heads_or_tails()
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!
for i in range(1,6): print(i)
1 2 3 4 5
cities=['Sydney', 'Melbourne', 'Brisbane', 'Adelaide', 'Perth'] for city in cities: print(city)
Sydney Melbourne Brisbane Adelaide Perth
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 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:
(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.
(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:
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.