In [5]:
a = [-1, 1, 66.25, 333, 333, 1234.5]
del a[0]
print(a)

[1, 66.25, 333, 333, 1234.5]
del a[2:4]
print(a)

[1, 66.25, 1234.5]
del a[:]
print(a)

a = []
del a
[1, 66.25, 333, 333, 1234.5]
[1, 66.25, 1234.5]
[]
In [2]:
# dictionary
result = 0
basket_items = {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8}

'''
print(basket_items['apples'])

for key in basket_items:
    print(key)

for custom_name in basket_items.values():
    print(custom_name)

for key, value in basket_items.items():
    print(key, value)
'''

fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']
for fruit, fruit_count in basket_items.items():
    if fruit in fruits:
        result += fruit_count
print(result)
23
In [4]:
# tuple
tuple = ("apple", "banana", "cherry")
for x in tuple:
    print(x)

if "apple" in tuple:
    print("Yes, 'apple' is in the fruits tuple")
apple
banana
cherry
Yes, 'apple' is in the fruits tuple
In [4]:
# loop
headlines = ["Local Bear Eaten by Man",
             "Legislature Announces New Laws",
             "Peasant Discovers Violence Inherent in System",
             "Cat Rescues Fireman Stuck in Tree",
             "Brave Knight Runs Away",
             "Papperbok Review: Totally Triffic"]
news_ticker = ""
for headline in headlines:
    news_ticker += headline + " "
    if len(news_ticker) >= 140:
        news_ticker = news_ticker[:140]
        break
print(news_ticker)
Local Bear Eaten by Man Legislature Announces New Laws Peasant Discovers Violence Inherent in System Cat Rescues Fireman Stuck in Tree Brave
In [5]:
# zip
x_coord = [23, 53, 2, -12, 95, 103, 14, -5]
y_coord = [677, 233, 405, 433, 905, 376, 432, 445]
z_coord = [4, 16, -6, -42, 3, -6, 23, -1]
labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"]
points = []
for label, x, y, z in zip(labels, x_coord, y_coord, z_coord):
    points.append("{}: {}, {}, {}".format(label, x, y, z))
for point in points:
    print(point)
F: 23, 677, 4
J: 53, 233, 16
A: 2, 405, -6
Q: -12, 433, -42
Y: 95, 905, 3
B: 103, 376, -6
W: 14, 432, 23
X: -5, 445, -1
In [6]:
# zip list to dictionary
cast_names = ["Barney", "Robin", "Ted", "Lily", "Marshall"]
cast_heights = [72, 68, 72, 66, 76]
cast = dict(zip(cast_names, cast_heights))
print(cast)
{'Barney': 72, 'Robin': 68, 'Ted': 72, 'Lily': 66, 'Marshall': 76}
In [7]:
# unzip
cast = (("Barney", 72), ("Robin", 68), ("Ted", 72), ("Lily", 66), ("Marshall", 76))
names, heights = zip(*cast)
print(names)
print(heights)
('Barney', 'Robin', 'Ted', 'Lily', 'Marshall')
(72, 68, 72, 66, 76)
In [8]:
# transpose matrix
data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
data_transpose = tuple(zip(*data))
print(data_transpose)
((0, 3, 6, 9), (1, 4, 7, 10), (2, 5, 8, 11))
In [9]:
# enumerate
cast = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby", "Lily Aldrin", "Marshall Eriksen"]
heights = [72, 68, 72, 66, 76]
for i, cas in enumerate(cast):
    cast[i] = "{} {}".format(cas, str(heights[i]))
print(cast)
['Barney Stinson 72', 'Robin Scherbatsky 68', 'Ted Mosby 72', 'Lily Aldrin 66', 'Marshall Eriksen 76']
In [10]:
# list comprehension
multiples_3 = [num*3 for num in range(1,21)]
print(multiples_3)
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60]
In [11]:
# filter with list comprehension
scores = {
             "Rick Sanchez": 70,
             "Morty Smith": 35,
             "Summer Smith": 82,
             "Jerry Smith": 23,
             "Beth Smith": 98
          }
passed = [name for name, score in scores.items() if score>=65]
print(passed)
['Rick Sanchez', 'Summer Smith', 'Beth Smith']
In [12]:
# lambda with map
numbers = [
              [34, 63, 88, 71, 29],
              [90, 78, 51, 27, 45],
              [63, 37, 85, 46, 22],
              [51, 22, 34, 11, 18]
           ]

def mean(num_list):
    return sum(num_list) / len(num_list)

averages = list(map(lambda num_list: sum(num_list) / len(num_list), numbers))
print(averages)
[57.0, 58.2, 50.6, 27.2]
In [13]:
# lambda with filter
cities = ["New York City", "Los Angeles", "Chicago", "Mountain View", "Denver", "Boston"]

def is_short(name):
    return len(name) < 10

short_cities = list(filter(lambda name: len(name) < 10, cities))
print(short_cities)
['Chicago', 'Denver', 'Boston']
In [14]:
# generator function
lessons = ["Why Python Programming", "Data Types and Operators", "Control Flow", "Functions", "Scripting"]

def my_enumerate(iterable, start=0):
    index = start
    for value in iterable:
        yield index, value
        index += 1

for i, lesson in my_enumerate(lessons, 1):
    print("Lesson {}: {}".format(i, lesson))
Lesson 1: Why Python Programming
Lesson 2: Data Types and Operators
Lesson 3: Control Flow
Lesson 4: Functions
Lesson 5: Scripting
In [15]:
# generator chunker solution 1
def chunker(iterable, size):
    chunk_size = size
    chunk_pointer = 0;

    while chunk_pointer < len(iterable):
        yield iterable[chunk_pointer: chunk_pointer + chunk_size]
        chunk_pointer += chunk_size

for chunk in chunker(range(25), 4):
    print(list(chunk))
[0, 1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11]
[12, 13, 14, 15]
[16, 17, 18, 19]
[20, 21, 22, 23]
[24]
In [16]:
# generator chunker solution 2
def chunker(iterable, size):
    """Yield successive chunks from iterable of length size."""
    for i in range(0, len(iterable), size):
        yield iterable[i:i + size]

for chunk in chunker(range(25), 4):
    print(list(chunk))
[0, 1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11]
[12, 13, 14, 15]
[16, 17, 18, 19]
[20, 21, 22, 23]
[24]
In [18]:
# generator sequence
sq_list = [x**2 for x in range(10)]  # this produces a list of squares
sq_iterator = (x**2 for x in range(10))  # this produces an iterator of squares
In [ ]:
# file open
with open('C:/Users/Vinay/Python Workspace/Nanodegree/README.md', 'r') as f:
    content = f.read()
print(content)

# looping in file
camelot_lines = []
with open("camelot.txt") as f:
    for line in f:
        camelot_lines.append(line.strip())
print(camelot_lines)
In [30]:
# csv
import unicodecsv
def read_csv(filename):
    with open(filename, 'rb') as f:
        reader = unicodecsv.DictReader(f)
        return list(reader)

daily_engagement = read_csv('data/daily_engagement.csv')

def get_unique_students(data):
    unique_students = set()
    for data_point in data:
        unique_students.add(data_point['account_key'])
    return unique_students

unique_engagement_students = get_unique_students(daily_engagement)
len(unique_engagement_students)
Out[30]:
1237
In [39]:
# Filling missing values
import pandas as pd

s1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
s2 = pd.Series([10, 20, 30, 40], index=['c', 'd', 'e', 'f'])

s = s1 + s2
print(s)

# print(s).dropna()

# s_fill = s1.sum(s2, fill_value=0)
# print(s_fill)
a     NaN
b     NaN
c    13.0
d    24.0
e     NaN
f     NaN
dtype: float64
In [ ]:
# If we want to extract column A from dataframe
df['A']
# more coloumns
df[['B', 'D']]

# Turn pandas DataFrames into NumPy arrays
numpy.array(df)
In [17]:
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib.pyplot import figure

figure(figsize=(12,12))
img=mpimg.imread('ml_map.png')
imgplot = plt.imshow(img)
plt.show();
In [ ]: