Created
November 11, 2021 17:20
-
-
Save jjfiv/3cbe4862ae8a676788dfc1628d8daa80 to your computer and use it in GitHub Desktop.
CS145 Midterm Review #2: 17b_notes.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 17b_notes.py | |
## Recursion Breakdown | |
def countdown(n: int): | |
print("begin: countdown(",n,")") | |
if n == 0: | |
print("output:\t\tBlastoff!") | |
else: | |
print("before:\t\t", n) | |
countdown(n-1) | |
print("after:\t\t", n) | |
print("finish: countdown(",n,")") | |
def q9(): | |
items = [1,2,3,7,4,7] | |
k = 0 | |
while k < len(items): | |
if items[k] == 7: | |
print(items[k]) | |
k += 1 | |
print("---") | |
for k in range(len(items)): | |
if items[k] == 7: | |
print(items[k]) | |
print("---") | |
for it in items: | |
if it == 7: | |
print(it) | |
def for_loops(): | |
stuff = [1,2,3,4,7,3] | |
output = [] | |
for name in stuff: | |
if name == 7: | |
output.append(name) | |
break | |
print(output) | |
def factors(n): | |
keep = [] | |
for i in range(1, n+1): | |
if n % i == 0: | |
keep.append(i) | |
return keep | |
def is_prime(n): | |
return factors(n) == [1,n] | |
def line_count_file(file_name): | |
with open(file_name, 'r') as file_var: | |
total = 0 | |
for line in file_var: | |
total += 1 | |
continue | |
return total | |
def is_sorted(xs): | |
for i in range(len(xs)-1): | |
if xs[i] > xs[i+1]: | |
return False | |
return True | |
def sort_if_needed(xs): | |
if is_sorted(xs): | |
return xs | |
xs.sort() | |
return xs | |
def loops(): | |
numbers = [11, 2, 33, 4, 55, 6, 77, 8, 99] | |
for x in numbers: | |
if x < 11: | |
continue | |
if x > 50: | |
break | |
print(x * 10) | |
def aliasing_example(): | |
def add_c_to_list(second): | |
second.append("c") | |
first = ["a", "b"] | |
# second = first | |
# second.append("c") | |
add_c_to_list(first) | |
print(first) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment