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] + '_')
def nearest_value(values: set[int], one: int) -> int:
return min(sorted(values), key=lambda x: abs(x-one))
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))
def count_words(word_list):
return len(word_list)
count_words(['apple', 'mango', 'pear'])
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
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)
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)
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.
def is_number(string):
try:
float(string)
return True
except:
return False
is_number("123")
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, "-"))
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))
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()
with open('input.txt', 'r') as input_file, open('output.txt', 'w') as output_file:
for line in input_file:
output_file.write(line)
def minmax(a):
if a > 1:
return 1
else:
return 0
minmax(2)
def nearest_value(values: set, one: int) -> int:
return min(values, key=lambda x: abs(x - 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))
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')
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())
def compare(numbers):
smaller = []
for x in numbers:
smaller.append(x)
return smaller
compare([1, 2, 3])
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.
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])
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))
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()
def divide(x, y):
return x / y
divide(10, 2)
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():
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)
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)
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)
def is_number(str):
try:
float(str)
return True
except ValueError:
return False
is_number("1.0")
def draw_square():
for i in range(4):
turtle.forward(100)
turtle.right(90)
draw_square()
Returns all the strings in the list a in reverse.
def compare_numbers(a, b):
return [x for x in [a, b] if x < max(a, b)]
compare_numbers(2, 1)
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.
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.
def find_nearest(values, target):
values = sorted(values)
index = bisect.bisect(values, target)
return values[index-1:index+1]
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])
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'])
def redraw(x, y):
turtle.clear()
turtle.goto(x, y) # draw to new position
turtle.onscreenclick(redraw)
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)
def make_grid(columns, rows):
rows = rows * ' ---' + '\n'
columns = columns * '| ' + '|\n'
grid = rows + columns
for _ in range(rows):
print(grid)
make_grid(8, 8)
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())
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)
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)
def print_ordered(data):
data = sorted(data)
for item in data:
print(item)
print_ordered({'a', 'b', 'c'})
This code returns a list of the elements in the list lst but in reverse order.
The function mpy takes two arguments m and n and returns the product of m and n.
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')
def three_biggest(list_of_dictionaries):
return sorted(list_of_dictionaries, key=lambda k: k['num'])[-3:]
def divide(list):
return list[0:2], list[2:4], list[4:]
divide([1, 2, 3, 4, 5, 6])
def draw_square():
for i in range(0, 4):
turtle.forward(100)
turtle.right(90)
draw_square()
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'])
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()
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}])
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()
def main(file_in, file_out):
# your code here
main("sample_input.txt", "sample_output.txt")
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()
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 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
def grid(num):
for x in range(num):
print(' ---' * num)
print('| ' * num, '|')
print(' ---' * num)
grid(8)
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.'))
def add(a, b):
return a + b
add(1, 2)
def split_pairs(text: str) -> Iterable[str]:
for i in range(0,len(text),2):
yield text[i:i+2]
def closest_number(nums, target):
nums.sort()
for num in nums:
if num >= target:
return num
return nums[0]
The above code is called Euclidean algorithm. It finds the greatest common divisor of two numbers.
def check_file(path):
try:
open(path)
return True
except FileNotFoundError:
return False
check_file('test.txt')
def process(source, target):
target.write(source.readline())
target.write(source.readline())
source = open('test.txt')
target = open('target.txt')
process(source, target)
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)
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)
def nearest_value(values: set, one: int) -> int:
return min(values, key=lambda x: abs(x - one))
def nearest_value(values: set[int], one: int) -> int:
return min(values, key=lambda v: abs(v - one))
def get_max(list):
max = list[0]
for i in list:
if i > max:
max = i
return max
get_max([1, 2, 3, 4])
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)
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'])
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)
is the famous euclidian algorithm for calculating the gcd of two numberes.
The function sum takes a list as an argument and returns the sum of the elements in the list.
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()
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'])
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 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)
def redraw(x, y):
turtle.goto(x, y)
turtle.onscreenclick(redraw)
def two_decimal_places(n):
return round(n, 2)
def make_grid(columns, rows):
return [[0] * columns for i in range(rows)]
make_grid(8, 8)
def find_nearest(arr, target):
return min(arr, key=lambda x: abs(x-target))
find_nearest([1,2,3,4,5], 7)
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)
#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)
def split_sentence(sentence):
sentence = sentence.replace(',', '').replace('.', '').replace('?', '').replace('!', '')
return sentence.split(' ')
split_sentence('Hello, world.')
def add_txt_file_end(filename):
return filename + '.txt'
add_txt_file_end(filename = 'test')
def remove_none(input):
return input.replace('none', '')
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
def nearest_int(lst, num):
return min(lst, key=lambda x:abs(x-num))
f= open('path/to/file1','r')
f2 = open(path/to/file2,'w')
for line in f:
f2.write(line)
f.close()
f2.close()
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)
def nearest_value(values: set[int], one: int) -> int:
return min(sorted(values), key=lambda x: (abs(x - one), x))
import math
def nearest_value(values: set, one: int) -> int:
return min(values, key = lambda x: math.fabs(x - 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)
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 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
def product(m, n):
if m == 0:
return 0
return add(product(dec(m), n), n)
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)
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
def alphabetical(name):
print(sorted(name))
alphabetical(["Jon", "Arya", "Tyrion"])
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)
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")
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)
This code takes a list and splits it in 3 parts and reverses them.
def copyTurtleCoordinates(turtle):
screen = turtle.getscreen()
screen.onclick(turtle.goto)
turtle = Turtle()
copyTurtleCoordinates(turtle)
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.
def grid():
for i in range(8):
if i % 2 == 0:
print "* " * 4
else:
print " *" * 4
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])
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)
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']
def hello_world(name):
print("Hello World, ", name)
hello_world("Daniel")
def string_word_count(string, word_list):
word_dict = {}
#your code here
return word_dict
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)
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())
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()
def factorial(n):
product = 1
for i in range(1, n+1):
product = product * i
return product
def return_biggest_number_in_list(list_of_dicts, key):
# sort list_of_dicts by key
# return first two elements
def addtxt(filename):
filename = addtxt(filename)
def add_txt(f):
return f + ".txt"
def divide_by(num):
return num % 3
def divide_list(list):
return map(divide_by, list)
divide_list(['a', 'b', 'c', '1', '2', '3'])
def truncate(number, places=2):
return number[:places + 1]
truncate(1.234, 1)
def find_nearest_number(a, b):
return min(a, key = lambda x:abs(x-b))
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)
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_
def min_max(numbers):
return min(numbers), max(numbers)
min_max([1,2,3,4,5])
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])
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])
- 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)
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]
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']))
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()
def mult(a, b):
if b == 0:
return 0
return a + mult(a, b - 1)
mult(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.
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')
def isNumber(string):
try:
float(string)
return True
except ValueError:
return False
isNumber("1") #True
def make_8_8_grid():
for i in range(8):
for j in range(8):
print(" ---")
print("| | | | | | | | |")
print(" --- --- --- --- --- --- --- ---")
make_8_8_grid()
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')
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.
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"))
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
def file_exists(filename):
try:
f = open(filename)
f.close()
return True
except FileNotFoundError:
return False
file_exists('test.txt')
text = 'abc'
result = []
for i in range(0, len(text), 2):
result.append(text[i:i+2].ljust(2, '_'))
result
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!")
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)
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])
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)
def min_max(a, b):
if a < b:
return a
elif b < a:
return b
else:
return 'equal'
min_max(5, 4)
import string
def remove_punct(s):
return s.translate(string.punctuation)
remove_punct("This is a sentence.")
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)
def bigger(a,b):
if a > b:
return 'a'
else:
return 'b'
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)
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.
def format_number(number):
return format(number, '.2f')
format_number(2.345)
with open('../Data/test.txt') as f:
with open('../Data/output.txt', 'w') as f1:
for line in f:
f1.write(line)
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]
def alphabetical(str):
return sorted(str)
alphabetical("mango")
def draw_square():
for i in range(4):
t.fd(100)
t.lt(90)
"""
"""
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:
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
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)
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.
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}])
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')
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))
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)
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'])
def f(x):
return x*x
f(2)
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.
def make_file(filename):
if '.txt' in filename:
pass
else:
filename = filename + '.txt'
return filename
filename = 'test'
make_file(filename)
def get_coordinates():
coordinates = []
def add_coordinate(x, y):
coordinates.append((x, y))
screen.onclick(add_coordinate)
return coordinates
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
def getMouseCoordinates():
turtle.onscreenclick(turtle.goto)
getMouseCoordinates()
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]
def minmax(numbers):
return min(numbers), max(numbers)
minmax([1,2,4,5,6,7,8,9,10])
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)
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')
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))]
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'
from turtle import *
def createCoord(x, y):
print((x,y))
getscreen().onclick(createCoord)
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)
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.
def split_into_pair(s):
return s[0:2], s[2:4]
split_into_pair("abcd")
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")
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)
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')
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
def two_biggest_numbers(l):
return max(l, key=lambda x: x['number'])
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)
### **TODO**:
- [ ] The code for the function
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)
This is the Euclidean algorithm which finds the greatest common divisor of two numbers.
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'])
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()
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)
def min(list):
lowest = list[0]
for i in list:
if i < lowest:
lowest = i
return lowest
min([1,2,3,4,5])
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')
def process_mouse_clicks(x, y):
t.goto(x, y)
t.pendown()
t.circle(10)
t.penup()
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()
def separate(list):
return list[:3], list[3:6], list[6:]
separate(['a', 'b', 'c', '1', '2', '3'])
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}])
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)
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'])
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)
def check_file(file):
try:
with open(file, 'rb') as f:
return True
except IOError:
return False
check_file('file.txt')
def get_biggest(arr):
if len(arr) < 2:
return None
return sorted(arr)[-2]
get_biggest([1,2,3,4])
# 3
def nearest_value(values: set[int], one: int) -> int:
return min(sorted(values), key=lambda x: abs(x - one))
def check_word(word, special_word, dictionary):
if word == special_word:
if word not in dictionary:
dictionary[word] = 1
else:
dictionary[word] += 1
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}])
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}])
def find_nearest(array, value):
index = (np.abs(array - value)).argmin()
return array[index]
def product_sum(n):
sum = 0
for i in range(1, n+1):
sum = sum + i * i
return sum
product_sum(50)
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
def print_table(n):
for i in range(1, 11):
print(n, 'x', i, '=', n*i)
print_table(7)
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])
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
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]
def separate(a, b, c, d, e, f):
return [a, b, c], [d, e, f]
separate('a', 'b', 'c', '1', '2', '3')
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)
def add(file_name):
return file_name + '.txt'
add('blah')
def type_of_number(a):
if a % 1 == 0:
return "integer"
else:
return "float"
type_of_number(2.2)
def my_fun(l):
return l[0:2], l[2:4], l[4:6]
my_fun(['a', 'b', 'c', '1', '2', '3'])
def add_text_to_file(file_name):
file_name = file_name + '.txt'
return file_name
add_text_to_file("dear_diary")
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'])
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)
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')
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
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')
def nearest_value(values: set[int], one: int) -> int:
nearest = min(values, key=lambda x: abs(one-x))
return nearest
The function add takes two arguments m and n and returns the result of adding m to n.
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
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] )
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] + '_']
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]
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]
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]
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)
def draw_by_click(x, y):
# code to draw something here
canvas.bind("<Button-1>", draw_by_click)
def mult(n, m):
for i in range(n):
for j in range(m):
print(i * j, end='')
print('')
mult(10, 10)
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)
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)
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))
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))
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)
will print the list of the numbers in reverse order
def nearest_value(values: set[int], one: int) -> int:
return min(sorted(values), key=lambda x:abs(one-x))
def nearest_value(values: set[int], one: int) -> int:
return min(sorted(values), key=lambda x: abs(x-one))
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")
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))
def nearest_value(values: set[int], one: int) -> int:
return min(sorted(values), key=lambda x: abs(x - one))
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.
def divide_list(lst):
return [lst[:3], lst[3:6], []]
divide_list(['a', 'b', 'c', '1', '2', '3'])
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')
def checkFileExist(file, path):
try:
with open(os.path.join(path, file)) as f:
return True
except FileNotFoundError:
return False
# 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')
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))
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")
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()
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}])
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'])
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')
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')
def multiply(m, n):
product = 0
while n > 0:
product = add(m, product)
n -= 1
return product
multiply(5, 4)
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.
The above code is a function which finds the gcd of x and y.
def nearest_value(values: set[int], one: int) -> int:
values = set(values)
values.remove(one)
return min(values, key=lambda x: abs(x - one))
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)
def order_list(numbers):
ordered_numbers = []
for number in numbers:
ordered_numbers.append(number)
return ordered_numbers
order_list([2, 4, 1, 3, 5])
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}])
# 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.")
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}]
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)
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)
reverses the first element (i.e. the string) of every inner list and returns the resulting list.
def divide(a_list):
return a_list[:3], a_list[3:6], a_list[6:]
divide(['a', 'b', 'c', '1', '2', '3'])
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)
def three_biggest(a_list_of_numbers):
a_list_of_numbers.sort()
return a_list_of_numbers[-3:]
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}])
def get_maximum(lst, key):
return max(lst, key=lambda item: item[key])
get_maximum([{'a': 1}, {'a': 3}, {'a': 2}], 'a')
def check_end_of_file(x):
if x == 'end':
return True
return False
check_end_of_file('end')
check_end_of_file('not')
def nearest(x, vals):
return min(vals, key=lambda y: abs(x - y))
nearest(2, {3, 5})
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
def separate(list):
return list[:3], list[3:6]
separate(['a', 'b', 'c', '1', '2', '3'])
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,
def nearest_value(values: set, one: int) -> int:
# your code here
return min(values, key=lambda x:abs(x-one))
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)
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Division by zero is not allowed."
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")
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
is_number("1")
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"])
file_name = "hello"
file_name_with_extension = file_name + ".txt"
def isint(a):
return isinstance(a, int)
isint(2)
def count_words(s, n):
# To do
return {}
count_words("cat bat mat cat bat cat", ["cat", "bat", "mat"])
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)
def nearest(n, v):
return min(v, key=lambda x:abs(x-n))
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)
turtle.onscreenclick(turtle.goto)
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)
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)
import random
print(random.randint(1,99))
def nearest_value(values: set[int], one: int) -> int:
# your code here
return min((abs(one-i), i) for i in values)[1]
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"])
for i in range(1, 10):
for j in range(1, i + 1):
print('{}x{}={}\t'.format(i, j, i * j), end='')
print()
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'])
The above line reverses the first element of each sublist in the list
def nearest_value(values: set[int], one: int) -> int:
return min(sorted(values), key=lambda v: abs(v-one))
def find_nearest(array, value):
idx = np.abs(np.asarray(array)-value).argmin()
return array[idx]
find_nearest([10,12,18,20],15)
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)
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])
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'])
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)
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'])
def get_highest_value_items(inventory):
highest = 0
for key, value in inventory.items():
if value > highest:
highest = value
return highest
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)
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)
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')
def divide_list(list1):
return list1[:3], list1[3:], list1[3:6]
divide_list(['a', 'b', 'c', '1', '2', '3'])
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()
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')
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"])
def multiply(m, n):
if m == 0:
return 0
return add(m, multiply(m, dec(n)))
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('') # []
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()
def func(file1, file2):
f1 = open(file1, 'r')
f2 = open(file2, 'w')
for line in f1:
f2.write(line)
f1.close()
f2.close()
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
def big(b):
return max(b, key=lambda x:x['value'])['value']
big([{'value': 5}, {'value': 6}, {'value': 3}])
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)
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])
# 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]
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}])
# 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')
def nearest_value(values: set[int], one: int) -> int:
return min(values, key=lambda x: (abs(x - one), x))
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
def fileCopy(source, target):
sourceFile = open(source, 'r')
targetFile = open(target, 'w')
for line in sourceFile:
targetFile.write(line)
targetFile.close()
sourceFile.close()
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)
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]
def divide(lst, n):
return [lst[i::n] for i in range(n)]
divide(['a', 'b', 'c', '1', '2', '3'], 3)
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")
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
def nearest_value(values: set[int], one: int) -> int:
return min(sorted(values), key=lambda x: (abs(x - one), x))
def min_max(n):
print(min(n))
print(max(n))
min_max(range(0, 10))
def type_of_num(arg):
type(arg)
def nearest_value(values: set[int], one: int) -> int:
return min(values, key=lambda x: abs(x - one))
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:
def max2(list):
max1 = max(list)
list.remove(max1)
max2 = max(list)
return max1, max2
max2([0,1,2,3,4,5,6])
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]
This is the code for euclid's algorithm for finding the GCD of two numbers.
def find_nearest(array, value):
idx = np.abs(np.asarray(array) - value).argmin()
return array[idx]
def get_three_biggest(dic_list):
sorted_list = sorted(dic_list, key=lambda x: x['number'])[::-1]
return sorted_list[:3]
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)
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]
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
string = "test.txt"
os.path.splitext(string)[1]
def nearest(arr, value):
return min(arr, key=lambda x: abs(x - value))
nearest([1, 2, 3, 4, 5], 2.5)
def nearest_value(values: set[int], one: int) -> int:
return min(sorted(values), key=lambda x: abs(x - one))
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
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)
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)
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()
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)).
def getcoords(x, y):
global coords
coords.append([x, y])
turtle.onscreenclick(getcoords)
def min(a,b):
if a < b:
return a
else:
return b
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.
def alphabetical(lst):
lst.sort()
for i in lst:
print(i)
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)
def find_nearest(values, target):
return min(values, key=lambda x: abs(x - target))
find_nearest([1, 2, 3, 4], 6)
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])
import math
def add(a,b):
return a+b
print(round(add(3.14159,2),2))
def closest_mod_5(x):
if x % 5 == 0:
return x
return x + (5 - x % 5)
def nearest(given_list, num):
return min(given_list, key=lambda x:abs(x-num))
nearest([1,2,3,4,5], 5)
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 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)
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'])
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[
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}
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()
def back_to_beginning():
turtle.speed(1)
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
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)
def max(a, b):
if a > b:
return a
else:
return b
max(1, 2)
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')
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)
def file_exists(file):
try:
open(file)
return True
except FileNotFoundError:
return False
file_exists('example.txt')
This code is used to find the greatest common divisor of two numbers.
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()
def smallest_difference(a, x):
return min(a, key=lambda y:abs(x-y))
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)
# 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")
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!'")
def create_file(filename):
if not os.path.isfile(filename):
open(filename, 'w').close()
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])
def twoBiggest(l):
return sorted(l, key=lambda d: d['key'])[-2:]
l = [{'key': 2}, {'key': 1}, {'key': 3}]
twoBiggest(l)
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)
def myfunc(t):
mylist = []
while t > 0:
mylist.append(t)
t -= 1
return mylist
myfunc(5)
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")
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]
def separate(lst, *args):
return [x for x in lst if x in args]
separate(['a', 'b', 'c', '1', '2', '3'], 'a', 'b', 'c')
def onclick(x, y):
# clear the screen
t.clear()
t.penup()
t.goto(x, y)
t.pendown()
t.dot()
screen.onclick(onclick)
def redraw(x, y):
turtle.clear()
turtle.pu()
turtle.goto(x, y)
turtle.pd()
turtle.circle(50)
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))
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))
The function egcd is the extended Greatest Common Divisor of a and b.
The function mpy takes two arguments m and n and multiplies them together.
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()
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])
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()
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']
def count_special_words(word, sentence):
count = 0
for letter in sentence:
if letter == word:
count += 1
return count
count_special_words("f", "ff")
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)
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)
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)
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
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])
is a code version of the euclidean algorithm.
The function sum_numbers takes a string argument and returns an integer.
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()
def multiply(m, n):
product = 0
for i in range(n):
product = add(product, m)
return product
multiply(5, 3)
def divide(l):
return l[0:3], l[3:6]
divide(['a', 'b', 'c', '1', '2', '3'])
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'])
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)
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])
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
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")
def sorted_alphabet(my_list):
my_list.sort()
return my_list
print(sorted_alphabet(["A", "B", "C", "D"]))
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)
The function sum_numbers takes a string and returns the sum of all the numbers in the string.
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)
f = open('something.txt', 'r')
while True:
line = f.readline()
if not line:
break
print line
def get_two_largest_numbers(some_list):
# ...
return [max_1, max_2]
get_two_largest_numbers([{'name': 'sam', 'number': 1}, {'name': 'max', 'number': 2}])
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)
def add(a, b):
return a + b
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}])
numbers = ['a', 'b', 'c', '1', '2', '3']
new_numbers = []
for number in numbers:
new_numbers.append(number)
print(new_numbers)
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"))
def div_list(lst):
return [lst[0:3], lst[3:6], lst[6::]]
div_list(['a', 'b', 'c', '1', '2', '3','4', '5', '6'])
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)
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.
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)
def file_exists(filename):
try:
open(filename, 'r')
return True
except IOError:
return False
def nearest_value(values: set[int], one: int) -> int:
return min(sorted(values), key=lambda x: abs(x - one))
#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)
def number_type(a):
if type(a) == float:
print('float')
else:
print('integer')
number_type(1.1)