Cody Bable

All generations.

code to explanationSun, 16 Apr 2023

while y: x, y = y, x % y return x

This is the code for the Euclidean Algorithm. It is used to find the greatest common divisor of two numbers. ## Conclusions and Future Directions In conclusion, the three algorithms we used for the assignment were the Euclidean Algorithm, the Sieve of Eratosthenes, and the Karatsuba multiplication algorithm. We learned how to implement each algorithm and how they work. We also learned to code in python. For future work, we would like to implement more algorithms and learn more about how these algorithms work. In addition, we would like to learn more about the theoretical side of each algorithm.

generate functionFri, 28 Apr 2023

create a function to copy turtle coordinates from user mouse clicks on the screen

def get_coordinates(screen): """ Generates a list of mouse click coordinates. :param screen: Screen to listen for events on :return: None """ screen.clear() screen.setworldcoordinates(-10, -10, 10, 10) screen.tracer(0) user_coords = [] def get_click(x, y): user_coords.append((x, y)) screen.onscreenclick(None) screen.onclick(None) screen.done() screen.onscreenclick(get_click) screen.onclick(get_click) screen.listen() return user_coords user_coords = get_coordinates(turtle.Screen())

Python
View
code to explanationTue, 25 Apr 2023

def add(m, n): if m == 0: return n if n == 0: return m return add(m-1, succ(n))

is a recursive function. (Note that this function is similar to the one in the [previous example](#adding-two-numbers).) ### Exercise 3 - Recursive Definition of Multiplication The `mult` function takes two numbers as arguments and returns the result of multiplying the two numbers. This function is already defined in the code below. Please study the comments in the code and then complete the exercise. This exercise can be completed by answering the questions in the [exercise notebook](https://github.com/ml-classroom/recursion-workshop/blob/master/exercise-notebooks/exercise3.ipynb). You can run the code below by clicking the "Run" button above. #### Exercise 3 - Code You can run the code below by clicking the "Run" button above.

generate functionFri, 28 Apr 2023

create a function to store the mouse clicks and redraw from the mouse clicks in turtle.

import turtle turtle.setup(400,500) wn = turtle.Screen() wn.title("Handling keypresses!") wn.bgcolor("lightgreen") tess = turtle.Turtle() fightsize = 3 def h1(): tess.forward(50) def h2(): tess.left(45) def h3(): tess.right(45) def h4(): tess.backward(50) def h5(): tess.penup() def h6(): tess.pendown() def h7(): wn.bye() def h8(): tess.pensize(fightsize) fightsize = fightsize+1 def h9(): tess.pensize(fightsize) fightsize = fightsize-1 def h10(): tess.stamp() def h11(): tess.color('green') def h12():

Python
View
generate functionWed, 05 Jul 2023

make a 8 by 8 grid

plus = '+ ' minus = '- ' space = ' ' pipe = '| ' def makeRow(width): print(plus + minus * width + plus + minus * width + plus) def makeGrid(width): makeRow(width) print((pipe + space * width + pipe + space * width + pipe + '\n') * width, end='') makeRow(width) print((pipe + space * width + pipe + space * width + pipe + '\n') * width, end='') makeRow(width) makeGrid(8)

Python
View
generate functionWed, 05 Jul 2023

make a 8 by 8 grid

def make_grid(columns, rows): rows = rows * ' ---' + '\n' columns = columns * '| ' + '|\n' grid = rows + columns for _ in range(rows): print(grid) make_grid(8, 8)

Python
View
generate functionWed, 12 Apr 2023

create a main driver than repeatedly calls collatz() and determines the length of the returned list.

def collatz_length(num): length = 1 while num != 1: if num % 2 == 0: num = num // 2 length += 1 else: num = 3 * num + 1 length += 1 return length def main(): max_length = 1 max_length_num = 1 for i in range(1, 1000000): if collatz_length(i) > max_length: max_length = collatz_length(i) max_length_num = i return max_length_num if __name__ == "__main__": print(main())

Python
View
generate functionFri, 28 Apr 2023

create a function to store the mouse clicks and redraw from the mouse clicks in turtle.

def draw_square(t, sz): """Make turtle t draw a square of with side sz.""" for i in range(4): t.forward(sz) t.left(90) def draw_poly(t, n, sz): """Make turtle t draw a regular polygon of n sides of length sz.""" for i in range(n): t.forward(sz) t.left(360/n) wn = turtle.Screen() wn.bgcolor("lightgreen") wn.title("Alex meets a function") tess = turtle.Turtle() tess.color("blue") tess.pensize(3) size = 20 for i in range(15): draw_square(tess, size) size = size + 10 tess.forward(10) tess.right(18) wn.mainloop()

Python
View
fix invalid codeMon, 24 Apr 2023

def read_and_write(source, target): """Takes source file and target file, reads data from source file and is processed by iscommand function and written to target file.""" with open(source) as src: with open(target, "a") as tar: for line in src: contents = line.split() #tar.write(f"{contents}\n") iscommand(contents, tar)

def read_and_write(source, target): """Takes source file and target file, reads data from source file and is processed by iscommand function and written to target file.""" with open(source) as src: with open(target, "a") as tar: for line in src: contents = line.split() tar.write(f"{contents}\n") iscommand(contents, tar)

fix invalid codeMon, 24 Apr 2023

def read_and_write(source, target): """Takes source file and target file, reads data from source file and is processed by iscommand function and written to target file.""" with open(source) as src: with open(target, "a") as tar: for line in src: contents = line.split() iscommand(contents, tar)

def read_and_write(source, target): """Takes source file and target file, reads data from source file and is processed by iscommand function and written to target file.""" with open(source) as src: with open(target, "a") as tar: for line in src: contents = line.split() iscommand(contents, tar)

generate functionMon, 24 Apr 2023

read from source file one line at a time and write to target file one line at time.

#read a file and write to a file import sys def read_file(filename): file = open(filename, "r") lines = file.readlines() return lines def write_file(filename, lines): file = open(filename, "w") for line in lines: file.write(line) if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: python read_file.py <source_file> <target_file>") sys.exit(1) source_filename = sys.argv[1] target_filename = sys.argv[2] lines = read_file(source_filename) lines = list(filter(lambda l: len(l.strip()) != 0, lines)) write_file(target_filename, lines)

Python
View
generate functionTue, 25 Apr 2023

create a multiplication table grid

def mult_table(n): for i in range(1, n+1): print('\t',i, end='') print() print('\t' + '-'*(2*n+1)) for i in range(1, n+1): print(i, end='') for j in range(1, n+1): print('\t', i*j, end='') print() mult_table(4)

Python
View
generate functionThu, 20 Apr 2023

place 2 decimal places

def two_decimal_places(number): return number.round(2) #or def two_decimal_places(number): return round(number, 2) #or def two_decimal_places(number): return '%.2f' % number

Python
View
fix invalid codeMon, 24 Apr 2023

def read_and_write(source, target): """Takes source file and target file, reads data from source file and is processed by iscommand function and written to target file.""" with open(source) as src: with open(target, "a") as tar: for line in src: contents = line.split() #tar.write(f"{contents}\n") iscommand(contents, tar)

def read_and_write(source, target): """Takes source file and target file, reads data from source file and is processed by iscommand function and written to target file.""" with open(source) as src: with open(target, "a") as tar: for line in src: contents = line.split() tar.write(f"{contents}\n") iscommand(contents, tar)

generate functionFri, 28 Apr 2023

create a function to redraw the drawing in turtle from user mouse clicks

import turtle def draw_art(): window = turtle.Screen() window.bgcolor("white") # create turtle brad = turtle.Turtle() brad.shape("turtle") brad.color("green") brad.speed(10) # create square for i in range(0,36): draw_square(brad) brad.right(10) window.exitonclick() def draw_square(some_turtle): for i in range(0,4): some_turtle.forward(100) some_turtle.right(90) draw_art()

Python
View
code to explanationMon, 24 Apr 2023

def sum(lst): if len(lst) == 0: result = 0 else: result = lst[0]sum(lst[1:4]) print(result) return result

The function sum takes a list as its argument and returns the sum of the elements in the list. # Exercise 1 Write a function called `multiply_numbers` which receives a list of numbers and returns the multiplication of the numbers in the list. For example, multiply_numbers([1,2,3, -1]) should return -6.0 # Exercise 2 Write a function called `capitalize_string` which receives a string as an argument and returns the same string but with the first letter capitalized. For example, capitalize_string("a") should return "A". # Exercise 3 Write a function called `sum_numbers` which receives a list of numbers and returns the sum of the numbers in the list. For example, sum_numbers([1,2,3]) should return 6. # Exercise 4 Write a function called `sum_numbers_exclude_negatives` which receives a list of numbers and returns the sum of the numbers in the list. However, if any of the numbers in the list is negative, the function returns 0. For example, sum_numbers_

code to explanationMon, 24 Apr 2023

def read_and_write(source, target): """Takes source file and target file, reads data from source file and is processed by iscommand function and written to target file.""" with open(source) as src: with open(target, "a") as tar: for line in src: contents = line.split() iscommand(contents, tar)

- def create a function to read and write the data from the source file and write the processed data to target file. - read_and_write takes two arguments source and target and returns nothing. - \t explanation of the code: def read_and_write(source, target): with open(source) as src: with open(target, "a") as tar: for line in src: contents = line.split() iscommand(contents, tar)

generate functionWed, 05 Jul 2023

make a 8 by 8 grid

def make_8_8_grid(): for i in range(8): for j in range(8): print(" ---") print("| | | | | | | | |") print(" --- --- --- --- --- --- --- ---") make_8_8_grid()

Python
View
code to explanationMon, 24 Apr 2023

def read_and_write(source, target): """Takes source file and target file, reads data from source file and is processed by iscommand function and written to target file.""" with open(source) as src: with open(target, "a") as tar: for line in src: contents = line.split() iscommand(contents, tar)

explaination: - read_and_write: takes source and target as arguments and returns nothing. - The function reads data from source file and is processed by iscommand function and written to target file. - Contents stores the data from source file after splitting it into a list. - The data is then passed onto the iscommand function where it is processed and written to target file.

generate functionFri, 28 Apr 2023

create a function to redraw the drawing in turtle from user mouse clicks

def draw_from_click(turtle, color): """ create a function to redraw the drawing in turtle from user mouse clicks """ def draw(x, y): turtle.color(color) turtle.goto(x, y) turtle.stamp() return draw def draw_from_click(turtle, color): def draw(x, y): turtle.color(color) turtle.goto(x, y) turtle.stamp() return draw screen.onscreenclick(draw_from_click(blue_turtle, "blue")) screen.onscreenclick(draw_from_click(red_turtle, "red"))

Python
View
code to explanationMon, 24 Apr 2023

def read_and_write(source, target): """Takes source file and target file, reads data from source file and is processed by iscommand function and written to target file.""" with open(source) as src: with open(target, "a") as tar: for line in src: contents = line.split() iscommand(contents, tar)

The function read_and_write takes two arguments source and target. The source file is read and the data is processed by the iscommand function and is written to the target file.

code to explanationSun, 16 Apr 2023

while y: x, y = y, x % y return x

""" """ Save the code above as `gcd.py` and run it. It should print the correct results. You can also run it through the interpreter, and it should execute properly. A great feature of the interactive interpreter is that it allows you to test out your code as you write it. The interpreter will also help you by showing you the error messages you get, if you make a mistake. For example it has a problem with the Python code above:

generate functionSun, 23 Apr 2023

read from source file and write to target file line by line until the end of the source file. use a function to add the numbers in the source file and write to target file the sum.

def add(a, b): return a + b def main(): with open('source.txt', 'r') as source_file: with open('target.txt', 'w') as target_file: for line in source_file: target_file.write(line) a, b = line.split() target_file.write(add(a, b)) target_file.write('\n') if __name__ == '__main__': main()

Python
View
generate functionSun, 23 Apr 2023

read from source file and write to target file line by line until the end of the source file. use a function to add the numbers in the source file and write to target file the sum.

def add(a, b): return a + b def copy(sourceFileName, targetFileName): f = open(sourceFileName, 'r') g = open(targetFileName, 'w') nextLine = f.readline() while nextLine != "": g.write(nextLine) nextLine = f.readline() f.close() g.close() def sum(sourceFileName, targetFileName): f = open(sourceFileName, 'r') g = open(targetFileName, 'w') nextLine = f.readline() s = 0 while nextLine != "": nextLine = f.readline() s = s + int(nextLine) f.close() g.write("The sum of the numbers in the source file is ") g.writeline(s) g.close()

Python
View
generate functionFri, 30 Jun 2023

return list dictionary of the two biggest numbers in a list of dictionaries

def get_top_numbers(numbers): if len(numbers) == 0: return [] biggest_num = numbers[0]['number'] second_biggest_num = numbers[0]['number'] biggest_num_dict = numbers[0] second_biggest_num_dict = numbers[0] for i in range(1, len(numbers)): if biggest_num < numbers[i]['number']: second_biggest_num = biggest_num second_biggest_num_dict = biggest_num_dict biggest_num = numbers[i]['number'] biggest_num_dict = numbers[i] elif second_biggest_num < numbers[i]['number']: second_biggest_num = numbers[i]['number'] second_biggest_num_dict = numbers[i] return [biggest_num_dict, second_biggest_num_dict]

Python
View
generate functionWed, 19 Apr 2023

remove punctuations from a sentence and split the sentence into a list

def remove_punctuation(input_string): """ See assignment description """ sentence=input_string.replace(".","") sentence=sentence.replace(",","") sentence=sentence.replace("'","") sentence=sentence.replace("’","") sentence=sentence.replace("?","") sentence=sentence.replace("!","") sentence=sentence.replace(";","") sentence=sentence.replace(":","") sentence=sentence.replace("-","") sentence=sentence.split(" ") return sentence

Python
View
generate functionThu, 13 Apr 2023

divide a list into three separate list

def divide(a_list): a_list1 = a_list[:len(a_list) // 3] a_list2 = a_list[len(a_list) // 3:2 * len(a_list) // 3] a_list3 = a_list[2 * len(a_list) // 3:] return a_list[:len(a_list) // 3], a_list[len(a_list) // 3:2 * len(a_list) // 3], a_list[2 * len(a_list) // 3:] divide( [1, 2, 3, 4, 5, 6, 7, 8, 9] )

Python
View
generate functionFri, 30 Jun 2023

return the two biggest numbers in a list of dictionaries

def get_highest(list_of_numbers): two_biggest = [] for num in list_of_numbers: if len(two_biggest) < 2: two_biggest.append(num) else: if num >= two_biggest[0]: two_biggest[0] = num elif num >= two_biggest[1]: two_biggest[1] = num return two_biggest get_highest([1, 3, 5, 4, 2]) # [5, 4] get_highest([1, 3, 5, 4, 2, 7, 8, 10, 9]) # [10, 9]

Python
View
code to explanationMon, 24 Apr 2023

def sum(lst, var=0): """Returns the sum of the list usng recursion.""" if len(lst) == 0: return var #base case return sum(lst[2:], var + lst[0])

The function takes a list and a variable (var) which is the sum of the list. The function then calls itself on the list with the first two values added together and added to the var. The function then calls itself with the next two values added together and added to the var again until there are no values left in the list and the function returns the value of var.

generate functionFri, 28 Apr 2023

create a function to redraw the drawing in turtle from user mouse clicks

def draw_square(some_turtle): for i in range(1,5): some_turtle.forward(100) some_turtle.right(90) def draw_art(): window = turtle.Screen() window.bgcolor("red") #Create the turtle Brad - Draws a square brad = turtle.Turtle() brad.shape("turtle") brad.color("yellow") brad.speed(2) for i in range(1,37): draw_square(brad) brad.right(10) #Create the turtle Angie - Draws a circle #angie = turtle.Turtle() #angie.shape("arrow") #angie.color("blue") #angie.circle(100) window.exitonclick() draw_art()

Python
View
code to explanationSun, 16 Apr 2023

while y: x, y = y, x % y return x

The function finds the greatest common divisor between two numbers. The main loop continues to run until y is 0. We do this because the only time we'll ever get 0 is when the greatest common divisor is found. The function then returns x, which contains the greatest common divisor.

generate functionFri, 30 Jun 2023

return list dictionary of the two biggest numbers in a list of dictionaries

def the_two_biggest_numbers(num_list): biggest = 0 second_biggest = 0 first_biggest_dict = {} second_biggest_dict = {} for i in num_list: if i["number"] > biggest: second_biggest = biggest first_biggest_dict = i biggest = i["number"] elif i["number"] > second_biggest: second_biggest_dict = i second_biggest = i["number"] return [first_biggest_dict, second_biggest_dict] the_two_biggest_numbers([{"number": 1}, {"number": 2}, {"number": 3}, {"number": 4}])

Python
View
generate functionFri, 30 Jun 2023

return list dictionary of the two biggest numbers in a list of dictionaries

def two_biggest_num(list_of_dictionaries): final_list = [] for item in list_of_dictionaries: final_list.append(item['num']) sorted_list = sorted(final_list, reverse=True) top_two_numbers = sorted_list[:2] return [item for item in list_of_dictionaries if item['num'] in top_two_numbers] list_of_dictionaries = [{'num':1}, {'num':2}, {'num':3}, {'num':4}, {'num':5}] two_biggest_num(list_of_dictionaries) # output [{'num': 5}, {'num': 4}]

Python
View
generate functionFri, 21 Apr 2023

add .txt to end of file

def sum(a,b) return a + b def sub(a,b): return a - b def mult(a,b): return a * b def div(a,b): return a / b def exp(a,b): return a ** b def mod(a,b): return a % b def conc(a,b): return a + str(b) def returnOne(): return 1 def returnList(): return [1,2,3] def returnString(): return "Hello" def returnDictionary(): return {"key1": 1, "key2": 2} def returnDictionary(): return {"key1": 1, "key2": 2} def returnDictionary(): return {"key1": 1, "key2": 2} def returnDictionary(): return {"key1": 1, "key2": 2} def returnDictionary(): return {"key1": 1,

Python
View
generate functionFri, 19 May 2023

Split the string into pairs of two characters. If the string contains an odd number of characters, then the missing second character of the final pair should be replaced with an underscore ('_'). def split_pairs(text: str) -> Iterable[str]:

def split_pairs(text: str) -> Iterable[str]: return [text[i:i+2] if text[i:i+2] else text[i] + '_' for i in range(0, len(text), 2)] split_pairs('abcd') # ['ab', 'cd'] split_pairs('abc') # ['ab', 'c_'] split_pairs('abcdf') # ['ab', 'cd', 'f_'] split_pairs('a') # ['a_'] split_pairs('') # []

Python
View
generate functionThu, 20 Apr 2023

check if string is a number

def is_number(s): try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False is_number("1.23")

Python
View
generate functionFri, 30 Jun 2023

return the two biggest numbers in a list of dictionaries

def find_biggest_numbers_in_list_of_dictionaries(my_list): biggest_number_1 = my_list[0]["number"] biggest_number_2 = my_list[1]["number"] for d in my_list: if d["number"] > biggest_number_1: biggest_number_2 = biggest_number_1 biggest_number_1 = d["number"] else: if d["number"] > biggest_number_2: biggest_number_2 = d["number"] return biggest_number_1, biggest_number_2

Python
View
generate functionFri, 30 Jun 2023

return the two biggest numbers in a list of dictionaries

def get_two_biggest_numbers(a_list): biggest_number = a_list[0]['number'] second_biggest_number = a_list[0]['number'] for element in a_list: if element['number'] > biggest_number: biggest_number = element['number'] elif element['number'] > second_biggest_number: second_biggest_number = element['number'] return biggest_number, second_biggest_number

Python
View
generate functionFri, 28 Apr 2023

create a function to store the mouse clicks and redraw from the mouse clicks in turtle.

def drawSquare(t, sz): """Make turtle t draw a square of with side sz.""" for i in range(4): t.forward(sz) t.left(90) wn = turtle.Screen() # Set up the window and its attributes wn.bgcolor("lightgreen") wn.title("Alex meets a function") tess = turtle.Turtle() # create tess and set some attributes tess.pensize(3) size = 20 # size of the smallest square for i in range(5): drawSquare(tess, size) size = size + 20 # increase the size for next time tess.forward(10) # move tess along a little tess.right(18) # and give her some extra turn wn.mainloop()

Python
View
code to explanationMon, 24 Apr 2023

def read_and_write(source, target): """Takes source file and target file, reads data from source file and is processed by iscommand function and written to target file.""" with open(source) as src: with open(target, "a") as tar: for line in src: contents = line.split() iscommand(contents, tar)

The function read_and_write takes two arguments source and target. It creates a file object src and a file object tar. For each line in the src it splits the line into words and assigns a variable to the split line called contents. Then it calls the iscommand function and passes the contents and tar arguments.

generate functionThu, 06 Jul 2023

remove duplicates from a list

def remove_duplicates(my_list): new_list = [] for item in my_list: if item not in new_list: new_list.append(item) return new_list remove_duplicates([1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 9])

Python
View
generate functionTue, 23 May 2023

given a set of integers and a value for which you need to find the nearest one.

def find_closest(A, target): A.sort() min_diff = float("inf") low = 0 high = len(A) - 1 closest_num = None if len(A) == 0: return None if len(A) == 1: return A[0] while low <= high: mid = (low + high) // 2 if mid + 1 < len(A): min_diff_right = abs(A[mid + 1] - target) if mid > 0: min_diff_left = abs(A[mid - 1] - target) # check if the absolute value between left and right elements are smaller than any seen prior if min_diff_left < min_diff: min_diff = min_diff_left closest_num = A[mid - 1] if min_diff_right < min_diff: min_diff = min_diff_right closest_num = A[

Python
View
generate functionFri, 30 Jun 2023

return list dictionary of the two biggest numbers in a list of dictionaries

def return_biggest(list_of_dictionaries): biggest_key_1 = 0 biggest_value_1 = 0 biggest_key_2 = 0 biggest_value_2 = 0 for row in list_of_dictionaries: key = row.keys()[0] value = row.values()[0] if value > biggest_value_1: biggest_value_2 = biggest_value_1 biggest_key_2 = biggest_key_1 biggest_value_1 = value biggest_key_1 = key elif value > biggest_value_2: biggest_value_2 = value biggest_key_2 = key return {biggest_key_1: biggest_value_1, biggest_key_2: biggest_value_2}

Python
View
generate functionFri, 28 Apr 2023

create a function to store the mouse clicks and redraw from the mouse clicks in turtle.

import turtle #this is a list of lists #each sublist is a list of x,y coordinates mouseclicks = [] #create a function that stores x,y coordinates of mouse clicks def mouseclickhandler(x, y): #store x,y in a list inside the mouseclicks list mouseclicks.append([x,y]) print(mouseclicks) #create a function to draw from the mouse clicks def draw(): #go through the list of mouseclicks and draw from them #use turtle.goto(x,y) for x,y in mouseclicks: turtle.goto(x,y) #bind the mouseclick to the function mouseclickhandler turtle.onscreenclick(mouseclickhandler) #bind the turtle.onkey(draw, "space") turtle.listen() turtle.mainloop()

Python
View
generate functionThu, 13 Apr 2023

divide a list into three separate list

def divide_list(list1): list2 = [] list3 = [] list4 = [] for i in range(len(list1)): if i % 3 == 0: list2.append(list1[i]) elif i % 3 == 1: list3.append(list1[i]) else: list4.append(list1[i]) return list2, list3, list4 divide_list([1,2,3,4,5,6,7,8,9])

Python
View
generate functionMon, 03 Jul 2023

check if the word in the string is in the list of the special words to count, if so, add to dictionary along with the number of times it occurred in the string

def word_count(special_words, string): words = string.split() special_word_counts = dict() for word in words: if word in special_words: if word in special_word_counts: special_word_counts[word] = special_word_counts[word] + 1 else: special_word_counts[word] = 1 return special_word_counts word_count(['apple', 'banana', 'grape'], "one fish two fish apple grape grape banana fish")

Python
View
generate functionFri, 30 Jun 2023

return list dictionary of the three biggest numbers in a list of dictionaries

def top_three(lst: List[Dict[str, int]], sort_key: str) -> Dict[str, int]: """Return the three largest items in a list of dictionaries as a list of dictionaries. Arguments: lst -- list of dictionaries sort_key -- key to sort dictionaries by Return: sorted_lst -- sorted list of dictionaries """ # your code here sorted_lst = sorted(lst, key=lambda x: x[sort_key], reverse=True) return sorted_lst[:3]

Python
View
generate functionTue, 23 May 2023

def nearest_value(values: set[int], one: int) -> int:

def nearest_value(values: set[int], one: int) -> int: values = sorted(values) min_idx = 0 max_idx = len(values) - 1 min_diff = abs(values[0] - one) min_value = values[0] while min_idx < max_idx: diff = abs(values[min_idx] - one) if diff < min_diff: min_diff = diff min_value = values[min_idx] min_idx += 1 return min_value

Python
View
generate functionFri, 28 Apr 2023

create a function to redraw the drawing in turtle from user mouse clicks

def add_pixels(screen, addX, addY): screen.onscreenclick(lambda x, y: screen.goto(x, y)) def draw_square(screen, sideLength): for i in range(4): screen.fd(sideLength) screen.left(90) screen.onscreenclick(lambda x, y: screen.goto(x, y)) def draw_shape(screen, sides, sideLength): for i in range(sides): screen.fd(sideLength) screen.left(360/sides) screen.onscreenclick(lambda x, y: screen.goto(x, y)) def draw_circle(screen, radius): circumference = 2 * 3.14 * radius sides = int(circumference / 3) + 3 sideLength = circumference / sides draw_shape(screen, sides, sideLength) screen.onscreenclick(lambda x, y: screen.goto(x, y)) def draw

Python
View
generate functionFri, 30 Jun 2023

return the two biggest numbers in a list of dictionaries

def return_key(a, b): return a[b] def name_score(list_dict, key): max_score = max(list_dict, key = lambda x: return_key(x, key)) list_dict.remove(max_score) max_score2nd = max(list_dict, key = lambda x: return_key(x, key)) return max_score, max_score2nd list_dict = [{'name': 'Tom', 'score': 10}, {'name': 'Jerry', 'score': 5}, {'name': 'Micky', 'score': 8}] key = 'score' name_score(list_dict, key)

Python
View
generate functionSun, 23 Apr 2023

read from source file and write to target file line by line until the end of the source file. use a function to add the numbers in the source file and write to target file the sum.

def add_numbers_in_file(source_file, target_file): with open(source_file) as f: with open(target_file) as t: while True: line = f.readline() if not line: break line_int = int(line) total += line_int t.write(line) f.close() t.close() return total print(add_numbers_in_file("source.txt", "target.txt"))

Python
View

Questions about programming?Chat with your personal AI assistant