Advanced Topics in Python

I Iteration Nation

i. Iterators for Dictionaries 1/18

my_dict = {
    'Name': 'Sunakshi',
    'Height': 160
}
print my_dict.items()

ii. keys() and values() 2/18

my_dict = {
    'Name': 'Sunakshi',
    'Height': 160
}
print my_dict.keys()
print my_dict.values()

iii. The ‘in’ Operator 3/18

my_dict = {
    'Name': 'Sunakshi',
    'Height': 160
}

for key in my_dict:
    print key, my_dict[key]

II List Comprehensions

i. Building Lists 4/18

>Save and Submit!

ii. List Comprehension Syntax 5/18

doubles_by_3 = [x*2 for x in range(1,6) if (x*2) % 3 == 0]

# Complete the following line. Use the line above for help.
even_squares = [x**2 for x in range(1,12) if x % 2 == 0]
print even_squares

iii. Now you Try! 6/18

cubes_by_four = [ x**3 for x in range(1,11) if x**3 % 4 == 0]
print cubes_by_four

III List Slicing

i. List Slicing Syntax 7/18

l = [i ** 2 for i in range(1, 11)]
# Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

print l[2:9:2]

ii. Omitting Indices 8/18

my_list = range(1, 11) # List of numbers 1 - 10

# Add your code below!
print my_list[::2]

iii. Reversing a List 9/18

my_list = range(1, 11)

# Add your code below!
backwards = my_list[::-1]

iv. Stride Length 10/18

to_one_hundred = range(101)
# Add your code below!
backwards_by_tens = to_one_hundred[::-10]
print backwards_by_tens

v. Practice Makes Perfect 11/18

to_21 = range(1,22)
odds = to_21[::2]
print odds
middle_third = to_21[7:14]
print middle_third

IV Lambdas

i. Anonymous Functions 12/18

>Save and Submit!

ii. Lambda Syntax 13/18

languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda x: x == 'Python', languages)

iii. Try it! 14/18

squares = [x**2 for x in range(1,11)]
print filter(lambda i: 30 <= i <=70, squares)

V Review

i. Iterating over Dictionaries 15/18

movies = {
	"Monty Python and the Holy Grail": "Great",
	"Monty Python's Life of Brian": "Good",
	"Monty Python's Meaning of Life": "Okay"
}
print movies.items()

ii. Comprehending Comprehensions 16/18

threes_and_fives = [x for x in range(1,16) if x % 3 == 0 or x % 5 == 0]

iii. List Slicing 17/18

garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[::-2]

iv. Lambda Expressions 18/18

garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
message = filter(lambda i: i != 'X', garbled)
print message
Advertisements

2 thoughts on “Advanced Topics in Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s