## Cody Bable

All generations.

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): if len(text) % 2 == 0: for i in range(0, len(text),2): print(text[i] + text[i+1]) else: for i in range(0, len(text)-1, 2): print(text[i] + text[i+1]) print(text[-1] + '_')```

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: return min(sorted(values), key=lambda x: abs(x-one))```

Python
View
generate functionThu, 13 Apr 2023

## list comprehension for dividing a list into three lists and reverse the items in the each of the three lists.

```def devide_list_into_three(my_list): return [my_list[:4][::-1], my_list[4:8][::-1], my_list[8:12][::-1]] my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] print(devide_list_into_three(my_list))```

Python
View
generate functionMon, 03 Jul 2023

## count words in a list

```def count_words(word_list): return len(word_list) count_words(['apple', 'mango', 'pear'])```

Python
View
generate functionThu, 13 Apr 2023

## divide this ['a', 'b', 'c', '1', '2', '3','4', '5', '6'] evenly into three separate list

```def partition(my_list, num_buckets): bucket_size = len(my_list) // num_buckets buckets = [] for bucket_index in range(num_buckets): start = bucket_index * bucket_size end = start + bucket_size buckets.append(my_list[start:end]) return buckets```

Python
View
generate functionThu, 13 Apr 2023

## list comprehension for dividing a list into three lists and reverse the items in the each of the three lists.

```def divide(list): return [list[i::3] for i in range(3)] def reverse(list): return [list[::-1] for i in range(3)] def divide_and_reverse(list): return reverse(divide(list)) list = [1, 2, 3, 4, 5, 6, 7, 8, 9] divide_and_reverse(list)```

Python
View
generate functionFri, 19 May 2023

## create a function for min and max of a number

```def min(a, b): if a < b: return a else: return b def max(a, b): if a < b: return b else: return a min(1, 2) max(1, 2)```

Python
View
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 functionThu, 20 Apr 2023

## check if string is a number

```def is_number(string): try: float(string) return True except: return False is_number("123")```

Python
View
generate functionTue, 25 Apr 2023

## create a multiplication table grid using lines and dashes

```def create_grid(w, h, p): result = "" for i in range(h): if i > 0: result += "\n" result += p * w return result print(create_grid(6, 5, "-"))```

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: return min(sorted(values, key=lambda x: abs(x - one)), key=lambda x: abs(x - one))```

Python
View
generate functionFri, 28 Apr 2023

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

```def get_coordinates(): pts = [] while True: x, y = turtle.pos() print(x, y) pts.append((x, y)) if turtle.distance(0,0) < 5: break turtle.home() return pts get_coordinates()```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line until end of file

```with open('input.txt', 'r') as input_file, open('output.txt', 'w') as output_file: for line in input_file: output_file.write(line)```

Python
View
generate functionFri, 19 May 2023

## create a function for min and max of a number

```def minmax(a): if a > 1: return 1 else: return 0 minmax(2)```

Python
View
generate functionTue, 23 May 2023

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

```def nearest_value(values: set, one: int) -> int: return min(values, key=lambda x: abs(x - one))```

Python
View
generate functionTue, 23 May 2023

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

```def find_closest(lst, K): return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))] # Driver code lst = [4, 7, 10, 11, 12, 17] K = 13 print(find_closest(lst, K))```

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.

```with open("source.txt", 'r') as source_file, open("target.txt", 'w') as target_file: for line in source_file: target_file.writelines(line) target_file.writelines('\n')```

Python
View
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
generate functionThu, 29 Jun 2023

## compare numbers in a list and return numbers that smaller than the rest

```def compare(numbers): smaller = [] for x in numbers: smaller.append(x) return smaller compare([1, 2, 3])```

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 functionThu, 06 Jul 2023

## find the next duplicate in the list

```def next_duplicate(L): for i in range(len(L)): for j in range(i + 1, len(L)): if L[i] == L[j]: return L[i] return None next_duplicate([1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1])```

Python
View
code to explanationTue, 25 Apr 2023

## def mpy(m, n): if n == 0: return 0 return add(m, mpy(m, pred(n))) print(mpy(5, 4))

```The function mpy takes two arguments m and n and multiplies them together by adding the first argument, m, to itself n number of times. explanation of the code: def pow(m, n): if n == 0: return 1 return mpy(m, pow(m, pred(n))) print(pow(5, 4))```

generate functionMon, 24 Apr 2023

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

```source_file = open('source.txt', 'r') target_file = open('target.txt', 'w') def read_line(source_file, target_file): source_line = source_file.readline() if source_line == '': return else: target_file.write(source_line) read_line(source_file, target_file) read_line(source_file, target_file) source_file.close() target_file.close()```

Python
View
generate functionThu, 13 Apr 2023

## divide this ['a', 'b', 'c', '1', '2', '3','4', '5', '6'] evenly into three separate list

```def divide(x, y): return x / y divide(10, 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 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 functionFri, 30 Jun 2023

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

```def two_biggest(l): pass l = [ {'id': 5, 'value': 5}, {'id': 2, 'value': 2}, {'id': 3, 'value': 3}, {'id': 4, 'value': 4}, {'id': 9, 'value': 9}, {'id': 1, 'value': 1} ] two_biggest(l)```

Python
View
generate functionFri, 28 Apr 2023

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

```def mouse_click(): x, y = t.pos() t.ondrag(None) t.goto(x, y) t.stamp() t.ondrag(t.goto) def on_click(x, y): red_turtle.goto(x, y) mouse_click() def on_drag(x, y): red_turtle.goto(x, y) mouse_click() red_turtle.ondrag(on_drag) red_turtle.onclick(on_click)```

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 functionThu, 20 Apr 2023

## check if string is a number

```def is_number(str): try: float(str) return True except ValueError: return False is_number("1.0")```

Python
View
generate functionFri, 28 Apr 2023

## create a function to redraw the drawing in turtle

```def draw_square(): for i in range(4): turtle.forward(100) turtle.right(90) draw_square()```

Python
View
code to explanationThu, 13 Apr 2023

## [[a[i][0][::-1]] for i in range(len(a))]

`Returns all the strings in the list a in reverse.`

generate functionThu, 29 Jun 2023

## compare numbers and return the numbers that are smaller in a list

```def compare_numbers(a, b): return [x for x in [a, b] if x < max(a, b)] compare_numbers(2, 1)```

Python
View
code to explanationSun, 16 Apr 2023

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

`The code gets the greatest common denominator of two integers. It uses a while loop to get the remainder of (x,y) until y is 0. If y is 0, then x is the greatest common denominator.`

code to explanationFri, 28 Apr 2023

## tess.clear() for c in range(len(coordinates) - 1): x, y = coordinates[c] #store coordinates from the initial start x2, y2 = coordinates[c + 1] # tess.pendown() tess.goto(x, y) tess.pendown() tess.goto(x2, y2)

`The code above will pick up the pen, and go to the coordinates of the first point it finds, then the pen will be dropped, and the turtle will go to the next point.`

generate functionTue, 23 May 2023

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

```def find_nearest(values, target): values = sorted(values) index = bisect.bisect(values, target) return values[index-1:index+1]```

Python
View
generate functionThu, 13 Apr 2023

## divide a list into three separate list

```def divide_list(a_list): third = len(a_list) // 3 return a_list[:third], a_list[third:2 * third], a_list[2 * third:] divide_list([1, 2, 3, 4, 5, 6, 7, 8, 9])```

Python
View
generate functionMon, 03 Jul 2023

## check if the word is in the special word, if so, add to dictionary along with count

```def get_word_counts(word_list): word_count = {} for word in word_list: if word in word_count: word_count[word] += 1 else: word_count[word] = 1 return word_count get_word_counts(['a', 'b', 'a'])```

Python
View
generate functionFri, 28 Apr 2023

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

```def redraw(x, y): turtle.clear() turtle.goto(x, y) # draw to new position turtle.onscreenclick(redraw)```

Python
View
generate functionTue, 25 Apr 2023

## create a multiplication table grid

```def create_multiplication_table(m, n): for i in range(1, m+1): for j in range(1, n+1): print(i*j, end="\t") print() create_multiplication_table(3, 5)```

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 functionTue, 23 May 2023

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

```def nearest_val(nums, val): diff = [abs(val-i) for i in nums] min_diff = min(diff) return diff.index(min_diff) nearest_val([1,2,3,4,5], 10)```

Python
View
generate functionTue, 23 May 2023

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

```def find_nearest(array, value): array = np.asarray(array) idx = (np.abs(array-value)).argmin() return array[idx] find_nearest(np.array([0, 2.1, 4.3, 6.5, 8.8, 11.0]), 1.5)```

Python
View
generate functionThu, 04 May 2023

## create a function to print data that is in a set, in alphabetical order

```def print_ordered(data): data = sorted(data) for item in data: print(item) print_ordered({'a', 'b', 'c'})```

Python
View
code to explanationThu, 13 Apr 2023

## [[x] for [x] in lst[::-1]]

`This code returns a list of the elements in the list lst but in reverse order.`

code to explanationTue, 25 Apr 2023

## def mpy(m, n): if n == 0: return 0 return add(m, mpy(m, pred(n))) print(mpy(5, 4))

`The function mpy takes two arguments m and n and returns the product of m and n.`

generate functionMon, 24 Apr 2023

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

```def copy(source, target): source_f = open(source) target_f = open(target, 'w') while True: line = source_f.readline() if len(line) == 0: break target_f.write(line) source_f.close() target_f.close() copy('source.txt', 'target.txt')```

Python
View
generate functionFri, 30 Jun 2023

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

```def three_biggest(list_of_dictionaries): return sorted(list_of_dictionaries, key=lambda k: k['num'])[-3:]```

Python
View
generate functionThu, 13 Apr 2023

## divide a list into three separate list

```def divide(list): return list[0:2], list[2:4], list[4:] divide([1, 2, 3, 4, 5, 6])```

Python
View
generate functionFri, 28 Apr 2023

## create a function to redraw the drawing in turtle

```def draw_square(): for i in range(0, 4): turtle.forward(100) turtle.right(90) draw_square()```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def divide_list(list): list1 = [] list2 = [] list3 = [] for i in list: if i.isalpha(): list1.append(i) if i.isnumeric(): list2.append(i) if i.isalnum(): list3.append(i) return list1, list2, list3 divide_list(['a', 'b', 'c', '1', '2', '3'])```

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
generate functionFri, 30 Jun 2023

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

```def two_biggest(d_list): sorted_list = sorted(d_list, key=lambda t:t['number'], reverse=True) return sorted_list[:2] two_biggest([{'number':1}, {'number':3}, {'number':2}, {'number':4}, {'number':7}])```

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(number): if number % 2 == 0: number = number // 2 print(number) return number elif number % 2 == 1: number = 3 * number + 1 print(number) return number def main(): number = int(input('Enter a number: ')) print(collatz(number)) main()```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line until end of file

```def main(file_in, file_out): # your code here main("sample_input.txt", "sample_output.txt")```

Python
View
generate functionFri, 28 Apr 2023

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

```def draw_point(): # draw the point turtle.pendown() turtle.circle(5) turtle.penup() def draw_path(): # draw the path turtle.pendown() turtle.goto(x, y) turtle.penup() def draw(x, y): draw_path() draw_point() turtle.onscreenclick(draw) turtle.listen()```

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, 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]: if len(text) % 2 != 0: text += '_' lst = [text[i:i+2] for i in range(0, len(text), 2)] return lst```

Python
View
generate functionWed, 05 Jul 2023

## make a 8 by 8 grid

```def grid(num): for x in range(num): print(' ---' * num) print('| ' * num, '|') print(' ---' * num) grid(8)```

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(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print( word_count('the quick brown fox jumps over the lazy dog.'))```

Python
View
generate functionFri, 19 May 2023

## create a function for min and max of a number

```def add(a, b): return a + b add(1, 2)```

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]: for i in range(0,len(text),2): yield text[i:i+2]```

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 closest_number(nums, target): nums.sort() for num in nums: if num >= target: return num return nums[0]```

Python
View
code to explanationSun, 16 Apr 2023

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

`The above code is called Euclidean algorithm. It finds the greatest common divisor of two numbers.`

generate functionThu, 20 Apr 2023

## try...except block checking if a file exist

```def check_file(path): try: open(path) return True except FileNotFoundError: return False check_file('test.txt')```

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 process(source, target): target.write(source.readline()) target.write(source.readline()) source = open('test.txt') target = open('target.txt') process(source, target)```

Python
View
generate functionMon, 24 Apr 2023

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

```def copy(source_file, target_file): with open(source_file, 'r') as source: with open(target_file, 'w') as target: for line in source: target.write(line)```

Python
View
generate functionTue, 23 May 2023

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

```def f(a, b): return min(a, key=lambda x:abs(x-b)) a = [1, 2, 3, 4, 5, 6, 7, 8, 9] b = 4.5 f(a, b)```

Python
View
generate functionTue, 23 May 2023

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

```def nearest_value(values: set, one: int) -> int: return min(values, key=lambda x: abs(x - one))```

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: return min(values, key=lambda v: abs(v - one))```

Python
View
generate functionSun, 02 Jul 2023

## store largest to smallest numbers in a list

```def get_max(list): max = list[0] for i in list: if i > max: max = i return max get_max([1, 2, 3, 4])```

Python
View
generate functionThu, 13 Apr 2023

## divide this ['a', 'b', 'c', '1', '2', '3','4', '5', '6'] evenly into three separate list

```def divide_list(list, n): return [ list[i::n] for i in range(n)] divide_list(['a', 'b', 'c', '1', '2', '3','4', '5', '6'],3)```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] evenly into three separate list

```def divide_list(l): return l[:int(len(l)/3)], l[int(len(l)/3):int(len(l)/3)*2], l[int(len(l)/3)*2:] divide_list(['a', 'b', 'c', '1', '2', '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: m = min(values, key=lambda x: abs(x - one)) if m in values: return m return None nearest_value({4, 7, 10, 11, 12, 17}, 9)```

Python
View
code to explanationSun, 16 Apr 2023

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

`is the famous euclidian algorithm for calculating the gcd of two numberes.`

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 an argument and returns the sum of the elements in the list.`

generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line until end of file

```def read_write(read_file, write_file): with open(read_file, 'r') as rf: with open(write_file, 'w') as wf: line = rf.readline() while line: print(line, end='') wf.write(line) line = rf.readline()```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def divide_list(l, a, b): return l[:a], l[a:b], l[b:] divide_list(['a', 'b', 'c', '1', '2', '3'], 2, 5) >> (['a', 'b'], ['c', '1', '2'], ['3'])```

Python
View
code to explanationThu, 13 Apr 2023

## [lst[i:i+3][::-1] for i in range(0, len(lst), 3)]

`This line of code will reverse the order of every 3 elements in list lst.`

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 functionTue, 25 Apr 2023

## create a multiplication table grid greater than 11

```def multiplication_table(width, height): for i in range(1, height+1): for j in range(1, width+1): print("{:4}".format(i*j), end="") print() multiplication_table(13, 13)```

Python
View
generate functionFri, 28 Apr 2023

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

```def redraw(x, y): turtle.goto(x, y) turtle.onscreenclick(redraw)```

Python
View
generate functionThu, 20 Apr 2023

## place 2 decimal places

```def two_decimal_places(n): return round(n, 2)```

Python
View
generate functionWed, 05 Jul 2023

## make a 8 by 8 grid

```def make_grid(columns, rows): return [[0] * columns for i in range(rows)] make_grid(8, 8)```

Python
View
generate functionTue, 23 May 2023

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

```def find_nearest(arr, target): return min(arr, key=lambda x: abs(x-target)) find_nearest([1,2,3,4,5], 7)```

Python
View
generate functionTue, 25 Apr 2023

## create a multiplication table grid

```def multiplication_table(n): for row in range(1, n+1): for col in range(1, n+1): print(str(row*col),end=" ") print() multiplication_table(4)```

Python
View
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 functionWed, 19 Apr 2023

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

```def split_sentence(sentence): sentence = sentence.replace(',', '').replace('.', '').replace('?', '').replace('!', '') return sentence.split(' ') split_sentence('Hello, world.')```

Python
View
generate functionFri, 21 Apr 2023

## add .txt to end of a file name

```def add_txt_file_end(filename): return filename + '.txt' add_txt_file_end(filename = 'test')```

Python
View
generate functionSun, 23 Apr 2023

## remove none from a string

```def remove_none(input): return input.replace('none', '')```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def split(lst): a = [lst[i] for i in range(len(lst)) if lst[i] in 'abcABC'] b = [lst[i] for i in range(len(lst)) if lst[i] not in 'abcABC'] return a, b```

Python
View
generate functionTue, 23 May 2023

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

```def nearest_int(lst, num): return min(lst, key=lambda x:abs(x-num))```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line until end of file

```f= open('path/to/file1','r') f2 = open(path/to/file2,'w') for line in f: f2.write(line) f.close() f2.close()```

Python
View
generate functionFri, 30 Jun 2023

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

```def two_biggest(lst): lst = sorted(lst, key=lambda x: x['value'], reverse=True) return lst[:2] lst = [{'value': 1}, {'value': 2}, {'value': 3}] two_biggest(lst)```

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: return min(sorted(values), key=lambda x: (abs(x - one), x))```

Python
View
generate functionTue, 23 May 2023

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

```import math def nearest_value(values: set, one: int) -> int: return min(values, key = lambda x: math.fabs(x - one))```

Python
View
generate functionTue, 23 May 2023

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

```def near(list, i): for x in list: if abs(i - x) < abs(i - y): y = x return y near([1,2,3,4,5], 4.2)```

Python
View
generate functionTue, 25 Apr 2023

## calculate the product of m x n but without using the * operator. Use both functions below def add(m, n): if m == 0: return n if n == 0: return m return add(m, succ(n)) def succ(n): return n +1

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

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def divide(list): list_1 = [] list_2 = [] list_3 = [] for element in list: if element.isalpha(): list_1.append(element) elif element.isnumeric(): list_2.append(element) else: list_3.append(element) return list_1, list_2, list_1```

Python
View
generate functionTue, 25 Apr 2023

## calculate the product of m x n but without using the * operator. Use both functions below def add(m, n): if m == 0: return n if n == 0: return m return add(m, succ(n)) def succ(n): return n +1

```def product(m, n): if m == 0: return 0 return add(product(dec(m), n), n)```

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
generate functionThu, 04 May 2023

## create a function to print set of data in alphabetical order

```def alphabetical(name): print(sorted(name)) alphabetical(["Jon", "Arya", "Tyrion"])```

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 store the mouse clicks and redraw from the mouse clicks in turtle.

```point = [] def add(x,y): point.append([x,y]) turtle.clear() turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.dot(3, "red") def draw(): for i in point: x = i[0] y = i[1] turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.dot(3, "red") turtle.onscreenclick(add, btn = 1) turtle.onkey(draw, "space")```

Python
View
generate functionTue, 23 May 2023

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

```import numpy as np def find_nearest(array,value): idx = (np.abs(array-value)).argmin() return array[idx] find_nearest([1,2,3,4,5,6,7,8,9],2.5)```

Python
View
code to explanationThu, 13 Apr 2023

## [lst[i:i+3][::-1] for i in range(0, len(lst), 3)]

`This code takes a list and splits it in 3 parts and reverses them.`

generate functionFri, 28 Apr 2023

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

```def copyTurtleCoordinates(turtle): screen = turtle.getscreen() screen.onclick(turtle.goto) turtle = Turtle() copyTurtleCoordinates(turtle)```

Python
View
code to explanationSun, 16 Apr 2023

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

```function: get_gcd(x, y): while y: x, y = y, x % y return x The function get_gcd computes the greatest common denominator of x and y.```

generate functionWed, 05 Jul 2023

## make a 8 by 8 grid

```def grid(): for i in range(8): if i % 2 == 0: print "* " * 4 else: print " *" * 4```

Python
View
generate functionThu, 29 Jun 2023

## compare all the numbers in the list and return when there is a change in direction

```def compare(a): b = [] for i in range(len(a) - 1): if a[i] > a[i + 1]: b.append(-1) elif a[i] < a[i + 1]: b.append(1) else: b.append(0) return b compare([1, 2, 3, 2, 1])```

Python
View
generate functionTue, 25 Apr 2023

## create a multiplication table grid using lines and dashes

```def multiplication_table(size): for i in range(1, size+1): for j in range(1, size+1): print(f'{i*j:4}', end='') print() multiplication_table(12)```

Python
View
generate functionWed, 19 Apr 2023

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

```def remove_punc_split(text): # replace punctuations with spaces text = re.sub('[^\w\s]', ' ', text) return text.split() remove_punc_split('This!! is? a sentence.') # returns ['This', 'is', 'a', 'sentence']```

Python
View
generate functionFri, 21 Apr 2023

## add .txt to end of a file name

```def hello_world(name): print("Hello World, ", name) hello_world("Daniel")```

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 string_word_count(string, word_list): word_dict = {} #your code here return word_dict```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line until end of file

```def read_and_write(in_filename, out_filename): with open(in_filename, 'r') as fin: with open(out_filename, 'w') as fout: for line in fin: fout.write(line)```

Python
View
generate functionFri, 28 Apr 2023

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

```import turtle def get_coordinates(screen): screen.clear() coord_list = [] screen.onscreenclick(coord_list.append) screen.listen() screen.mainloop() return coord_list turtle.Screen() coord_list = get_coordinates(turtle.Screen())```

Python
View
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
generate functionThu, 20 Apr 2023

## calculate the product of 50 integers

```def factorial(n): product = 1 for i in range(1, n+1): product = product * i return product```

Python
View
generate functionFri, 30 Jun 2023

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

```def return_biggest_number_in_list(list_of_dicts, key): # sort list_of_dicts by key # return first two elements```

Python
View
generate functionFri, 21 Apr 2023

## add .txt to end of file

```def addtxt(filename): filename = addtxt(filename)```

Python
View
generate functionFri, 21 Apr 2023

## add .txt to end of file

```def add_txt(f): return f + ".txt"```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def divide_by(num): return num % 3 def divide_list(list): return map(divide_by, list) divide_list(['a', 'b', 'c', '1', '2', '3'])```

Python
View
generate functionThu, 20 Apr 2023

## place 2 decimal places

```def truncate(number, places=2): return number[:places + 1] truncate(1.234, 1)```

Python
View
generate functionTue, 23 May 2023

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

```def find_nearest_number(a, b): return min(a, key = lambda x:abs(x-b))```

Python
View
generate functionSun, 23 Apr 2023

## check if input is file, if not make it a file

```def tofile(input): if isinstance(input, file): input = input.read() if not isinstance(input, str): input = str(input) with open(input, "w") as f: f.write(input) return f tofile(1)```

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_```

generate functionFri, 19 May 2023

## create a function for min and max of a list of numbers

```def min_max(numbers): return min(numbers), max(numbers) min_max([1,2,3,4,5])```

Python
View
generate functionFri, 28 Apr 2023

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

```def redraw(): turtle.clear() turtle.pendown() turtle.goto(pos_list[0]) turtle.goto(pos_list[1]) turtle.goto(pos_list[2]) turtle.goto(pos_list[3])```

Python
View
generate functionFri, 30 Jun 2023

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

```test_data = [{'name': 'Bob', 'age': 25}, {'name': 'Tom', 'age': 18}, {'name': 'Sally', 'age': 39}, {'name': 'Jane', 'age': 45}, {'name': 'Dorothy', 'age': 20}] test_data.sort(key=lambda x: x['age'], reverse=True) print(test_data[0:3])```

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)

```- 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 functionTue, 23 May 2023

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

```def nearest_value(values: set, one: int) -> int: values = list(values) values.sort() if one < values[0]: return values[0] if one > values[-1]: return values[-1] for i in range(1, len(values)): if one < values[i]: return values[i - 1] if abs(one - values[i - 1]) < abs(one - values[i]) else values[i]```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def divider(a): a1 = [] a2 = [] a3 = [] for i in a: if type(i) == str: a1.append(i) else: a2.append(i) a3.append(a1) a3.append(a2) return a3 print(divider(['a', 'b', 'c', '1', '2', '3']))```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def divide(): string_list = ['a', 'b', 'c', '1', '2', '3'] list_1 = [] list_2 = [] list_3 = [] for item in string_list: if item.isalpha(): list_1.append(item) elif item.isdigit(): if int(item) % 2 == 0: list_2.append(item) elif int(item) % 2 ==1: list_3.append(item) return list_1, list_2, list_3 divide()```

Python
View
generate functionTue, 25 Apr 2023

## calculate the product of m x n but without using the * operator. Use both functions below def add(m, n): if m == 0: return n if n == 0: return m return add(m, succ(n)) def succ(n): return n +1

```def mult(a, b): if b == 0: return 0 return a + mult(a, b - 1) mult(5, 4)```

Python
View
code to explanationTue, 25 Apr 2023

## def mpy(m, n): if n == 0: return 0 return add(m, mpy(m, pred(n))) print(mpy(5, 4))

```This function is a multiplication function. It takes the argument m and n and recursively calls itself. i.e. If n is zero then it returns 0. Otherwise it calls the add function and multiplies the value of m and n.```

generate functionWed, 12 Apr 2023

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

```def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1 print('Enter number:') try: n = int(input()) print(n) except ValueError: print('You must enter an integer')```

Python
View
generate functionThu, 20 Apr 2023

## check if string is a number

```def isNumber(string): try: float(string) return True except ValueError: return False isNumber("1") #True```

Python
View
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
generate functionWed, 19 Apr 2023

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

```def remove_punctuation(sentence): string = sentence.translate(None, string.punctuation) return string.split() remove_punctuation('This is a sentence. I want to split it into a list')```

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
generate functionFri, 19 May 2023

## create a function for min and max of a number

```def min_max(a, b, c): if a < b and a < c: return a elif b < a and b < c: return b else: return c```

Python
View
generate functionThu, 20 Apr 2023

## try...except block checking if a file exist

```def file_exists(filename): try: f = open(filename) f.close() return True except FileNotFoundError: return False file_exists('test.txt')```

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]:

```text = 'abc' result = [] for i in range(0, len(text), 2): result.append(text[i:i+2].ljust(2, '_')) result```

Python
View
generate functionWed, 19 Apr 2023

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

```def remove_punc_and_split(s): return "".join([w for w in s if w not in string.punctuation]).split() remove_punc_and_split("I love NLP!")```

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_nearest(s, target): if target in s: return target diff = [] for val in s: diff.append(abs(target - val)) nearest = diff.index(min(diff)) return s[nearest] find_nearest([1, 2, 3, 4, 5], 6)```

Python
View
generate functionFri, 30 Jun 2023

## return the two biggest numbers in a list

```def find_max(lst): biggest = lst[0] for item in lst: if item > biggest: biggest = item return biggest find_max([1, 2, 3, 4, 5, 6, 7])```

Python
View
generate functionTue, 23 May 2023

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

```def find_nearest(numbers, target): numbers.sort() i = 0 j = len(numbers) - 1 while i < j: mid = (i + j) // 2 if numbers[mid] == target: return mid elif numbers[mid] > target: j = mid else: i = mid + 1 return (i + j) // 2 find_nearest([1, 2, 3, 4, 5, 6, 7, 10, 15], 3)```

Python
View
generate functionFri, 19 May 2023

## create a function for min and max of a number

```def min_max(a, b): if a < b: return a elif b < a: return b else: return 'equal' min_max(5, 4)```

Python
View
generate functionWed, 19 Apr 2023

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

```import string def remove_punct(s): return s.translate(string.punctuation) remove_punct("This is a sentence.")```

Python
View
generate functionFri, 28 Apr 2023

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

```def drawLine(x1, y1, x2, y2): t.penup() t.goto(x1, y1) t.pendown() t.goto(x2, y2) def clear(): t.clear() t.reset() t.hideturtle() t.color('black') t.speed(0) def draw(): clear() s.onclick(drawLine) wn.onclick(drawLine)```

Python
View
generate functionFri, 30 Jun 2023

## return the two biggest numbers in a list

```def bigger(a,b): if a > b: return 'a' else: return 'b'```

Python
View
generate functionFri, 30 Jun 2023

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

```def top_three(input): return sorted(input, key=lambda k: k['value'], reverse=True)[:3] l = [ {'name': 'Hector', 'value': 20}, {'name': 'Gandalf', 'value': 100}, {'name': 'John', 'value': 12}, {'name': 'Aaron', 'value': 3} ] top_three(l)```

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.`

generate functionThu, 20 Apr 2023

## place 2 decimal places

```def format_number(number): return format(number, '.2f') format_number(2.345)```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line until end of file

```with open('../Data/test.txt') as f: with open('../Data/output.txt', 'w') as f1: for line in f: f1.write(line)```

Python
View
generate functionThu, 13 Apr 2023

## list comprehension for dividing a list into three lists and reverse the items in the each of the three lists.

```def list_comprehension(): a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] b = [i for i in a if i%3 == 0] c = [i for i in a if i%3 == 1] d = [i for i in a if i%3 == 2] b.reverse() c.reverse() d.reverse() return [b, c, d]```

Python
View
generate functionThu, 04 May 2023

## create a function to print set of data in alphabetical order

```def alphabetical(str): return sorted(str) alphabetical("mango")```

Python
View
generate functionFri, 28 Apr 2023

## create a function to redraw the drawing in turtle

```def draw_square(): for i in range(4): t.fd(100) t.lt(90)```

Python
View
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 functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def divide(list): list1 = [list[i] for i in range(0, len(list), 3)] list2 = [list[i] for i in range(1, len(list), 3)] list3 = [list[i] for i in range(2, len(list), 3)] return list1, list2, list3```

Python
View
generate functionTue, 25 Apr 2023

## calculate the product of m x n but without using the * operator

```def mul(a, b): if a < 0 or b < 0: raise ValueError("Inputs must be non-negative integers.") elif a == 0 or b == 0: return 0 else: return a + mul(a, b - 1)```

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 takes source file name and target file name and reads data from source file and is processed by iscommand function and written to target file.`

generate functionFri, 30 Jun 2023

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

```def top_3_max_numbers(list_of_dictionaries): return sorted(list_of_dictionaries, key=lambda x: x['value'])[-3:] top_3_max_numbers([{'name': 'a', 'value': 1}, {'name': 'b', 'value': 2}, {'name': 'c', 'value': 3}, {'name': 'd', 'value': 4}, {'name': 'e', 'value': 5}])```

Python
View
generate functionMon, 24 Apr 2023

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

```def copy(src_file, target_file): with open(src_file) as fin: with open(target_file, 'w') as fout: while True: line = fin.readline() if not line: break fout.write(line) copy('source.txt', 'target.txt')```

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 closest(lst, K): lst = sorted(lst) return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))] # Driver code lst = [1,2,3,4,8] K = 2 print(closest(lst, K))```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line until end of file

```with open(infile, 'r') as inf, open(outfile, 'w') as outf: for line in inf: outf.write(line) f = open(infile, 'r') try: for line in f: print(line) finally: f.close() with open(infile, 'r') as f: for line in f: print(line)```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def split_list(lst): lst1 = lst[0:2] lst2 = lst[2:4] lst3 = lst[4:] return lst1, lst2, lst3 split_list(['a', 'b', 'c', '1', '2', '3'])```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line until end of file

```def f(x): return x*x f(2)```

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 in a list and a variable and returns the sum of the list. It has a two base cases if the list is empty it returns 0 and if the list has only 1 element it returns the element.`

generate functionSun, 23 Apr 2023

## check if input is file, if not make it a file

```def make_file(filename): if '.txt' in filename: pass else: filename = filename + '.txt' return filename filename = 'test' make_file(filename)```

Python
View
generate functionFri, 28 Apr 2023

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

```def get_coordinates(): coordinates = [] def add_coordinate(x, y): coordinates.append((x, y)) screen.onclick(add_coordinate) return coordinates```

Python
View
code to explanationThu, 13 Apr 2023

## [lst[i:i+3][::-1] for i in range(0, len(lst), 3)]

```The code above is a list comprehension that takes every 3 elements from a list and returns a new list where we have reversed the elements in every 3 elements```

generate functionFri, 28 Apr 2023

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

```def getMouseCoordinates(): turtle.onscreenclick(turtle.goto) getMouseCoordinates()```

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: l = sorted(list(values)) i = bisect_left(l, one) if i == len(l): return l[i-1] if i == 0: return l[i] return l[i-1] if abs(l[i-1] - one) < abs(l[i] - one) else l[i]```

Python
View
generate functionFri, 19 May 2023

## create a function for min and max of a number

```def minmax(numbers): return min(numbers), max(numbers) minmax([1,2,4,5,6,7,8,9,10])```

Python
View
generate functionTue, 23 May 2023

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

```l = [1, 2, 4, 5, 6, 7, 9] def find_nearest(l, x): return min(l, key=lambda y:abs(y-x)) find_nearest(l, 3)```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line until end of file

```def read_file(in_filename): out_filename = in_filename + '_out' with open(in_filename) as in_file, open(out_filename, 'w') as out_file: for line in in_file: out_file.write(line) read_file('test.txt')```

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: # your code here l = list(values) l.sort() l.insert(0, -abs(l[0] - one)) l.insert(len(l), abs(l[-1] - one)) z = list(map(lambda x: abs(one - x), l)) return l[z.index(min(z))]```

Python
View
generate functionThu, 20 Apr 2023

## check if string is integer or float

```def check_if_int_or_float(string): try: int(string) return 'integer' except: try: float(string) return 'float' except: return 'string' check_if_int_or_float('3') #returns 'integer'```

Python
View
generate functionFri, 28 Apr 2023

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

```from turtle import * def createCoord(x, y): print((x,y)) getscreen().onclick(createCoord)```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line until end of file

```with open("data/example_file.txt", "r") as input_file, open("data/example_file_out.txt", "w") as output_file: for line in input_file: output_file.write(line)```

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))

```The function add takes two arguments m and n, if m is zero it returns n and if n is zero it returns m. If neither m nor n is zero, the function subtracts 1 from m, then adds 1 to n and then calls itself with the result.```

generate functionFri, 19 May 2023

## create a function to split a string into pairs: "abcd" = "ab", "cd"

```def split_into_pair(s): return s[0:2], s[2:4] split_into_pair("abcd")```

Python
View
generate functionMon, 03 Jul 2023

## check if the word is in the special word of the string, if so, add to dictionary along with count

```def find_word(string, word): string_list = string.split() word_dict = {} for i in string_list: if i == word: if i in word_dict: word_dict[i] += 1 else: word_dict[i] = 1 return word_dict find_word("My name is Joy. I like computer science.", "joy")```

Python
View
generate functionFri, 28 Apr 2023

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

```def get_coordinates(distance, angle): # get x,y coordinates from distance and angle x = distance * math.cos(angle * math.pi / 180.0) y = distance * math.sin(angle * math.pi / 180.0) return (x, y) click1 = get_coordinates(distance_from_center, degrees_from_north) click2 = get_coordinates(distance_from_center, degrees_from_north)```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line

```def copy(input_file, output_file): in_file = open(input_file, 'r') out_file = open(output_file, 'w') for line in in_file: out_file.write(line) in_file.close() out_file.close() copy('input.txt', 'output.txt')```

Python
View
generate functionWed, 05 Jul 2023

## You are given a set of square coordinates where we have placed white pawns. You should count how many pawns are safe.

```def safe_pawns(pawns): pawns = [pawns[i:i + 2] for i in range(0, len(pawns), 2)] pawns = [chr(int(pawn[0]) + 97) + str(int(pawn[1]) - 1) for pawn in pawns] count = 0 for pawn in pawns: if chr(ord(pawn[0]) - 1) + str(int(pawn[1]) - 1) in pawns or chr(ord(pawn[0]) + 1) + str(int(pawn[1]) - 1) in pawns: count += 1 return count```

Python
View
generate functionFri, 30 Jun 2023

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

```def two_biggest_numbers(l): return max(l, key=lambda x: x['number'])```

Python
View
generate functionFri, 28 Apr 2023

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

```def draw(x, y, r, g, b): turtle.goto(x, y) turtle.pencolor(r, g, b) turtle.pendown() turtle.circle(10) turtle.penup() turtle.onscreenclick(draw)```

Python
View
code to explanationSun, 16 Apr 2023

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

```### **TODO**: - [ ] The code for the function```

generate functionFri, 28 Apr 2023

## create a function to redraw the drawing in turtle

```def draw(t, length, n): if n == 0: return angle = 50 t.fd(length*n) t.lt(angle) draw(t, length, n-1) t.rt(2*angle) draw(t, length, n-1) t.lt(angle) t.bk(length*n) draw(bob, length=100, n=4)```

Python
View
code to explanationSun, 16 Apr 2023

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

`This is the Euclidean algorithm which finds the greatest common divisor of two numbers.`

generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] evenly into three separate list

```def divide_list(a_list): return [a_list[:len(a_list)/3], a_list[len(a_list)/3:(len(a_list)/3)*2], a_list[(len(a_list)/3)*2:]] divide_list(['a', 'b', 'c', '1', '2', '3'])```

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 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 functionTue, 25 Apr 2023

## create a multiplication table

```def mult_table(size): for i in range(1, size + 1): for j in range(1, size + 1): print(i * j, end='\t') print() mult_table(12)```

Python
View
generate functionFri, 19 May 2023

## create a function for min and max of a list of numbers

```def min(list): lowest = list[0] for i in list: if i < lowest: lowest = i return lowest min([1,2,3,4,5])```

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_file(source, target): with open(source) as source_file, open(target, 'w') as target_file: for line in source_file: target_file.write(str(sum(map(int, line.split()))) + '\n') add_file('source.txt', 'target.txt')```

Python
View
generate functionFri, 28 Apr 2023

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

```def process_mouse_clicks(x, y): t.goto(x, y) t.pendown() t.circle(10) t.penup()```

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 functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def separate(list): return list[:3], list[3:6], list[6:] separate(['a', 'b', 'c', '1', '2', '3'])```

Python
View
generate functionFri, 30 Jun 2023

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

```def returnTwoBiggest(listOfDictionaries): #first we must sort the list listOfDictionaries.sort(key=lambda x: x['number']) #then we return the last two elements return listOfDictionaries[-1], listOfDictionaries[-2] returnTwoBiggest([{number: 1}, {number: 2}, {number: 3}])```

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 closest_int_to(a, b): return sorted(a, key = lambda x: abs(x-b))[0] closest_int_to([10, 11, 12, 13, 14], 9)```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def divide(l): return [l[: len(l)//3]], [l[len(l)//3 : 2 * len(l)//3]], [l[2 * len(l)//3 :]] divide(['a', 'b', 'c', 'd', 'e', 'f'])```

Python
View
generate functionThu, 13 Apr 2023

## divide this ['a', 'b', 'c', '1', '2', '3','4', '5', '6'] evenly into three separate list

```l = ['a', 'b', 'c', '1', '2', '3','4', '5', '6'] def split(l, num_of_groups): return [l[i::num_of_groups] for i in range(num_of_groups)] split(l,3)```

Python
View
generate functionThu, 20 Apr 2023

## try...except block checking if a file exist

```def check_file(file): try: with open(file, 'rb') as f: return True except IOError: return False check_file('file.txt')```

Python
View
generate functionFri, 30 Jun 2023

## return the two biggest numbers from a list

```def get_biggest(arr): if len(arr) < 2: return None return sorted(arr)[-2] get_biggest([1,2,3,4]) # 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: return min(sorted(values), key=lambda x: abs(x - one))```

Python
View
generate functionMon, 03 Jul 2023

## check if the word is in the special word of the text, if so, add to dictionary along with count

```def check_word(word, special_word, dictionary): if word == special_word: if word not in dictionary: dictionary[word] = 1 else: dictionary[word] += 1```

Python
View
generate functionFri, 30 Jun 2023

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

```def get_two_biggest(lst): lst.sort(key=lambda x: x['num'], reverse=True) return lst[:2] get_two_biggest([{'num': 1}, {'num': 2}, {'num': 3}])```

Python
View
generate functionFri, 30 Jun 2023

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

```def largest_num(list_of_dicts): return sorted(list_of_dicts, key=lambda x: x["number"], reverse=True)[:2] largest_num([{'number': 1}, {'number': 10}, {'number': -3}])```

Python
View
generate functionTue, 23 May 2023

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

```def find_nearest(array, value): index = (np.abs(array - value)).argmin() return array[index]```

Python
View
generate functionThu, 20 Apr 2023

## product sum of 50 integers

```def product_sum(n): sum = 0 for i in range(1, n+1): sum = sum + i * i return sum product_sum(50)```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def separate_list(list): list_length = len(list) first_list_length = int(list_length/3) first_list = list[:first_list_length] second_list = list[first_list_length:first_list_length*2] third_list = list[first_list_length*2:] return first_list, second_list, third_list```

Python
View
generate functionTue, 25 Apr 2023

## create a multiplication table grid

```def print_table(n): for i in range(1, 11): print(n, 'x', i, '=', n*i) print_table(7)```

Python
View
generate functionThu, 06 Jul 2023

## find the next duplicate in the list

```def next_duplicate(l): for i in range(len(l)): for j in range(i+1, len(l)): if l[i] == l[j]: return l[i] return None next_duplicate([1, 2, 3, 4, 5, 6, 2])```

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(num): vals = [num] while num > 1: if num % 2 == 0: num /= 2 else: num = num * 3 + 1 vals.append(int(num)) return vals```

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 functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def separate(a, b, c, d, e, f): return [a, b, c], [d, e, f] separate('a', 'b', 'c', '1', '2', '3')```

Python
View
generate functionWed, 05 Jul 2023

## make a 8 by 8 grid

```def grid_8_by_8(x, y): for i in range(1, 9): print(str(x) + ' ' + str(y)) x = x + 5 y = y + 5 grid_8_by_8(1, 2)```

Python
View
generate functionFri, 21 Apr 2023

## add .txt to end of file

```def add(file_name): return file_name + '.txt' add('blah')```

Python
View
generate functionSun, 23 Apr 2023

## tell the difference between integer or float of a number.

```def type_of_number(a): if a % 1 == 0: return "integer" else: return "float" type_of_number(2.2)```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def my_fun(l): return l[0:2], l[2:4], l[4:6] my_fun(['a', 'b', 'c', '1', '2', '3'])```

Python
View
generate functionFri, 21 Apr 2023

## add .txt to end of file

```def add_text_to_file(file_name): file_name = file_name + '.txt' return file_name add_text_to_file("dear_diary")```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] evenly into three separate list

```def split_list(input_list): """ Split a list into 3 evenly sized chunks """ length = int(round(len(input_list) / 3.0)) return [input_list[i * length:(i + 1) * length] for i in range(3)] split_list(['a', 'b', 'c', '1', '2', '3'])```

Python
View
generate functionTue, 25 Apr 2023

## create a multiplication table grid

```def create_multiplication_table(number): def mul(i): return number * i return mul multiplier = create_multiplication_table(9) print multiplier(1) print multiplier(2) print multiplier(10)```

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. add the numbers in the source file and write to target file the sum.

```def read_file_write_file(src_file, dst_file): with open(src_file, 'r') as src, open(dst_file, 'w') as dst: while True: line = src.readline() if not line: break dst.write(line) read_file_write_file('src.txt', 'dst.txt')```

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 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 read(source, target): with open(source, 'r') as s, open(target, 'w') as t: line1 = s.readline() line2 = s.readline() t.write(add(int(line1), int(line2))) return read('number1.txt', 'number2.txt')```

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: nearest = min(values, key=lambda x: abs(one-x)) return nearest```

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))

`The function add takes two arguments m and n and returns the result of adding m to n.`

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): result = [] for i in range(len(text) // 2 + 1): if (i == len(text) // 2) and (len(text) % 2 != 0): result.append(text[i * 2] + "_") else: result.append(text[i * 2:i * 2 + 2]) return result```

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, 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(a): if len(a) % 2 == 0: return [a[i:i + 2] for i in range(0, len(a), 2)] else: return [a[i:i + 2] for i in range(0, len(a) - 1, 2)] + [a[-1] + '_']```

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 nearest_value(values: set, one: int) -> int: lst = list(values) lst.sort() if one <= lst[0]: return lst[0] if one >= lst[-1]: return lst[-1] for i in range(len(lst)-1): if lst[i] < one < lst[i+1]: if one - lst[i] > lst[i+1] - one: return lst[i+1] else: return lst[i]```

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 = set(values) values.add(one) l = sorted(values) return l[l.index(one) - 1] if l.index(one) > 0 else l[l.index(one) + 1]```

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
generate functionTue, 23 May 2023

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

```def nearest_value(values: set, one: int) -> int: return min(values, key=lambda x: abs(x-one)) nearest_value({4, 7, 10, 11, 12, 17}, 9)```

Python
View
generate functionFri, 28 Apr 2023

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

```def draw_by_click(x, y): # code to draw something here canvas.bind("<Button-1>", draw_by_click)```

Python
View
generate functionTue, 25 Apr 2023

## create a multiplication table grid without tabs

```def mult(n, m): for i in range(n): for j in range(m): print(i * j, end='') print('') mult(10, 10)```

Python
View
generate functionTue, 23 May 2023

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

```def find_nearest(value, array): idx = (np.abs(array-value)).argmin() return array[idx] my_array = np.arange(0, 10, 0.5) value = 3.4 find_nearest(value, my_array)```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] evenly into three separate list

```def divide_list(list, num_divide): return [list[index::num_divide] for index in range(num_divide)] divide_list(['a', 'b', 'c', '1', '2', '3'], 3)```

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. add the numbers in the source file and write to target file the sum.

```with open("source.txt", "r") as sourcefile: with open("target.txt", "w") as targetfile: sum = 0 while True: read = sourcefile.readline() if not read: break sum += int(read) targetfile.write(str(sum))```

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: return min(sorted(values, key=lambda x: abs(x - one)), key=lambda x: abs(x - one))```

Python
View
generate functionFri, 30 Jun 2023

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

```data = [ {'age': 43, 'name': 'Alice'}, {'age': 53, 'name': 'Bob'}, ] def biggest(data): return sorted(data, key=lambda x: x['age'], reverse=True)[:2] biggest(data)```

Python
View
code to explanationThu, 13 Apr 2023

## [lst[i:i+3][::-1] for i in range(0, len(lst), 3)]

`will print the list of the numbers in reverse order`

generate functionTue, 23 May 2023

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

```def nearest_value(values: set[int], one: int) -> int: return min(sorted(values), key=lambda x:abs(one-x))```

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: return min(sorted(values), key=lambda x: abs(x-one))```

Python
View
generate functionFri, 21 Apr 2023

## how to check for end of file

```is_end_of_file = False if(is_end_of_file): print("end of file") is_end_of_file = True if(is_end_of_file==True): print("end of file")```

Python
View
generate functionFri, 30 Jun 2023

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

```def sort_two_biggest_numbers(lst): sorted_list = sorted(lst, key=lambda x: x['value']) return sorted_list[-2:] lst = [{'value': 1}, {'value': 2}, {'value': 3}] print(sort_two_biggest_numbers(lst))```

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: return min(sorted(values), key=lambda x: abs(x - one))```

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 functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def divide_list(lst): return [lst[:3], lst[3:6], []] divide_list(['a', 'b', 'c', '1', '2', '3'])```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line until end of file

```def read_write_file(read_file, write_file): data = open(read_file, 'r') data_to_write = open(write_file, 'a') for line in data: if '\n' in line: line = line[:-1] data_to_write.write(line + '\n') data.close() data_to_write.close() read_write_file('some_file', 'some_new_file')```

Python
View
generate functionThu, 20 Apr 2023

## try...except block checking if a file exist

```def checkFileExist(file, path): try: with open(os.path.join(path, file)) as f: return True except FileNotFoundError: return False```

Python
View
generate functionMon, 24 Apr 2023

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

```# write a function to read from source file one line at a time and write to target file one line at time. def copy(source, target): source_file = open(source, 'r') target_file = open(target, 'w') for line in source_file.readlines(): target_file.write(line) source_file.close() target_file.close() copy('a.txt', 'b.txt')```

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: def nearest_value(values: set[int], one: int) -> int: return min(values, key=lambda x: (abs(x - one), x))```

Python
View
generate functionMon, 24 Apr 2023

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

```def readFile(filename, targetFile): f = open(filename, "r") t = open(targetFile, "w") for l in f.readlines(): t.write(l) f.close t.close readFile("sample.txt", "target.txt")```

Python
View
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
generate functionFri, 30 Jun 2023

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

```def biggest_in_list(list_of_dicts): max1 = list_of_dicts[0] max2 = list_of_dicts[0] for i in list_of_dicts: if i['number'] > max1['number']: max2 = max1 max1 = i elif i['number'] > max2['number']: max2 = i return [max1, max2] biggest_in_list([{'name': 'A', 'number': 1}, {'name': 'B', 'number': 10}, {'name': 'C', 'number': 100}])```

Python
View
generate functionThu, 13 Apr 2023

## divide this ['a', 'b', 'c', '1', '2', '3','4', '5', '6'] evenly into three separate list into one single list

```def list_splitting(list_of_items): list_of_list = [] for x in range(0, len(list_of_items), 3): single_list = list_of_items[x:x+3] list_of_list.append(single_list) return list_of_list list_splitting(['a', 'b', 'c', '1', '2', '3', '4', '5', '6'])```

Python
View
generate functionSun, 23 Apr 2023

## tell the difference between integer or float of a number.

```def get_type(a): if type(a) == int: return 'int' elif type(a) == float: return 'float' else: return 'unknown' get_type(1) get_type(1.1) get_type('1')```

Python
View
generate functionSun, 23 Apr 2023

## check input if file is in system, if not make the it a file

```def is_a_file(input_f, output_f): with open(input_f, 'r') as f: with open(output_f, 'w') as g: for line in f: g.write(line) is_a_file('foo.txt', 'bar.txt')```

Python
View
generate functionTue, 25 Apr 2023

## calculate the product of m x n but without using the * operator

```def multiply(m, n): product = 0 while n > 0: product = add(m, product) n -= 1 return product multiply(5, 4)```

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.`

code to explanationSun, 16 Apr 2023

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

`The above code is a function which finds the gcd of x and y.`

generate functionTue, 23 May 2023

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

```def nearest_value(values: set[int], one: int) -> int: values = set(values) values.remove(one) return min(values, key=lambda x: abs(x - one))```

Python
View
generate functionTue, 25 Apr 2023

## create a multiplication table grid

```def multiplication_table(a, b): for i in range(1, a+1): for j in range(1, b+1): print(i*j, end=' ') print() multiplication_table(3, 3)```

Python
View
generate functionSun, 02 Jul 2023

## store largest to smallest numbers in a list

```def order_list(numbers): ordered_numbers = [] for number in numbers: ordered_numbers.append(number) return ordered_numbers order_list([2, 4, 1, 3, 5])```

Python
View
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 functionWed, 19 Apr 2023

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

```# Punctuations punctuations = '''!()-[]{};:'"\,<>./?@#\$%^&*_~''' def remove_punctuations(text): no_punct = "" for char in text: if char not in punctuations: no_punct = no_punct + char return no_punct remove_punctuations("Hello!!!, he said ---and went.")```

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, 30 Jun 2023

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

```def two_biggest_numbers(dicts): return sorted(dicts, key=lambda x: x['number'], reverse=True)[:2] names = [ { 'name': 'Cheryl', 'number': 79 }, { 'name': 'Michael', 'number': 100 }, { 'name': 'Leo', 'number': 1 }, { 'name': 'Edward', 'number': 12 }, ] two_biggest_numbers(names)```

Python
View
generate functionFri, 19 May 2023

## create a function for min and max of a number

```def minn(a, b): if a < b: return a else: return b def maxx(a, b): if a > b: return a else: return b minn(3, 5) maxx(3, 5)```

Python
View
code to explanationThu, 13 Apr 2023

## [[a[i][0][::-1]] for i in range(len(a))]

`reverses the first element (i.e. the string) of every inner list and returns the resulting list.`

generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def divide(a_list): return a_list[:3], a_list[3:6], a_list[6:] divide(['a', 'b', 'c', '1', '2', '3'])```

Python
View
generate functionTue, 25 Apr 2023

## create a multiplication table grid

```def multiplication_table(number): # Loop 10 times from i = 1 to 10 for i in range(1,11): print(number, 'x', i, '=', number*i) multiplication_table(3)```

Python
View
generate functionFri, 30 Jun 2023

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

```def three_biggest(a_list_of_numbers): a_list_of_numbers.sort() return a_list_of_numbers[-3:]```

Python
View
generate functionFri, 30 Jun 2023

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

```def biggest_number_dicts(dictionaries): for dictionary in dictionaries: if dictionary["number"] > biggest_number: biggest_number = dictionary["number"] return biggest_number biggest_number_dicts([{"number": 10}, {"number": 5}, {"number": 20}])```

Python
View
generate functionFri, 30 Jun 2023

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

```def get_maximum(lst, key): return max(lst, key=lambda item: item[key]) get_maximum([{'a': 1}, {'a': 3}, {'a': 2}], 'a')```

Python
View
generate functionFri, 21 Apr 2023

## how to check for end of file

```def check_end_of_file(x): if x == 'end': return True return False check_end_of_file('end') check_end_of_file('not')```

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 nearest(x, vals): return min(vals, key=lambda y: abs(x - y)) nearest(2, {3, 5})```

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)

```1. line is read from source file 2. line is split 3. split line is passed to iscommand function 4. line is written to target file```

generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def separate(list): return list[:3], list[3:6] separate(['a', 'b', 'c', '1', '2', '3'])```

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 functionTue, 23 May 2023

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

```def nearest_value(values: set, one: int) -> int: # your code here return min(values, key=lambda x:abs(x-one))```

Python
View
generate functionThu, 13 Apr 2023

## divide a list into three separate list

```def divide(list): list_one = list[:len(list)/3] list_two = list[len(list)/3+1:2*(len(list)/3)] list_three = list[2*(len(list)/3)+1:] return list_one, list_two, list_three list_one, list_two, list_three = divide(list)```

Python
View
generate functionSun, 23 Apr 2023

## try except a division by zero

```def divide(a, b): try: return a / b except ZeroDivisionError: return "Division by zero is not allowed."```

Python
View
generate functionFri, 19 May 2023

## create a function to split a string into pairs: "abcd" = "ab", "cd"

```def split_string(string_to_split): return [string_to_split[i:i+2] for i in range(0, len(string_to_split), 2)] split_string("abcd")```

Python
View
generate functionThu, 20 Apr 2023

## check if string is a number

```def is_number(s): try: float(s) return True except ValueError: return False is_number("1")```

Python
View
generate functionMon, 03 Jul 2023

## count the individual number of words in a sentence that occur in the special words list

```def words_in_list(words, special_words): count = 0 for word in words: if word in special_words: count += 1 return count words_in_list(["hello", "world", "this", "is", "my", "function"], ["hello", "world"])```

Python
View
generate functionFri, 21 Apr 2023

## add .txt to end of file

```file_name = "hello" file_name_with_extension = file_name + ".txt"```

Python
View
generate functionSun, 23 Apr 2023

## tell the difference between integer or float of a number.

```def isint(a): return isinstance(a, int) isint(2)```

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. if the special word is not in the string, return the special word with zero.

```def count_words(s, n): # To do return {} count_words("cat bat mat cat bat cat", ["cat", "bat", "mat"])```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```list1 = ['a', 'b', 'c'] list2 = ['1', '2', '3'] # sorted: sort the list1 and list2 alphabetically def divide(list1): list1.sort() list2.sort() return list1, list2 divide(list1)```

Python
View
generate functionTue, 23 May 2023

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

```def nearest(n, v): return min(v, key=lambda x:abs(x-n))```

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_nearest(list, value): return min(list, key=lambda x:abs(x-value)) list = [1, 4, 6, 9, 13, 18] find_nearest(list, 3)```

Python
View
generate functionFri, 28 Apr 2023

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

`turtle.onscreenclick(turtle.goto)`

Python
View
generate functionFri, 28 Apr 2023

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

```def copy_turtle(turtle_num): screen = turtle.Screen() screen.setup(800, 800) screen.title("Click to get coordinates") screen.onclick(turtle_num.goto) screen.listen() screen.mainloop() t = turtle.Turtle() t2 = turtle.Turtle() copy_turtle(t2)```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def divide(lst, n): return [lst[i*n:(i+1)*n] for i in range(len(lst)/n)] divide(['a', 'b', 'c', '1', '2', '3'], 2)```

Python
View
generate functionThu, 20 Apr 2023

## place 2 decimal places

```import random print(random.randint(1,99))```

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: # your code here return min((abs(one-i), i) for i in values)[1]```

Python
View
generate functionMon, 03 Jul 2023

## count the total number of words in a sentence that occur in the special words list

```def count_words(message, special_words): message = message.lower().split() count = 0 for word in message: if word in special_words: count += 1 return count count_words("this is a sentence", ["is", "a"])```

Python
View
generate functionTue, 25 Apr 2023

## create a multiplication table grid without tabs

```for i in range(1, 10): for j in range(1, i + 1): print('{}x{}={}\t'.format(i, j, i * j), end='') print()```

Python
View
generate functionThu, 13 Apr 2023

## divide this ['a', 'b', 'c', '1', '2', '3','4', '5', '6'] evenly into three separate list

```def dividelist(lst): list1 = [] list2 = [] list3 = [] for i in range(0, len(lst), 3): list1.append(lst[i]) list2.append(lst[i+1]) list3.append(lst[i+2]) return list1, list2, list3 dividelist(['a', 'b', 'c', '1', '2', '3','4', '5', '6'])```

Python
View
code to explanationThu, 13 Apr 2023

## [[a[i][0][::-1]] for i in range(len(a))]

`The above line reverses the first element of each sublist in the list`

generate functionTue, 23 May 2023

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

```def nearest_value(values: set[int], one: int) -> int: return min(sorted(values), key=lambda v: abs(v-one))```

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_nearest(array, value): idx = np.abs(np.asarray(array)-value).argmin() return array[idx] find_nearest([10,12,18,20],15)```

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(number): if number % 2 == 0: return number // 2 else: return 3 * number + 1 def driver(number): seq = [number] while number > 1: number = collatz(number) seq.append(number) return seq driver(25)```

Python
View
generate functionThu, 13 Apr 2023

## divide a list into three separate list

```def divide(lst): lst1 = lst[0:3] lst2 = lst[3:6] lst3 = lst[6:] return lst1, lst2, lst3 divide([1,2,3,4,5,6,7,8,9])```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] evenly into three separate list

```def list_divider(list): list_len = len(list) list_len_divided_by_three = list_len/3 return [list[0:list_len_divided_by_three], list[list_len_divided_by_three:list_len_divided_by_three * 2], list[list_len_divided_by_three * 2:list_len]] list_divider(['a', 'b', 'c', '1', '2', '3'])```

Python
View
generate functionTue, 25 Apr 2023

## create a multiplication table grid greater than 11

```def table(num): print("x | 1 2 3 4 5 6 7 8 9 10 11 12") print("---------------------------") for x in range(1, num + 1): row = str(x) + " |" for y in range(1, 13): row += " " + str(x * y) print(row) table(12)```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def div(a): x = [] y = [] z = [] for i in a: if i.isdigit(): x.append(i) else: y.append(i) z = x + y return z div(['a', 'b', 'c', '1', '2', '3'])```

Python
View
generate functionFri, 30 Jun 2023

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

```def get_highest_value_items(inventory): highest = 0 for key, value in inventory.items(): if value > highest: highest = value return highest```

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_nearest(S, x): return min(S, key = lambda y: abs(y-x)) find_nearest([-1, 2, 4, 5, 6, 7, 9, 11], 6)```

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 of integers and finds the sum of all integers in the list. (I'm not sure if this is correct)```

generate functionSun, 23 Apr 2023

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

```def add_nums(source_file, target_file): fh = open(source_file, 'r') total = 0 for line in fh: total += int(line) fh.close() fh = open(target_file, 'w') fh.write(str(total)) fh.close() add_nums('numbers.txt', 'sum.txt')```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def divide_list(list1): return list1[:3], list1[3:], list1[3:6] divide_list(['a', 'b', 'c', '1', '2', '3'])```

Python
View
generate functionMon, 24 Apr 2023

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

```def copy_file(source, target): source_file = open(source) target_file = open(target, "w") for line in source_file: target_file.write(line) source_file.close() target_file.close()```

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. add the numbers in the source file and write to target file the sum.

```def add_source_target(source, target): with open(source) as source, open(target, 'w') as target: sum = 0 for line in source: sum += int(line) target.write(str(sum)) add_source_target('source.txt', 'target.txt')```

Python
View
generate functionMon, 03 Jul 2023

## count the number of words in a sentence that occur in the special words list

```def count_special_words(sentence, special_words): special_words = ["your", "words", "here"] special_words = [word.lower() for word in special_words] sentence_words = sentence.lower().split() count = 0 for word in sentence_words: if word in special_words: count += 1 return count count_special_words("Hello, this is a sentence!", ["hello", "this"])```

Python
View
generate functionTue, 25 Apr 2023

## calculate the product of m x n but without using the * operator. Use both functions below def add(m, n): if m == 0: return n if n == 0: return m return add(m, succ(n)) def succ(n): return n +1

```def multiply(m, n): if m == 0: return 0 return add(m, multiply(m, dec(n)))```

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 functionFri, 28 Apr 2023

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

```def copyTurtleCoords(): def callback(x, y): print ('Clicked at', x, y) screen = turtle.Screen() turtle.TurtleScreen.__init__(screen) screen.onclick(callback) turtle.mainloop() # Example of use copyTurtleCoords()```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line until end of file

```def func(file1, file2): f1 = open(file1, 'r') f2 = open(file2, 'w') for line in f1: f2.write(line) f1.close() f2.close()```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def seperate_list(l): l1 = [] l2 = [] l3 = [] for i in l: if i.isdigit(): l1.append(i) elif i.isalpha(): l2.append(i) else: l3.append(i) return l1, l2, l3```

Python
View
generate functionFri, 30 Jun 2023

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

```def big(b): return max(b, key=lambda x:x['value'])['value'] big([{'value': 5}, {'value': 6}, {'value': 3}])```

Python
View
generate functionFri, 19 May 2023

## create a function for min and max of a number

```def min_max(a, b): if a < b: return a, b else: return b, a def max(a, b): if a < b: return b else: return a def min(a, b): if a < b: return a else: return b min(1, 2), max(1, 2)```

Python
View
generate functionTue, 23 May 2023

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

```def find_nearest(val, set_of_vals): return min(set_of_vals, key=lambda x:abs(x-val)) find_nearest(5.1, [5, 6, 3, 8, 2])```

Python
View
generate functionFri, 30 Jun 2023

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

```# input: [{'key':1},{'key':2},{'key':3}] # output: [{'key':3},{'key':2}] def largestTwo(dictionaries): return sorted(dictionaries, key=lambda item: item['key'], reverse=True)[:2]```

Python
View
generate functionFri, 30 Jun 2023

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

```def find_max(list_of_dicts): return max(list_of_dicts, key=lambda x: x['value']) find_max([{'name': 'a', 'value': 1}, {'name': 'b', 'value': 2}])```

Python
View
generate functionSun, 23 Apr 2023

## check if input is file, if not make it a file

```# Define function to check if string is a file def is_file(file_name): if file_name.endswith('.txt'): print(file_name) return file_name else: new_file_name = f'{file_name}.txt' print(new_file_name) return new_file_name is_file('file1')```

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: return min(values, key=lambda x: (abs(x - one), x))```

Python
View
generate functionTue, 23 May 2023

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

```def find_nearest(array,value): idx = (np.abs(array-value)).argmin() return array[idx]```

Python
View
generate functionMon, 24 Apr 2023

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

```def fileCopy(source, target): sourceFile = open(source, 'r') targetFile = open(target, 'w') for line in sourceFile: targetFile.write(line) targetFile.close() sourceFile.close()```

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

```special_words = ["awesome", "excellent", "amazing", "fun", "beautiful", "great", "cool"] def count_special_word(string, special_words): for word in string: if word in special_words: print(word) count_special_word("amazing", special_words)```

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: l = list(values) l.sort() for i in l: if i > one: return i return l[-1]```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] evenly into three separate list

```def divide(lst, n): return [lst[i::n] for i in range(n)] divide(['a', 'b', 'c', '1', '2', '3'], 3)```

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 functionTue, 23 May 2023

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

```def nearest_value(values: set[int], one: int) -> int: return min(sorted(values), key=lambda x: (abs(x - one), x))```

Python
View
generate functionFri, 19 May 2023

## create a function for min and max of a number

```def min_max(n): print(min(n)) print(max(n)) min_max(range(0, 10))```

Python
View
generate functionSun, 23 Apr 2023

## tell the difference between integer or float of a number.

```def type_of_num(arg): type(arg)```

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: return min(values, key=lambda x: abs(x - one))```

Python
View
code to explanationSun, 16 Apr 2023

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

```This is an explanation. I've written a blog post about this [here](https://aszam.github.io/blog/posts/code-blocks-in-markdown.html). ## Installation To install, run the following command:```

generate functionFri, 30 Jun 2023

## return the two biggest numbers in a list

```def max2(list): max1 = max(list) list.remove(max1) max2 = max(list) return max1, max2 max2([0,1,2,3,4,5,6])```

Python
View
generate functionTue, 23 May 2023

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

```def nearest_value(values: set, one: int) -> int: lst = list(values) lst.sort() for i in range(len(lst)): if lst[i] >= one: if i == 0: return lst[i] else: if lst[i] - one >= one - lst[i-1]: return lst[i-1] else: return lst[i] return lst[-1]```

Python
View
code to explanationSun, 16 Apr 2023

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

`This is the code for euclid's algorithm for finding the GCD of two numbers.`

generate functionTue, 23 May 2023

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

```def find_nearest(array, value): idx = np.abs(np.asarray(array) - value).argmin() return array[idx]```

Python
View
generate functionFri, 30 Jun 2023

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

```def get_three_biggest(dic_list): sorted_list = sorted(dic_list, key=lambda x: x['number'])[::-1] return sorted_list[:3]```

Python
View
generate functionThu, 13 Apr 2023

## divide this ['a', 'b', 'c', '1', '2', '3','4', '5', '6'] evenly into three separate list

```lst = ['a', 'b', 'c', '1', '2', '3','4', '5', '6'] def divide(lst): lst1 = [] lst2 = [] lst3 = [] for i in lst: if i.isalpha(): lst1.append(i) else: lst3.append(i) lst2 = lst1 + lst3 return lst1, lst2, lst3 divide(lst)```

Python
View
generate functionThu, 29 Jun 2023

## compare numbers in a list

```def compare_list(list): if len(list) == 1: return list[0] if len(list) == 2: return list[0] + list[1] if len(list) >= 3: return list[0] - list[1] * list[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, 21 Apr 2023

## add .txt to end of file

```string = "test.txt" os.path.splitext(string)[1]```

Python
View
generate functionTue, 23 May 2023

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

```def nearest(arr, value): return min(arr, key=lambda x: abs(x - value)) nearest([1, 2, 3, 4, 5], 2.5)```

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: return min(sorted(values), key=lambda x: abs(x - one))```

Python
View
generate functionThu, 13 Apr 2023

## divide a list into three separate list

```def divide(lst): lst1 = lst[:len(lst)//3] lst2 = lst[len(lst)//3:2*len(lst)//3] lst3 = lst[2*len(lst)//3:] return lst1, lst2, lst3```

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 nearest_int(int_list, target): return min(int_list, key=lambda x:abs(x-target)) nearest_int([1, 2, 3, 4, 5, 6], 4.5)```

Python
View
generate functionFri, 30 Jun 2023

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

```L = [{'a':3, 'b':5}, {'a': 2, 'b':6},{'a':1, 'b':8}] def two_biggest(list): b_list = sorted(list, key=lambda x:x['b']) return b_list[-1], b_list[-2] two_biggest(L)```

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 explanationTue, 25 Apr 2023

## def mpy(m, n): if n == 0: return 0 return add(m, mpy(m, pred(n))) print(mpy(5, 4))

```The function mpy calculates the product of two numbers recursively. If the second argument (n) is 0, the result is 0. Else, the result is m plus the result of mpy(m, pred(n)).```

generate functionFri, 28 Apr 2023

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

```def getcoords(x, y): global coords coords.append([x, y]) turtle.onscreenclick(getcoords)```

Python
View
generate functionFri, 19 May 2023

## create a function for min and max of a number

```def min(a,b): if a < b: return a else: return b```

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, 04 May 2023

## create a function to print data that is in a set, in alphabetical order

```def alphabetical(lst): lst.sort() for i in lst: print(i)```

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 nearest_number(numbers, target): numbers.sort() diff = target - numbers[0] for i in range(1, len(numbers)): if target - numbers[i] < diff: diff = target - numbers[i] return numbers[0] + diff nearest_number([1, 2, 3, 4, 5], 3)```

Python
View
generate functionTue, 23 May 2023

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

```def find_nearest(values, target): return min(values, key=lambda x: abs(x - target)) find_nearest([1, 2, 3, 4], 6)```

Python
View
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 functionThu, 20 Apr 2023

## place 2 decimal places

```import math def add(a,b): return a+b print(round(add(3.14159,2),2))```

Python
View
generate functionTue, 23 May 2023

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

```def closest_mod_5(x): if x % 5 == 0: return x return x + (5 - x % 5)```

Python
View
generate functionTue, 23 May 2023

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

```def nearest(given_list, num): return min(given_list, key=lambda x:abs(x-num)) nearest([1,2,3,4,5], 5)```

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])

```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])```

generate functionThu, 13 Apr 2023

## divide this ['a', 'b', 'c', '1', '2', '3','4', '5', '6'] evenly into three separate list

```def split(list, num_groups): return [list[x:x + num_groups] for x in range(0, len(list), num_groups)] split(['a', 'b', 'c', '1', '2', '3','4', '5', '6'], 3)```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def split(list): list1 = [] list2 = [] list3 = [] for i in range(len(list)): if i < len(list)//3: list1.append(list[i]) elif i < len(list) * 2 // 3: list2.append(list[i]) else: list3.append(list[i]) return list1, list2, list3 split(['a', 'b', 'c', '1', '2', '3'])```

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 wn=turtle.Screen() wn.bgcolor("lightgreen") #tess=turtle.Turtle() #tess.color("blue") points=[] def add_point(x,y): points.append((x,y)) print(points) wn.onclick(add_point) for point in points: x,y=point print(x,y) turtle.mainloop()```

Python
View
generate functionFri, 28 Apr 2023

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

```def back_to_beginning(): turtle.speed(1) turtle.penup() turtle.goto(0, 0) turtle.pendown()```

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: return min(values, key=lambda x: (abs(x - one), x)) nearest_value({4, 7, 10, 11, 12, 17}, 9)```

Python
View
generate functionFri, 19 May 2023

## create a function for min and max of a number

```def max(a, b): if a > b: return a else: return b max(1, 2)```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line

```def copyfile(sourcefile, targetfile): with open(sourcefile) as src: with open(targetfile, 'a') as target: for line in src: target.write(line) copyfile('source.txt', 'target.txt')```

Python
View
generate functionTue, 25 Apr 2023

## create a multiplication table grid without tabs

```def create_multiplication_table(number): for row in range(number): for col in range(number): print(f'{row * col}', end = ' ') print() create_multiplication_table(13)```

Python
View
generate functionThu, 20 Apr 2023

## try...except block checking if a file exist

```def file_exists(file): try: open(file) return True except FileNotFoundError: return False file_exists('example.txt')```

Python
View
code to explanationSun, 16 Apr 2023

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

`This code is used to find the greatest common divisor of two numbers.`

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 functionTue, 23 May 2023

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

```def smallest_difference(a, x): return min(a, key=lambda y:abs(x-y))```

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 read_file(source_file, target_file): sum = 0 target = open(target_file, 'w') with open(source_file) as f: for line in f: sum += int(line) target.write(line) target.write(sum)```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line

```# Read from one file and write to another file line by line def read_write_file(infile, outfile): with open(infile) as fr: with open(outfile, 'w') as fw: for line in fr: fw.write(line) read_write_file("infile.txt", "outfile.txt")```

Python
View
generate functionWed, 19 Apr 2023

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

```def punctuation_removal(sentence): punctuations = '''!()-[]{};:'"\,<>./?@#\$%^&*_~''' no_punct = "" for char in sentence: if char not in punctuations: no_punct = no_punct + char return no_punct.split() punctuation_removal("'I am learning python!'")```

Python
View
generate functionSun, 23 Apr 2023

## check input if file is in system, if not make the it a file

```def create_file(filename): if not os.path.isfile(filename): open(filename, 'w').close()```

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 functionFri, 30 Jun 2023

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

```def twoBiggest(l): return sorted(l, key=lambda d: d['key'])[-2:] l = [{'key': 2}, {'key': 1}, {'key': 3}] twoBiggest(l)```

Python
View
generate functionThu, 13 Apr 2023

## divide this ['a', 'b', 'c', '1', '2', '3','4', '5', '6'] evenly into three separate list

```def divide(l, n): return [l[i:i + n] for i in range(0, len(l), n)] divide(['a', 'b', 'c', '1', '2', '3','4', '5', '6'], 3)```

Python
View
generate functionFri, 30 Jun 2023

## return the two biggest numbers from a list

```def myfunc(t): mylist = [] while t > 0: mylist.append(t) t -= 1 return mylist myfunc(5)```

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 functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def separate(lst, *args): return [x for x in lst if x in args] separate(['a', 'b', 'c', '1', '2', '3'], 'a', 'b', 'c')```

Python
View
generate functionFri, 28 Apr 2023

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

```def onclick(x, y): # clear the screen t.clear() t.penup() t.goto(x, y) t.pendown() t.dot() screen.onclick(onclick)```

Python
View
generate functionFri, 28 Apr 2023

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

```def redraw(x, y): turtle.clear() turtle.pu() turtle.goto(x, y) turtle.pd() turtle.circle(50)```

Python
View
generate functionSun, 02 Jul 2023

## store largest to smallest numbers in a list and print all the numbers in the list

```def sort_largest_to_smallest(lst): for i in range(len(lst)): for j in range(len(lst)-i-1): if lst[j] > lst[j+1]: lst[j], lst[j+1] = lst[j+1], lst[j] return lst lst = [2, 5, 7, 10, 3, 4, 1] print(sort_largest_to_smallest(lst))```

Python
View
generate functionTue, 23 May 2023

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

```def find_nearest_number(numbers, target): numbers.sort() nearest_number = None smallest_difference = None for number in numbers: difference = abs(number - target) if not nearest_number or difference < smallest_difference: nearest_number = number smallest_difference = difference return nearest_number numbers = [1, 3, 5, 7] print(find_nearest_number(numbers, 4))```

Python
View
code to explanationSun, 16 Apr 2023

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

`The function egcd is the extended Greatest Common Divisor of a and b.`

code to explanationTue, 25 Apr 2023

## def mpy(m, n): if n == 0: return 0 return add(m, mpy(m, pred(n))) print(mpy(5, 4))

`The function mpy takes two arguments m and n and multiplies them together.`

generate functionTue, 23 May 2023

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

```def nearest(numbers, value): small = [] large = [] for i in numbers: if i < value: small.append(i) else: large.append(i) if large and small: return max(small) if value - max(small) <= min(large) - value else min(large) return max(small) or min(large) def main(): numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] value = 6 print(nearest(numbers, value)) main()```

Python
View
generate functionThu, 13 Apr 2023

## divide a list into three separate list

```def divide(lst): return lst[:len(lst)//3], lst[len(lst)//3:len(lst)//3*2], lst[len(lst)//3*2:] divide([1,2,3,4,5,6,7,8,9,10])```

Python
View
generate functionFri, 21 Apr 2023

## read from one file and write to another file line by line until end of file

```def read_write(read_filename, write_filename): file_to_read = open(read_filename, "r") file_to_write = open(write_filename, "a") for row in file_to_read.readlines(): file_to_write.write(row) file_to_read.close() file_to_write.close()```

Python
View
generate functionWed, 19 Apr 2023

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

```def remove_punctuations(s): s = s.replace(',', '') s = s.replace('.', '') ... remove_punctuations('The quick brown fox jumps over the lazy dog.') # ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']```

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. if the special word is not in the string, return the special word with zero.

```def count_special_words(word, sentence): count = 0 for letter in sentence: if letter == word: count += 1 return count count_special_words("f", "ff")```

Python
View
generate functionFri, 28 Apr 2023

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

```def mouse_c(x, y): t.penup() t.goto(x, y) t.pendown() draw_shape() def draw_shape(): for i in range(3): t.forward(100) t.left(120) t.onscreenclick(mouse_c)```

Python
View
generate functionTue, 25 Apr 2023

## create a multiplication table grid greater than 11

```def multiplication_table(x): for i in range(1, 13): print("{0:<3} x {1:<3} = {2:<3}".format(i, x, i*x)) multiplication_table(11)```

Python
View
generate functionTue, 25 Apr 2023

## calculate the product of m x n but without using the * operator. Use both functions below def add(m, n): if m == 0: return n if n == 0: return m return add(m, succ(n)) def succ(n): return n +1

```def add(m, n): if m == 0: return n if n == 0: return m return add(m, succ(n)) def succ(n): return n +1 def mul(m,n): if n == 0: return 0 return add(m, mul(m, pred(n))) def pred(n): if n == 0: return 0 return n -1 mul(2,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 functionThu, 13 Apr 2023

## divide a list into three separate list

```def divide(aList): a = [] b = [] c = [] for x in aList: if x < 0: a.append(x) elif x == 0: b.append(x) else: c.append(x) return a, b, c divide([1, 2, -1, 0, -2, 3])```

Python
View
code to explanationSun, 16 Apr 2023

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

`is a code version of the euclidean algorithm.`

code to explanationTue, 16 May 2023

## def sum_numbers(text: str) -> int

`The function sum_numbers takes a string argument and returns an integer.`

generate functionFri, 28 Apr 2023

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

```import turtle def draw_line(x, y): global mouse_actions mouse_actions.append((x, y)) turtle.goto(x, y) def main(): global mouse_actions mouse_actions = [] turtle.onscreenclick(draw_line) turtle.mainloop() main()```

Python
View
generate functionTue, 25 Apr 2023

## calculate the product of m x n but without using the * operator

```def multiply(m, n): product = 0 for i in range(n): product = add(product, m) return product multiply(5, 3)```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```def divide(l): return l[0:3], l[3:6] divide(['a', 'b', 'c', '1', '2', '3'])```

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. if the special word is not in the string, return the special word with zero.

```def word_count(str, list_special_words): dict = {} for word in list_special_words: dict[word] = str.count(word) return dict word_count('Let us go to the store and pick up the baby.', ['let', 'pick', 'baby'])```

Python
View
generate functionTue, 23 May 2023

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

```def find_closest_int(integers, value): return min(integers, key=lambda x:abs(x-value)) find_closest_int([1, 2, 3, 4, 5, 6], 4.5)```

Python
View
generate functionTue, 23 May 2023

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

```def find_closest(num, arr): distance = 9999999999999 closest = 0 for n in arr: if abs(num - n) < distance: distance = abs(num - n) closest = n return closest find_closest(7, [1, 7, 9])```

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, 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 solution(s): if len(s) % 2 != 0: s += '_' result = "" for i in range(0, len(s), 2): result += f'{s[i]}{s[i+1]} ' return result.rstrip() solution("abcdef")```

Python
View
generate functionThu, 04 May 2023

## create a function to print set of data in alphabetical order

```def sorted_alphabet(my_list): my_list.sort() return my_list print(sorted_alphabet(["A", "B", "C", "D"]))```

Python
View
generate functionSun, 23 Apr 2023

## read from one file and write to another file line by line until end of file

```def copy_file(input_file, output_file): """ This function copies the content of one file to another. Args: input_file: file to copy from output_file: file to write to """ with open(input_file, 'r') as in_file, open(output_file, 'w') as out_file: for line in in_file: out_file.write(line)```

Python
View
code to explanationTue, 16 May 2023

## def sum_numbers(text: str) -> int

`The function sum_numbers takes a string and returns the sum of all the numbers in the string.`

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 functionFri, 21 Apr 2023

## how to check for end of file

```f = open('something.txt', 'r') while True: line = f.readline() if not line: break print line```

Python
View
generate functionFri, 30 Jun 2023

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

```def get_two_largest_numbers(some_list): # ... return [max_1, max_2] get_two_largest_numbers([{'name': 'sam', 'number': 1}, {'name': 'max', 'number': 2}])```

Python
View
generate functionTue, 25 Apr 2023

## calculate the product of m x n but without using the * operator. Use both functions below def add(m, n): if m == 0: return n if n == 0: return m return add(m, succ(n)) def succ(n): return n +1

```def add(m, n): if m == 0: return n else: return add(m, succ(n)) def succ(n): return n + 1 def product(m, n): if m == 0: return 0 else: return add(n, product(dec(m), n)) def dec(n): return n - 1 product(4, 5)```

Python
View
generate functionThu, 20 Apr 2023

## place 2 decimal places

```def add(a, b): return a + b```

Python
View
generate functionFri, 30 Jun 2023

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

```def return_biggest_numbers(num_list): num_list.sort(key=lambda x:x["number"], reverse=True) return num_list[:2] return_biggest_numbers([{"number":1},{"number":100},{"number":50}])```

Python
View
generate functionThu, 13 Apr 2023

## divide list ['a', 'b', 'c', '1', '2', '3'] into three separate list

```numbers = ['a', 'b', 'c', '1', '2', '3'] new_numbers = [] for number in numbers: new_numbers.append(number) print(new_numbers)```

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
generate functionThu, 13 Apr 2023

## divide this ['a', 'b', 'c', '1', '2', '3','4', '5', '6'] evenly into three separate list

```def div_list(lst): return [lst[0:3], lst[3:6], lst[6::]] div_list(['a', 'b', 'c', '1', '2', '3','4', '5', '6'])```

Python
View
generate functionFri, 30 Jun 2023

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

```numbers = [ {'id': 1, 'value': 3}, {'id': 2, 'value': 1}, {'id': 3, 'value': 6}, {'id': 4, 'value': 2} ] def get_two_biggest(numbers): numbers_sorted = sorted(numbers, key=lambda k: k['value']) return numbers_sorted[-2:] get_two_biggest(numbers)```

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)

`From the function read_and_write, the function iscommand is called and the contents of the source file and the target file are passed on to the function iscommand.`

generate functionFri, 30 Jun 2023

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

```data = [{"a": 10}, {"a": 30}, {"a": 50}, {"a": 40}] def get_two_biggest(data): return sorted(data, key=lambda x: x["a"], reverse=True)[:2] get_two_biggest(data)```

Python
View
generate functionThu, 20 Apr 2023

## try...except block checking if a file exist

```def file_exists(filename): try: open(filename, 'r') return True except IOError: return False```

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: return min(sorted(values), key=lambda x: abs(x - one))```

Python
View
generate functionFri, 28 Apr 2023

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

```#create a function to store the mouse clicks def storeClick(x, y): global clicks clicks += [[x, y]] #function to draw using the mouse clicks def drawFromClicks(): for click in clicks: turtle.goto(click[0], click[1]) #add the handler to the turtle window turtle.onscreenclick(storeClick)```

Python
View
generate functionSun, 23 Apr 2023

## tell the difference between integer or float of a number.

```def number_type(a): if type(a) == float: print('float') else: print('integer') number_type(1.1)```

Python
View