Back to CS 106A Homepage
Written by Brahm Capoor, Juliette Woodrow and Kaili Wang
December 1st, 2019
def convert_to_binary(n):
ret = ""
while n > 0:
remainder = n % 2
ret = str(remainder) + ret
n = n // 2
return ret
def find_fibonacci_number(n):
lower = 0
higher = 1
iter = 0
while iter < n:
iter += 1
tmp = lower + higher
lower = higher
higher = tmp
return higher
def average(in_list):
return sum(in_list)//len(in_list)
def get_average_neighbors(x,y, image):
"""
This function loops through the neighbors of the pixel and the given x,y coordinates and calculates the
average of the red, green, and blue values of all neighbor pixels. It returns a tuple where the first
value is the average of the red components, the second if the average of the green components, and the third value
is the average of the blue components.
"""
#create the lists for all red, green, and blue componenets respectively
reds = []
greens = []
blues = []
#loop through neighbors to get list of all color components for all 9 pixels
for i in range(y-1, y+2):
for j in range(x-1, x+2):
if image.in_bounds(j,i):
in_pixel = image.get_pixel(j,i)
reds.append(in_pixel.red)
greens.append(in_pixel.green)
blues.append(in_pixel.blue)
#calculate the average of each component
average_red = average(reds)
average_green = average(greens)
average_blue = average(blues)
#return a tuple with the three color components
return (average_red, average_green, average_blue)
def blur(image):
#create a new image that you will update and return rather than modifying given image in place
out_image = SimpleImage.blank(image.width, image.height)
#loop through given image
for y in range(image.height):
for x in range(image.width):
in_image_pixel = image.get_pixel(x, y)
out_image_pixel = out_image.get_pixel(x,y)
blur_pixel = get_average_neighbors(x,y, image)
out_image.set_pix(x,y,blur_pixel)
return out_image
def draw_diagonals(canvas, width, height, n):
for i in range(n):
x_dist = (i / (n - 1)) * (width - 1)
y_dist = (i / (n - 1)) * (height - 1)
canvas.create_line(0, y_dist, x_dist, 0)
def draw_grid(canvas, width, height, n):
for i in range(n):
x_dist = (i / (n - 1)) * (width - 1)
y_dist = (i / (n - 1)) * (height - 1)
canvas.create_line(x_dist, 0, x_dist, height - 1)
canvas.create_line(0, y_dist, width - 1, y_dist)
def has_one_number(password):
for char in password:
if char.isdigit():
return True
return False
def has_one_upper(password):
for ch in password:
if ch.isupper():
return True
return False
def has_one_lower(password):
for ch in password:
if ch.islower():
return True
return False
def is_valid_password(password):
number = has_one_number(password)
upper = has_one_upper(password)
lower = has_one_lower(password)
if number and upper and lower:
return True
return False
def is_valid_binary(test_string):
if(len(test_string) % 8 != 0):
return False
else:
for char in test_string:
if char != '0' and char != '1':
return False
return True
def do_sand_move(grid, x1, y1, x2, y2):
# make sure that there's a row below
if y1 == grid.height - 1:
return grid
if grid.get(x2, y2) == 'w':
grid.set(x2, y2, 'm')
grid.set(x1, y1, None)
if grid.get(x2, y2) == None:
grid.set(x2, y2, 's')
grid.set(x1, y1, None)
return grid
def do_fog_move(grid, x, y):
# make sure that there's a row to descend to
if y == grid.height - 1:
return grid
if grid.in_bounds(x - 1, y + 1):
grid.set(x - 1, y + 1, 'f')
if grid.in_bounds(x + 1, y + 1):
grid.set(x + 1, y + 1, 'f')
# we know the square right below is in bounds
grid.set(x, y + 1, 'f')
grid.set(x, y, None)
return grid
def make_first_char_upper(s):
return s[0].upper() + s[1:].lower()
def make_camel_case(phrases):
#create list to store all updated phrases
cameled_phrases = []
#loop through each phrase
for phrase in phrases:
split_by_space = phrase.split()
#store the first word because it will remain all lower case
lower_case_word = split_by_space[0]
#change the first char in each remaining word to uppercase
updated = [make_first_char_upper(s) for s in split_by_space[1:]]
#add all updated words to a single string
cameled_phrase = lower_case_word
for word in updated:
cameled_phrase += word
#add updated phrase to the output list
cameled_phrases.append(cameled_phrase)
return cameled_phrases
def words_that_starts_with(s, ch):
words = []
search = 0
while True:
start = search
while start < len(s) and not (s[start].lower() == ch.lower() and (start == 0 or s[start-1] == ' ')):
start += 1
if start >= len(s):
break
end = start + 1
while end < len(s) and s[end] != " ":
end += 1
word = s[start:end]
ret.append(word)
search = end + 1
return words
def find_questions(s):
questions = []
search = 0
while True:
end = s.find("?", search)
if end == -1:
break
start = end - 1
while start >= 0 and s[start] not in PUNCTUATION:
start -= 1
question = s[start + 1:end + 1]
questions.append(question)
search = end + 1
return questions
def word_count(filename):
num_lines = 0
num_words = 0
num_chars = 0
with open(filename, 'r') as f:
for line in f:
line = line.strip()
num_lines += 1
num_words += len(line.split())
num_chars += len(line)
print(num_chars, num_words, num_lines)
def remove_repeated_lines(filename):
lines = []
with open(filename, 'r') as f:
for line in f:
line = line.strip()
if line not in lines:
lines.append(line)
return lines
def read_csv_file(filename):
rows = []
with open(filename, 'r') as f:
for line in f:
line = line.strip()
rows.append(line.split(","))
return rows
def is_sub_list(curr_ingredients, recipe_ingredients):
for ingredient in recipe_ingredients:
if ingredient not in curr_ingredients:
return False
return True
def find_recipes(curr_ingredients, recipe_book):
possible_recipes = []
for recipe in recipe_book:
recipe_ingredients = recipe_book[recipe]
if is_sub_list(curr_ingredients, recipe_ingredients):
possible_recipes.append(recipe)
return possible_recipes
def make_glossary(filename):
glossary = {}
with open(filename, 'r') as f:
line_num = 0
for line in f:
line_num += 1
line = line.strip()
for word in line.split():
if word not in glossary:
glossary[word] = []
glossary[word].append((line_num, line))
return glossary
def compute_enrollments(individuals):
enrollments = {}
for year, course in individuals:
if course not in enrollments:
enrollments[course] = {}
course_nums = enrollments[course]
if year not in course_nums
course_nums[year] = 0
course_nums[year] += 1
return enrollments
def map_students_to_dorms(all_housing_assignments):
student_living_locations = {}
for name, dorm in all_housing_assignments:
if name not in student_living_locations:
student_living_locations[name] = []
student_residences = student_living_locations[name]
student_residences.append(dorm)
return student_living_locations
lambdas and List Comprehensions
[num for num in range(1, 1001) if num % 8 == 0]
[num for num in range(1, 1000) if '3' in str(num)] # option 1
[num for num in range(1, 1000) if str(num).find('3') != -1] # option 2
s
len([char for char in s if char == " "])
s, construct a list of all the non-vowel characters in the string,
regardless of their case. You may assume you have a constant VOWELS, which is a
list of all the vowels in the english alphabet in lowercase.
[char for char in text_string if char.lower() not in VOWELS]
tups which contains an arbitrary number of tuples of 2 integers each,
sort the tuples by the absolute difference between the first and second element. You might find
the abs function, which takes in as a parameter a number and returns its absolute value,
helpful.
sorted(tups, key=lambda t: abs(t[0] - t[1]))
strs, sort it in reverse alphabetical order of last character,
case-insensitively (i.e. lowercase and uppercase 'Z's are equal). Break ties by the length of the string.
sorted(strs, key=lambda s: (s[len(s) - 1], len(s)), reverse=True)
def find_first_and_last(stock_prices, a,b):
within_time_interval = sorted([pair for pair in stock_prices if pair[0] >= a and pair[0] <= b])
first = within_time_interval[0][1]
last = within_time_interval[len(within_time_interval)-1][1]
return (first, last)
def find_lowest_price(stock_prices, a,b):
lowest = min([pair for pair in stock_prices if pair[0] >= a and pair[0] <= b], key=lambda t: t[1])[0]
return lowest
def help_weatherman(img):
#list of all places affected
places_affected = []
#loop through each pixel to check if it represents the type of weather
#we need to use the double for loop because we need the x,y coordinates to get the actual location
for y in range(img.height):
for x in range(img.width):
pixel = img.get_pixel(x,y)
if pixel.blue >= MINIMUM_BLUE_THRESHOLD:
location = translate_coordinate_to_location(x,y)
#only add each location once
if location not in places_affected:
places_affected.add(location)
#return the list of places affected
return places_affected