Introduction to Computational Analysis




Pay Notebook Creator: Roy Hyunjin Han0
Set Container: Numerical CPU with TINY Memory for 10 Minutes 0
Total0

Strings

Count the number of letters.

In [ ]:
len('Bring me my Bow of burning gold;')

Strip peripheral whitespace.

In [ ]:
'    Bring me my Arrows of desire:    '.strip()

Replace characters.

In [ ]:
'Bring me my Spear: O clouds unfold!'.replace('Spear', 'Shrubbery')

Format template.

In [ ]:
'Bring me my %s of fire!' % 'Chariot'

Test characters.

In [ ]:
'I will not cease from Mental Fight,'.startswith('I')

Count occurrences.

In [ ]:
'Nor shall my Sword sleep in my hand:'.count('my')

Lists

Join a list into a string.

In [ ]:
' ;) '.join([
    'Welcome to all the pleasures that delight',
    'Of ev\'ry sense the grateful appetite,',
])

Split a string into a list.

In [ ]:
'Then lift up your voices, those organs of nature'.split(', ')

Make a list from another list.

In [ ]:
words = "Those charms to the troubled and amorous creature.".split()
['*%s*' % x for x in words]

Get the length of each word.

In [ ]:
# Type your solution here and press CTRL-ENTER

Dictionaries

Make a dictionary of US state names.

In [ ]:
code_by_state = {'California': 'CA', 'New York': 'NY', 'Virginia': 'VA'}
code_by_state
In [ ]:
code_by_state.keys()
In [ ]:
code_by_state['Florida'] = 'FL'
code_by_state
In [ ]:
code_by_state['New York']

Make a dictionary of US state codes using a dictionary comprehension.

In [ ]:
state_by_code = {code: state for state, code in code_by_state.items()}
state_by_code
In [ ]:
# Get the state name for VA
state_by_code['VA']

Make a dictionary where each letter corresponds to a list of US states that start with that letter.

In [ ]:
import csv
state_by_code = {code: state for state, code in csv.reader(open('datasets/USA-StateAbbreviations.csv'))}
state_by_code['MA']
In [ ]:
import collections
codes_by_letter = collections.defaultdict(list)
for code in state_by_code:
    letter = code[0].lower()
    codes_by_letter[letter].append(code)
print(codes_by_letter['a'])
print(codes_by_letter['m'])

Functions

Define a function.

In [ ]:
def add(x, y):
    return x + y

add(1, 2)
In [ ]:
multiply = lambda x, y: x * y
multiply(1, 2)

Make a list of functions.

In [ ]:
methods = [add, multiply]
methods
In [ ]:
import random
for x in range(5):
    combine = random.choice(methods)
    print(combine(4, 5))

Define a function that returns a list of links on a webpage.

In [ ]:
import requests
from bs4 import BeautifulSoup

def get_links(url):
    html = requests.get(url).content
    links = BeautifulSoup(html, 'lxml').find_all('a')
    return [link.get('href') for link in links]

Look at the first five links on a webpage.

In [ ]:
get_links('http://google.com')[:5]

Count the number of links on a webpage.

In [ ]:
# Type your solution here and press CTRL-ENTER

Classes

Classes can contain variables and methods.

In [ ]:
class Animal(object):
    
    def __init__(self, name):
        self.name = name
        self.stomach = []
        
    def __repr__(self):
        return self.name
        
    def ask(self):
        return '%s is %s.' % (self.name, 'full' if self.stomach else 'hungry')
              
    def eat(self, food):
        if food in self.stomach:
            print('%s already ate %s.' % (self.name, food))
        else:
            print('%s eats %s!' % (self.name, food))
            self.stomach.append(food)
In [ ]:
turtle = Animal('Donatello')
dinosaur = Animal('Barney')
monster = Animal('Cookie Monster')
In [ ]:
monster.ask()
In [ ]:
monster.eat(turtle)
In [ ]:
monster.eat(turtle)
In [ ]:
monster.stomach
In [ ]:
turtle in monster.stomach
In [ ]:
dinosaur in monster.stomach

Keywords

In [ ]:
words = 'why do bees make honey'.split()
for index, word in enumerate(words):
    print(index, word)
In [ ]:
boys = 'Roy', 'Oak', 'Cedar', 'Rock'
girls = 'Cathaleen', 'Sienna', 'Holly', 'Sapphire'
list(zip(boys, girls))
In [ ]:
def walk_numbers():
    print('searching...')
    for i in range(10):
        yield i
    print('not found!')

# Stop as soon as the condition is met using any()
print('has_condition = %s' % any(x > 5 for x in walk_numbers()))
print()
print('has_condition = %s' % any(x > 10 for x in walk_numbers()))

We recommend the Official Python Tutorial.