Codecademy Python 3 - Review - Quiz problems
zip()
Function that allows you to iterate through multiple lists at the same time list_a = [3, 9, 17, 15, 19] list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90] for a, b in zip(list_a, list_b): print a print b
while/else construction: How does it compare to an if/else?
Main difference: In while/else, the else block will execute anytime the loop condition is evaluated to False (even if the loop hasn't been entered, or if the loop exits normally). If the loop exits as a result of break, the else will not be executed.
What is the data type of x? x = "False"
Not boolean! It is a string
lista[::2]
2 is the step so it will start and end at the start and end of the list, going every other one
Modulo...what happens if you try to find the remainder of two numbers, but you list them backwards? Ex. 400 % 300 = 100 What about 300 % 400?
300 % 400 > 300 The smaller number will be returned.
What is list comprehension?
A way to create lists using for/in and if keywords format is different: evens = [i for i in range(51) if i % 2 == 0] print evens >> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]
What will happen if you call this: from datetime import datetime
All functions from datetime are imported
map() and lambda combo example
Celsius = [39.2, 36.5, 37.3, 37.8] Fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius) print Fahrenheit Here, we first do lambda (x: function-of-x) to return a list of function-of-x. Then, map the anonymous lambda function to a list.
bitwise AND syntax: print 8 & 5 output: >> 0
Compares two numbers on a bit level and returns a number where the bits of that number are turne on if the corresponding bits of both numbers are 1. Ex. 42 & 15 = 10: a: 0 0 1 0 1 0 1 0 b: 0 0 0 0 1 1 1 1 ================== 0 0 0 0 1 0 1 0 **NOTE, the & operator can only result in a number that is smaller than both of the numbers. RULES: 0 & 0 = 0 0 & 1 = 0 1 & 0 = 0 1 & 1 = 1
bitwise Right Shift: syntax: print 5 >> 4 output: 0 bitwise Left Shift: syntax: print 5 << 1 output: 10
These operations work byt shifting the bits of a number over by a designated number of slots. (Only works on an integer) # Left Bit Shift (<<) 0b000001 << 2 == 00b000100 so, 1 << 2 == 4 # Right Bit Shift (>>) 0b0010100 >> 3 == 000010 so, 20 >> 3 = 2 0b0000010 >> 2 = 0b000000 so, 2 >> 2 = 0 *In these cases, the 1 has fallen off the screen
What's the quick way to get a reversed string?
[::1] or reversed()
join()
a function that takes a list and joins them into a nice string format letters = ['a', 'b', 'c', 'd'] print " ".join(letters) print "---".join(letters) returns: a b c d a---b---c---d
index()
a function that will return the index of that item. Usually used like this: list_name.index(arg1)
What is an anonymous function?
a function without a name
What are the three Boolean operators in Python?
and, or, not
filter(f, l)
arg1 is a Boolean function (returns "True" or "false"); arg2 is a list. Filters out all the true values from the list.
Using a while loop to check if the user input is valid
choice = raw_input('Enjoying the course? (y/n)') while choice != 'y' and choice != 'n': choice = raw_input("Sorry, I didn't catch that. Enter again: ")
example of enumerate function
choices = ['pizza', 'pasta', 'salad', 'nachos'] print 'Your choices are:' for index, item in enumerate(choices): print index, item Prints: Your choices are: 1 pizza 2 pasta 3 salad 4 nachos
break
command that gets you out of the for loop
How can you use a break statement to prevent infinite loops from occurring?
count = 0 while True: print count count += 1 if count >= 10: break
Use a list comprehension to create a list, cubes_by_four. The comprehension should consist of the cubes of the numbers 1 through 10 only if the cube is evenly divisible by four. Finally, print that list to the console. Note that in this case, the cubed number should be evenly divisible by 4, not the original number.
cubes_by_four = [x ** 3 for x in range(1, 11) if ((x ** 3) % 4) == 0] print cubes_by_four
map() function example
def fahrenheit(T): return ((float(9)/5)*T + 32) def celsius(T): return (float(5)/9)*(T-32) temp = (36.5, 37, 37.5,39) F = map(fahrenheit, temp) C = map(celsius, F)
def is_prime To test if a number is prime, no other number should go into x evenly besides 1 and x.
def is_prime(x): if x < 2: return False else: for n in range (2, x-1): if x % n == 0: return False return True
median (Practice Makes Perfect) ''' Find the middle number of a list 1. Sort 2. Find middle value 3. If there are an even number of elements, take the mean of the two middle vals sorted() function Hint: Find the indexes of the middle two elements first element: len(array) / 2 second element: len(array) / 2 - 1 '''
def median(lista): lista = sorted(lista) if len(lista) % 2 == 0: # If even number of values index1 = int(len(lista) / 2) index2 = int(len(lista) / 2 - 1) median = (lista[index1] + lista[index2]) / 2.0 return median elif len(lista) % 2 == 1: # If odd number of values index1 = int((len(lista) / 2) + 0.5) median = lista[index1] return median
Product (Practice Makes Perfect) ''' Function that takes a list of integers Returns the product of all the elements in the list '''
def product(lista): prod = 1 for i in lista: prod *= i return prod (This one was easy, I did it in 2 minutes)
Purify (Practice Makes Perfect) ''' Function that takes a list of numbers, removes all odd numbers return the result '''
def purify(lista): listb = [] for i in lista: if i % 2 == 0: listb.append(i) return listb
Remove Duplicates (practice Makes Perfect) ''' Function that takes a list and removes elements of hte list that are the same. Keep a single occurance of the number Order doesn't matter '''
def remove_duplicates(lista): listb = [] for i in lista: if i not in listb: listb.append(i) return listb print(remove_duplicates([1, 1, 2, 2])) >> [1, 2]
**
exponent operator
What functions are commonly used in combo with lambda?
filter() map() reduce()
How to check a calendar (dictionary) to see if it has any dates (keys) in it
if len(calendar.keys()) < 1: print "Calendar is empty."
delete statement
not a function! It is a way to remove an item from a list / dict given its index instead of its value. del a[0] (not like the pop() method which returns a value) or you can use it to delete entire variables https://docs.python.org/2/tutorial/datastructures.html#the-del-statement
What are bitwise operations?
operatrions that directly manipulate bits print 5 >> 4 # Right Shift print 5 << 1 # Left Shift print 8 & 5 # Bitwise AND print 9 | 4 # Bitwise OR print 12 ^ 42 # Bitwise XOR print ~88 # Bitwise NOT output: 0 10 0 13 38 -89
What does it mean to call the index function on a list called options?
options.index()
How do you make text all uppercase or lowercase?
text-transform: uppercase; or lowercase;
example Use a list comprehension to create a list, threes_and_fives, that consists only of the numbers between 1 and 15 (inclusive) that are evenly divisible by 3 or 5.
threes_and_fives = [x for x in range(1, 16) if x % 3 == 0 or x % 5 == 0] >> [3, 5, 6, 9, 10, 12, 15]
How do you prompt a user for input and save it as a variable?
variable_name = input("Enter your name")
lista[::-1]
will print backwards
String formatting : %s vs %d
%s is used to format strings %d is used to format integers
zip() parameters
(Deciding if I should use in my search code) The iterator stops when the shortest variable is exhausted
How would you iterate through this list to create a new list of all the numbers? n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
Use DOUBLE nested iterating loops. *Make sure the name of the looping variable matches the inner list name. def flatten(lists): results = [] for numbers in lists: for i in numbers: results.append(i) return results print flatten(n)
How would you create a variable, set the variable equal to the result of calling the index() function on the options list. The index() function should take user_choice as its argument.
Use the format list_name.index(arg1): This will return the INDEX of the user choice, in relation to the list.
if x % 2 == 0
stands for the REMAINDER
from random import randint
imports the random module , specifically a random integer function inside that module You don't need to import the whole module blindly if there isn't a good reason to do so
general syntax of lambda
lambda argument list: expression argument is a comma separated list of args expression is an arithmetic expression using the args You can also assign to a variable. f = lambda x, y: x+y Then, later, just call it by the arguments: f(1, 1)
Examples of lambda & filter
languages = ["HTML", "JavaScript", "Python", "Ruby"] print filter(lambda x: x == 'Python', languages) >> ['Python'] ........ my_list = range(16) print filter(lambda x: x % 3 == 0, my_list) >> [0, 3, 6, 9, 12, 15] ......... squares = [x ** 2 for x in range(1,11)] print filter(lambda x: x >= 30 and x <= 70, squares) >> [36, 49, 64]
list slicing syntax
lista[start, stop, step]
map()
map is a function with 2 arguments: r = map(func, seq) func = name of a function seq = a list. map applies the function to every item in that list. Returns a new list (length of shorter list), with all args changed by func
# Say you have a list and you just want to extract one element: languages = ["HTML", "JavaScript", "Python", "Ruby"] # Add arguments to the filter() print filter(________, ________)
print filter(lambda x: x=="Python", languages) returns ['Python']
What is the correct way to output a string to the console?
print("The string") or print(variable_name)
How would you create a list of all zeroes? 5 items
print["0"] * 5 result: ['0', '0', '0', '0', '0']
my_dict.keys()
returns a list of the dictionary's keys *might be in a weird order but they will correspond to each other
my_dict.values()
returns a list of the the dictionary's values *might be in a weird order
scrabble_score (Practice makes perfect) letters each worth a given amount
score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, "x": 8, "z": 10} def scrabble_score(word): word = word.lower() total = 0 for letter in word: if letter in score.keys(): total += score[letter] return total print(scrabble_score('Olivia'))
snake case
snake_case pros way of making words https://en.wikipedia.org/wiki/Snake_case
print bin(0b1110 & 0b101) What is the result?
# 0b1110 # 0b0101 # ======== # 0b0100 = 8
What will this code print? time = datetime.now() #2014-07-08 12:08:09 print time.day
8
for letter in "Eric": print letter, # note the comma! what does that do?
Adding the comma will make spaces in between the letters. If you don't have the comma, it will just print them each on a new line! Ex. for key in my_dict: print key, my_dict[key] Returns: 1 2 3 4 5 6
reduce(func, seq)
Continually applies the function to the sequence. It returns a single value...like a playoffs bracket If seq = [s1, s2, s3, s4,...sn], 1. func(s1, s2) s3, s4... 2. func(func(s1, s2), s3), s4... 3. func(func(func(s1, s2), s3), s4)... Continues until just one element is left and returns this!
What's another way to think about >> and << (left and right shift bitwise operations)?
For >>, after dividing by 2, round down. For <<, after multiplying by 2, round down. It's easiest to just think about the 1s and 0s shifting left or right by the specified number of slots.
What does it mean if you include a comma after the print statement?
Good for for loops! The , character after the print statement means that our next print statement will print on the same line
Function that takes out vowels (Practice makes perfect)
I got this one right! It took a couple tries, but I had "if i in ..." and changed it to "for text[i] in..." def anti_vowel(text): output = "" for i in range (0, len(text)): if text[i] in "aeiouAEIOU": pass else: output += text[i] return output print(anti_vowel('Olivia'))
In a recursive function, how can you plan the indentation of the return statements?
If you just want the last value, place the return statement at the same level as the def. If you want a compilation of all the values along the way, place the return statement indented after the def / if / else.
What's a way to exit a loop and quit a program?
If you start out with start = True, later, you can say else: start = False # Exits the loop and quits the program.
What is the "base condition"?
In a recursion function, when the number reduces to 1. ** Every recursive function must have a base condition, otherwise it will call itself indefinitely!
What does lambda stand for in math?
In linear algebra, it's the "LaGrange multiplier" - way to find the maxiumum or minimum of a multivariable function f(x, y...) when there is some constraint on the input values, g(x,y) - Bascially, look for points where contour lines of f and g are tangent to each other
What does lambda do?
It creates an anonymous function When we pass the lambda to filter, filter uses the lambda to determine what to filter, and the second argument is the list is does the filtering on.
what does zip function do?
It creates pairs of elements when passed two lists
functional programming Allows you to pass functions as if they were variables or values Using lambda!
Syntax: lamda x: x % 3 == 0 is the same as: def by_three(x): return x % 3 == 0
sleep()
a function that tells a program, take a second to process the next line of code You can specify time: sleep(1) for 1 second
continue
a statement used in an if- loop, allows you to start the loop from the beginning again. Docs: https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
How would you create a grid of 25 zeros?
board = [] for i in range(0, 5): board.append(['O'] * 5)
What is control flow?
Something that allows us to select between multiple outcomes (if-elif-else statements)
Function for finding the HCF / GCD (highest common factor / greatest common denominator) aka. the largest positive integer that perfectly divides the two given numbers vs THE EUCLIDEAN ALGORITHM (A recursive function example from https://www.programiz.com/python-programming/examples/hcf)
# Using loops (less efficient) def compute(x, y): # Choose the smaller number if x > y: smaller = y else: smaller = x # Go thru all integers to find common factors for i in range(1, smaller + 1): #Check that they are both divisible by i if ((x % i == 0) and (y % i == 0)): hcf = i return hcf num1 = 54 num2 = 24 print("The H.C.F. of", num1,"and", num2,"is", compute(num1, num2)) # Euclidean Algorithm # This function finds the Highest Common Factor of two numbers def computeHCF(x, y): while(y): x, y = y, x % y return x computeHCF(300, 400)
# Recursive sum to find the sum of all natural numbers (Practice Makes Perfect) def recur_sum(n): if n <= 1: # base case return n else: return n + recur_sum(n - 1) # Recursive print (recur_sum(4)) > 10
''' Step-by-step explaination of the loop I made: START: n = 4 n > 1 so proceed return 4 + recur_sum(3) What is recur_sum(3)? n = 3 n > 1 so proceed return 3 + recur_sum(2) What is recur_sum(2)? n = 2 n > 1 so proceed return 2 + recur_sum(1) What is recur_sum(1)? n == 1 so return n return 1 STOP Now, gather all the return statements Since they are indented, the return statements should be compiled: Step 4: return 1 Step 3: return 2 + 1 Step 2: return 3 + 2 + 1 Step 1: return 4 + 3 + 2 + 1 Overall return 10. '''
How does the euclidean algorithm work? # to find H.C.F. of two numbers def computeHCF(x, y): while(y): x, y = y, x % y return x computeHCF(300, 400)
- Uses a while loop. While y is true, the loop will proceed. - When y becomes zero, the loop will end. - Break apart the single line assignment...it swaps the variables & simultaneously puts the remainder in y x, y = y, x % y or: x = y y = x % y # put remainder in y - When y becomes zero, we have the highest common factor in x.
How do you iterate through the key values in a dictionary?
.keys() This is essential if you're trying to find a key!! ex. for i in dict_name.keys(): return dict_name[i]
Advantages of recursion
1. Recursive functions make the code look clean & elegant 2. A complex task can be broken down into simpler sub-problems using recursion 3. Sequence generation is easier with recursion than using nested iteration.
Disadvantages of recursion
1. Sometimes the logic behind recursion is difficult to understand 2. From a memory / time standpoint, recursive functions are expensive 3. Recursive functions can be hard to debug
Infinite Loop: what are two reasons it might happen?
1. The loop condition cannot possibly be false ex. while 1 != 2 2. The logic of the loop prevents the loop condition from becoming false ex. count = 10 while count > 0: count += 1
What will this code print? now = datetime.now() #2013-01-04 19:22:43 print '%s/%s/%s %s:%s:%s' % (now.day, now.month, now.year, now.hour, now.minute, now.second)
4/1/2013 19:22:43
Step by step while statement for simultaneous assignment (find the LCM) def computeHCF(x, y): while(y): x, y = y, x % y return x computeHCF(300, 400) > 100
This while statement simultaneously swaps x, then puts the remainder in y. Ex x = 300, y = 400: Round 1: x = 300 and y = 400. y != 0 so go: Now x = 400, and y = 300 % 400 = 300 # Special case for modulos - see rules Round 2: x = 400 and y = 300. y != 0 so go: Now x = 300, and y = 400 % 300 = 100 # We finally get the right remainder Round 3: x = 300 and y = 100 y != 0 so go: Now x = 100, and y = 300 % 100 = 0 Round 4: x = 100 and y = 0 y == 0 so stop! While loop has been executed. What we do next? According to the indentation, time for the return statement. It just says "return x". Check out the 4th call when x = 100 and y = 0: So, return 100. '''
my_dict.items()
When you call the function items() on a DICT, it will convert them to a LIST of tuple pairs. *might be in a weird order ex. 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() >> [("Monty Python's Life of Brian", 'Good'), ("Monty Python's Meaning of Life", 'Okay'), ('Monty Python and the Holy Grail', 'Great')]
When should you use lambda functions?
When you need a "throwaway" function If you're going to use it over and over, just write a regular function.
enumerate()
When you're iterating through a dictionary (by the keys), it can be tricky to keep track of the key values. This function supplies a corresponding index to each element in the list that you pass it. Each time you go through the loop, index += 1 and item will be the next item in the sequence. Similar to using a regular for loop, but it counts as you go!
variable swapping - How To https://www.programiz.com/python-programming/examples/swap-variables
You could use a temporary variable...or...just do it on one line: x, y = y, x - You can also include operators (+ - * / ^) - This only works on integers
censor (Practice makes perfect) I got this mostly on my own! Key functions were: - enumerate() - split() - join()
def censor(text, word): no_letters = len(word) bleep = '*' * no_letters tlist = text.split() # Turn string into a list for index, item in enumerate(tlist): # Turns list into dictionary if tlist[index] == word: tlist[index] = bleep index += 1 return " ".join(tlist) print(censor('what do I do', 'do')) >> what ** I **
count (Practice Makes Perfect) ''' Return the number of times the item occurs in the list count([1, 2, 1, 1], 1)) should return 3 becuase 1 appears 3x on the list. Input may be int, str, float, or list -- Return an int Don't use the built-in method for this. '''
def count (sequence, item): count = 0 for i in sequence: if i == item: count +=1 return count
Reverse (Practice makes perfect)
def reverse(text): length = len(text) - 1 char = "" while length >= 0: char += text[length] length -= 1 else: print (char) print(reverse('Olivia'))
in
for iterating over lists, tuples, dictionaries, and strings Use intuitively
for/else
for loops may also have else associated with them! The else statement is only executed after the for ends normally If it ends with "break", the else will simply not be executed.
What if you want to import multiple things from a module?
from time import sleep, strftime
example of for/else loop
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape'] print 'You have...' for f in fruits: if f == 'tomato': print 'A tomato is not a fruit!' # (It actually is.) break print 'A', f else: print 'A fine selection of fruits!' You have... A banana A apple A orange A tomato is not a fruit!
string.split() and " ".join(list)
help split a string by its spaces and conversely, helps rejoin a list into a string, separated by a space
List Comprehension syntax tho... Examples of how to write a list in one lin
list1 = [x for x in range(1, 6)] aka.... for x in range(1,6): list1.append(x) ......... list2 = [x * 2 for x in range(1, 6)] aka..... for x in range(1, 6): list2.append(x * 2) ......... list3 = [x * 2 for x in range(1, 6) if (x * 2) % 3 == 0] aka.... for x in range(1, 6): if (x * 2) % 3 == 0: list3. append(x * 2) .......... list4 = [i for i in range(10) if i % 2 == 0] aka.... for i in range(1): if i % 2 == 0: list4.append(i) ........ So the first item before "for" is what you're appending to the new list. The rest of the statement is a one line conversion of all the for/if/in shits
garbled = "IXXX aXXmX aXXX" Example of lambda & filter on a string
message = filter(lambda x: x != 'X', garbled) print message I am a! # Removed all the X's
garbled = "IXXX aXXmX aXXX" Use string slicing to get the secret message
message = garbled[::-2] print message
string formatting with % (how do you directly print strings with variables in specific spots?)
name = "Me" print "Hello %s" % (name) or... print "The %s who %s %s!" % ("Knights", "say", "Ni") or if it's a plural, add the s directly inline print "There were many %ss protesting to keep %s in stores."
\n What does this mean if it's in a string? ex. hint = "Don't forget! \nExiting..."
newline If this variable is printed, everything that comes after the \n will print on a new line
Syntax for lambda & filter on a list...
var = filter(lambda args: fxn(args), list)
Syntax for lambda & filter on a string:
var = filter(lambda args: fxn(args), string)