Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Exam Review 2022 June 18
- # LABS
- # Ch 2-14... all Labs!
- # Ch 21-31 just ADDITIONAL LABS, but important practice!
- # Use Submit Mode!!!
- # Watch your string input and output
- # # 1
- # myVar = input().strip() # myVar = input().rstrip()
- # # 2
- # print("some stuff", end=" ") # if you ever override end
- # print() # print(end="\n")
- # Comp 1: Basic syntax and knowledge: operators, data types, etc
- # Comp 2: Control Flow
- # Comp 3: Modules and Files
- # Comp 1: Basic syntax and knowledge: operators, data types, etc
- # Data Types
- # str
- # int
- # float
- # list
- # dict
- # tuple # immutable, any series x, y, z -> interpreted as a tuple, return x, y -> return (x,y)
- # sets # all unique/no duplicates, no order -> no index, no slicing
- # operators
- # = # assigning a value
- # == # asking, "equality operator"... use in conditional
- # +
- # -
- # *
- # /
- # % # modulo... whole number remainder, "How many whole things are left over?"
- # // # floor division... int(x/y) or really like math.floor(x,y)
- # <
- # >
- # <=
- # >=
- # !=
- # += # increment... x += 1 same as x = x + 1
- # -=
- # ** # raise to power... similar to math.pow()
- # # # keywords used like operators
- # in # if __ in __
- # not # if not __ in __
- # and
- # or # any one True means whole condition True... limit OR to 2 conditions
- # Comp 2
- # Basic control structures
- # IF statements... if, if/else, if/elif, if/elif/else, etc
- # LOOPS
- # WHILE - an IF that repeats
- # FOR - looping over some container, or a known number of times (range())
- # for __ in __:
- # for item in myList:
- # for n in range(0, 5): # [0, 1, 2, 3, 4]
- # for i in range(len(myList)): # i for the index, myList[i] for the value
- # for k in myDictionary: # value for the key is myDictionary[k]
- # FUNCTIONS
- # defining/writing vs calling
- # parameters vs outside or "regular" variables
- # parameters vs arguments
- # a good function has ONE job, modular
- # return vs print()... # do whichever the question
- # methods are functions that belong to a type/class
- # def someFunction(x, y):
- # return x + y
- #
- # if "__name__" == "__main__": # am I running from this particular file that I'm writing?
- # myInput = int(input().strip())
- # num = someFunction(myInput, someOtherNum)
- # print(num)
- # See "tasks" in the last section of Ch 10, 11, 13, 14 for function writing practice
- # CodingBat also has good function-based Python questions:
- # https://codingbat.com/python
- # BUILT-IN FUNCTIONS
- # print()
- # input()
- # len()
- # sum()
- # min()
- # max()
- # range()
- # str()
- # list()
- # dict()
- # tuple()
- # set()
- # sorted() # compare to list.sort()
- # reversed() # compare to list.reverse()
- # enumerate()
- # round() # cousins math.ceil(), math.floor()
- # open() # IO/file methods: .read(), .readlines(), .write()
- #
- # help()
- # dir()
- # help(str)
- # print(dir(str))
- # help(str.isspace)
- # for item in dir(str):
- # if not item.startswith("_"):
- # print("{}()".format(item))
- # STRINGS
- # be able to slice like it's 2nd nature... myString[start:stop:step]
- # myString = "abc"
- # myRevString = myString[::-1]
- # print(myRevString)
- # KNOW YOUR WHITESPACE
- # # " " # ... and a lot of other Unicode spaces
- # # "\n"
- # # "\r"
- # # "\b"
- # # "\t"
- # # "\f"
- # # STRING METHODS
- # myString.format()
- # myString.strip() # myString.rstrip()
- # myString.split() # returns a list of smaller string
- # ",".join(someListOfStrings)
- # myString.replace(oldSubStr, newSubStr) # remove... myString.replace(oldSubStr, "")
- # myString.find(subStr) # return index of first occurrences, compare myString.index()
- # myString.count(subStr) # return int number of occurrences
- # # is/Boolean methods: isupper(), islower(), isdigit(), isnumeric(), isspace(), isalphanum()
- #
- # # LISTS
- # # again be able to slice
- #
- # # LIST METHODS
- # # +
- # myList.append(item)
- # myList.insert(i, item)
- # myList.extend(anotherList)
- # # -
- # myList.pop() # myList.pop(i), pop by index...
- # myList.remove(item) # remove by value...
- # # other
- # myList.count(item)
- # myList.sort()
- # myList.reverse()
- # # not as important
- # myList.index() # be careful, could be in there more than once
- # myList.copy()
- # myList.clear()
- # DICT
- # # # use the key like an index
- # # # you can use the dict KEY to get its VALUE
- # myDict[key] # retrieve the value for that key
- # myDict[key] = new value
- # myDict.items() # for k, v in myDict.items()
- # myDict.keys()
- # myDict.values()
- # SETS
- # mySet.add()
- # mySet.remove(item) # by value
- # mySet.pop() # removes a random item
- # MODULES
- # # MATH MODULE
- # import math
- # math.factorial(x)
- # math.ceil(x.yz)
- # math.floor(x.yz)
- # math.pow(x, y) # similar to **
- # math.sqrt(x)
- # math.fabs() # abs()
- # math.e
- # math.pi
- # different import types
- # full import: math.factorial()
- # partial import:
- # from math import factorial
- # --> factorial()
- # from math import factorial, sqrt
- # from math import *
- # aliased imports
- # import math as m --> m.factorial()
- # # OPENING FILES
- # good practice in Ch 14 Task 4, 7, 8
- # with open("filename.txt", "r") as f:
- # # grab contents and get out of the open block
- # contents = f.read() # whole file as one big string
- # contents = f.readlines() # a list of line by line strings
- with open("test.txt", "r") as f:
- contents = f.readlines()
- # print(contents)
- # for line in contents:
- # line = line.strip()
- # print(line) # print(line, end="\n")
- with open("mock_data.csv", "r") as f:
- # contents = f.readlines() # ["1,Flossie,Levey...\n"...]
- import csv
- contents = list(csv.reader(f)) # csv.reader(f, delimiter="\t")
- # does one more step for us...
- # ['1', 'Flossie', 'Levey', 'flevey0@jimdo.com', '129.134.226.30']
- print(contents)
- with open("mock_data2.csv", "w") as f2:
- for line in contents:
- if line[3].endswith(".org"): # if line[3][-4] == ".org"
- f2.write("{}\n".format(",".join(line)))
- # Student Questions
- # Seats (or columns) within rows in a room is a good use case for nested loops...
- rows = 5
- seats = 10 # "columns" within the rows
- for row in range(0, rows):
- for seat in range(0, seats):
- print("{}-{}".format(row, seat))
- # The Simon Says game in Ch 6.10 is a good example where
- # you might THINK it needs a nested loop... but it doesn't!
- '''
- "Simon Says" is a memory game where "Simon" outputs a sequence of 10 characters (R, G, B, Y) and the user must repeat the sequence. Create a for loop that compares each character of the two strings. For each matching character, add one point to user_score. Upon a mismatch, end the loop.
- Sample output with inputs: 'RRGBRYYBGY' 'RRGBBRYBGY'
- '''
- user_score = 0
- simon_pattern = "RRGBRYYBGY" #input()
- user_pattern = "RRGBBRYBGY" # input()
- ''' Your solution goes here '''
- # NOT a nested loop! We don't need to compare all the values, just corresponding ones
- for i in range(len(simon_pattern)):
- if simon_pattern[i] == user_pattern[i]:
- user_score += 1
- else:
- break
- print('User score:', user_score)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement