From 77655700e88d14f002507f3c6e4da3bfe28e2839 Mon Sep 17 00:00:00 2001 From: Shule Evrenk <105816821+saevrenk@users.noreply.github.com> Date: Sun, 11 Dec 2022 16:46:05 -0500 Subject: [PATCH 1/5] Added solutions to the exercises. --- 12_09_practice.py | 84 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/12_09_practice.py b/12_09_practice.py index 7914563..3df7f16 100644 --- a/12_09_practice.py +++ b/12_09_practice.py @@ -1,29 +1,111 @@ #Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". Example: make_it_big([-1, 3, 5, -5]) returns that same list, #changed to [-1, "big", "big", -5]. +def make_big(lst): + return ["big" if el > 0 else el for el in lst ] + +print(make_big([-1, 3, 5, -5])) + #Count Positives - Given a list of numbers, create a function to replace last value with number of positive values. Example, count_positives([-1,1,1,1]) changes list #to [-1,1,1,3] and returns it. (Note that zero is not considered to be a positive number). +def add_number_positives(lst): + lst[len(lst)-1] = len([i for i in lst if i>0]) + return lst + +print(add_number_positives([-1,1,1,1])) + #SumTotal - Create a function that takes a list as an argument and returns the sum of all the values in the list. For example sum_total([1,2,3,4]) should return 10 +def sum_total(lst): + return sum(lst) + +print(sum_total([1,2,3,4])) + #Average - Create a function that takes a list as an argument and returns the average of all the values in the list. For example multiples([1,2,3,4]) should return #2.5 +def get_avg(lst): + return sum(lst)/len(lst) + +print(get_avg([1,2,3,4])) + #Length - Create a function that takes a list as an argument and returns the length of the list. For example length([1,2,3,4]) should return 4 +def get_length(lst): + return len(lst) + +print(get_length([1,2,3,4])) + #Minimum - Create a function that takes a list as an argument and returns the minimum value in the list. If the passed list is empty, have the function return false. #For example minimum([1,2,3,4]) should return 1; minimum([-1,-2,-3]) should return -3. + +def get_minimum(lst): + return False if len(lst) == 0 else min(lst) + + +print(get_minimum([1,2,3,4]), get_minimum([-1,-2,-3])) # #Maximum - Create a function that takes a list as an argument and returns the maximum value in the list. If the passed list is empty, have the function return false. #For example maximum([1,2,3,4]) should return 4; maximum([-1,-2,-3]) should return -1. +def get_maximum(lst): + return False if len(lst) == 0 else max(lst) + +print(get_maximum([1,2,3,4]), get_maximum([-1,-2,-3])) + #Ultimateaalyze - Create a function that takes a list as an argument and returns a dictionary that has the sumTotal, average, minimum, maximum ad length of the list. +def ultimateanalyze(lst): + dct = {} + dct['sumTotal'] = sum(lst) + dct['average'] = sum(lst)/len(lst) + dct['minimum'] = min(lst) + dct['maximum'] = max(lst) + dct['length'] = len(lst) + return dct + +print(ultimateanalyze([1,2,3,4])) + #ReverseList - Create a function that takes a list as a argument and return a list in a reversed order. Do this without creating a empty temporary list. For example #reverse([1,2,3,4]) should return [4,3,2,1]. This challenge is known to appear during basic technical interviews. +def reverselist(lst): + return lst[::-1] + +print(reverselist([1,2,3])) #Ispalindrome- Given a string, write a python function to check if it is palindrome or not. A string is said to be palindrome if the reverse of the string is the same as string. For example, “radar” is a palindrome, but “radix” is not a palindrome. +def ispalindrome(lst): + return lst == lst[::-1] + +print(ispalindrome('abba')) #Fizzbuzz- Create a function that will print numbers from 1 to 100, with certain exceptions: #If the number is a multiple of 3, print “Fizz” instead of the number. #If the number is a multiple of 5, print “Buzz” instead of the number. #If the number is a multiple of 3 and 5, print “FizzBuzz” instead of the number. +#Fizzbuzz- Create a function that will print numbers from 1 to 100, with certain exceptions: +#If the number is a multiple of 3, print “Fizz” instead of the number. +#If the number is a multiple of 5, print “Buzz” instead of the number. +#If the number is a multiple of 3 and 5, print “FizzBuzz” instead of the number. + +def fizzbuzz(): + p = lambda x: print(x) + + [p('FizzBuzz') if (i%3==0 and i%5==0) + else (p('Fizz') if i%3==0 + else ( p('Buzz') if i%5==0 else p(i))) + for i in range(1,101)] + +fizzbuzz() + #Fibonacci- The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, #starting from 0 and 1. That is, #F(0) = 0, F(1) = 1 #F(n) = F(n - 1) + F(n - 2), for n > 1. - #Create a function that accepts any number and will create a sequence based on the fibonacci sequence. \ No newline at end of file + #Create a function that accepts any number and will create a sequence based on the fibonacci sequence. + +def fibonacci(n): + if n == 0: return 0 + dct_fibo = {} + dct_fibo[0] = 0 + dct_fibo[1] = 1 + for i in range(2,n+1): + dct_fibo[i] = dct_fibo[i-1] + dct_fibo[i-2] + return [values for _, values in dct_fibo.items()] + +print(fibonacci(10)) \ No newline at end of file From fdb98502ed1211697bc238fbc539c06b0e6f9534 Mon Sep 17 00:00:00 2001 From: Shule Evrenk <105816821+saevrenk@users.noreply.github.com> Date: Mon, 12 Dec 2022 17:41:19 -0500 Subject: [PATCH 2/5] Added solutions to the second set of python exercises. --- python_exercises2.py | 64 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 python_exercises2.py diff --git a/python_exercises2.py b/python_exercises2.py new file mode 100644 index 0000000..2c6ce23 --- /dev/null +++ b/python_exercises2.py @@ -0,0 +1,64 @@ +##################################################################### +# GENERATORS: +##################################################################### +# Generator exercises: Create a generator, primes_gen that generates prime numbers starting from 2. + +import math + +# use the principle that if a number have any factor less than the numbers square root, then the number cannot be prime + +def isprime(n): + if n == 2: return True + nroot = int(math.sqrt(n))+ 1 + for i in range(2,nroot+1): + if n % i == 0: + return False + return True + +def primes_gen(): + n = 2 + while True: + if isprime(n): + yield n + n += 1 + +gen = primes_gen() +print('primes') +for _ in range(10): + print(next(gen), end=' ') +##################################################################### +#Create a generator, unique_letters that generates unique letters from the input string. It should generate the letters in the same order as from the input string. + +def unique_letters(str): + mem = [] # memory list to keep unique letters + for lt in str: + if lt not in mem: + yield lt + mem.append(lt) +print('\nUnique Letters:') +for letter in unique_letters('hello'): + print(letter, end=' ') + +##################################################################### +# LAMBDA FUNCTIONS +##################################################################### +#Consider the list: +prog_lang = [('Python', 3.8), + ('Java', 13), + ('JavaScript', 2019), + ('Scala', 2.13)] + +#1. Sort the list by each language's version in ascending order. + +print(sorted(prog_lang, key = lambda x : x[1])) + +#2. Sort the list by the length of the name of each language in descending order. + +print(sorted(prog_lang, key = lambda x : len(x[0]), reverse=True)) + +#3. Filter the list so that it only contains languages with 'a' in it. + +print(list(filter(lambda x : True if 'a' in x[0] else False, prog_lang))) + +#4. Filter the list so that it only contains languages whose version is in integer form. +print(list(filter(lambda x : isinstance(x[1],int) , prog_lang))) From f2fd97ab180db10b8315939446e016ced1a9597d Mon Sep 17 00:00:00 2001 From: Shule Evrenk <105816821+saevrenk@users.noreply.github.com> Date: Tue, 13 Dec 2022 10:44:48 -0500 Subject: [PATCH 3/5] Added solutions to the exercises on page 20. --- python_exercises2.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/python_exercises2.py b/python_exercises2.py index 2c6ce23..de626a5 100644 --- a/python_exercises2.py +++ b/python_exercises2.py @@ -4,6 +4,7 @@ # Generator exercises: Create a generator, primes_gen that generates prime numbers starting from 2. import math +from functools import reduce # use the principle that if a number have any factor less than the numbers square root, then the number cannot be prime @@ -62,3 +63,13 @@ def unique_letters(str): #4. Filter the list so that it only contains languages whose version is in integer form. print(list(filter(lambda x : isinstance(x[1],int) , prog_lang))) + +#5 Transform the list so that it contains the tuples in the form,("language in all lower case", length of the language string) + +print(list(map(lambda x: (x[0].lower(), len(x[0])), prog_lang))) + +#6 Generate a tuple in the form, ("All languages separated by commas", "All versions separated by commas") + + +print((reduce(lambda x,y: ",".join([x,y]), [x for (x,y) in prog_lang]),(reduce(lambda x,y: ",".join([x,y]), [str(y) for (x,y) in prog_lang])))) + From 0c62a6f969f5aa79d4a2d21c9f57b915040080b4 Mon Sep 17 00:00:00 2001 From: Shule Evrenk <105816821+saevrenk@users.noreply.github.com> Date: Tue, 13 Dec 2022 18:57:25 -0500 Subject: [PATCH 4/5] Added solutions to the closure and decorator exercises. --- python_exercises3_closures_decorators.py | 134 +++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 python_exercises3_closures_decorators.py diff --git a/python_exercises3_closures_decorators.py b/python_exercises3_closures_decorators.py new file mode 100644 index 0000000..c8071b3 --- /dev/null +++ b/python_exercises3_closures_decorators.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +""" +Created on Tue Dec 13 13:01:37 2022 + +@author: SAE +""" +#CLOSURE: +#Closure exercise: Using a closure, create a function, multiples_of(n) which we can use to create generators that generate multiples of n less than a given number. + +def multiples_of(n): + def inner(nmax): + num = n + while num + +print(*m3_under30) +# output: 3 6 9 12 15 18 21 24 27 + +print(*m7_under30) +# output: 7 14 21 28 + + +# DECORATORS: +#Create following decorators: +#1. make_upper – make every letter of a string returned from the decorated function uppercase. +def make_upper(func): + def wrapper(): + return func().upper() + return wrapper + +@make_upper +def hello_world(): + return 'hello young, good day!!' + +print(hello_world()) # output: HELLO YOUNG, GOOD DAY!! + + +#2. print_func_name – print the name of the decorated function before executing the function. + +def print_func_name(func): + def wrapper(): + print(f'{func.__name__} is running') + func() + return wrapper + +@print_func_name +def my_func(): + print('Python is fun!!') + +my_func() # output: my_func is running... + + +#3. give_name(name) – concatenate the given name at the end of a string returned from the decorated function. + +def give_name(name): + def wrapper(func): + return f'{func()} {name}' + return wrapper + +@give_name('Theresa') +def greeting(): + return 'Hello' + +print(greeting) # output: Hello Theresa + + +#4. print_input_type – print a data type of the input argument before executing the decorated function. +def print_input_type(func): + def typer(n): + return f'The input data type is {type(func)}\nThe {func.__name__} of {n} is {func(n)}' + return typer + +@print_input_type +def square(n): + return n**2 + +print(square(3.5)) # output: The input data type is + + +#5. check_return_type(return_type) – check if the return type of the decorated function is return_type and print the result before executing the function. + +def check_return_type(return_type): + def wrapper(func): + def inner(*args): + print(func(*args)) + if type(func(*args)) == return_type: + return f'The return type is {type(func(*args))}' + else: + return f'=========Error!!=========The return type is NOT {return_type}' + return inner + return wrapper + +@check_return_type(float) +def square(n): + return n ** 2 + +print(square(6)) # output: =========Error!!=========The return type is NOT + + +print(square(2.9)) # output: The return type is + + +#6. execute_log – write a function execution log on the log file. +from datetime import datetime + +def execute_log(func): + def wrapper(*args): + return f'{datetime.now()} {func.__name__}' + return wrapper + +@execute_log +def multiply(*nums): + mult = 1 + for n in nums: + mult *= n + return mult + +@execute_log +def hello_world(): + return 'hello world!!' + +print(multiply(6, 2, 3)) # 36 +print(hello_world()) # hello world!! +print(multiply(2.2, 4)) # 8.8 +print(hello_world()) # hello world!! From f8303912125872b0d93253baab8947bc9786a59b Mon Sep 17 00:00:00 2001 From: Shule Evrenk <105816821+saevrenk@users.noreply.github.com> Date: Thu, 15 Dec 2022 22:01:47 -0500 Subject: [PATCH 5/5] Added XML exercises --- modify_xml.py | 62 ++++++++++++++++++++++++++ movies.xml | 120 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 182 insertions(+) create mode 100644 modify_xml.py create mode 100644 movies.xml diff --git a/modify_xml.py b/modify_xml.py new file mode 100644 index 0000000..5f35900 --- /dev/null +++ b/modify_xml.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +""" +Created on Thu Dec 15 20:24:04 2022 + +@author: SAE +""" + +import xml.etree.ElementTree as ET +import re + +# import xml +tree = ET.parse('movies.xml') +root = tree.getroot() + +# -Add a new genre called Anime to the root +new_genre = ET.SubElement(root, 'genre') +new_genre.attrib["category"] = 'Anime' +print(ET.tostring(new_genre)) + +# -Add a new decade to the new anime genre. First check the decade for the Batman movies: + +for title in root.findall("./genre/decade/movie/[@title]"): + match = re.match('Batman', title.attrib['title']) + if match: + print(title.attrib['title']) + +# returns two movies: +# Batman Returns +# Batman: The Movie + +# Find which year these movies belong to: + +for movie in root.iter('movie'): + for y in movie.iter('year'): + match = re.match('Batman', movie.attrib['title']) + if match: + print(movie.attrib['title'], y.text) + +# returns two movies with dates: +# Batman Returns 1992 +# Batman: The Movie 1966 + +# Create anime decade 1990s +anime = root.find("./genre[@category='Anime']") +new_decade = ET.SubElement(anime, 'decade') +new_decade.attrib["years"] = '1990s' +print(new_decade.attrib) + +# Add Batman returns +batman = root.find("./genre/decade/movie[@title='Batman Returns']") +decade1990s = root.find("./genre[@category='Anime']/decade[@years='1990s']") +decade1990s.append(batman) +print(ET.tostring(root, encoding='utf8').decode('utf8')) + + +# Delete Batman from the old genre: +dec1990s = root.find("./genre[@category='Action']/decade[@years='1990s']") +dec1990s.remove(batman) +print(ET.tostring(root, encoding='utf8').decode('utf8')) + +# Write updated tree to xml file +tree.write("movies.xml") \ No newline at end of file diff --git a/movies.xml b/movies.xml new file mode 100644 index 0000000..fc9e620 --- /dev/null +++ b/movies.xml @@ -0,0 +1,120 @@ + + + + + DVD + 1981 + PG + + 'Archaeologist and adventurer Indiana Jones + is hired by the U.S. government to find the Ark of the + Covenant before the Nazis.' + + + + DVD,Online + 1984 + PG + None provided. + + + Blu-ray + 1985 + PG + Marty McFly + + + + + Online + 1992 + R + WhAtEvER I Want!!!?! + + + + dvd, digital + 2000 + PG-13 + Two mutants come to a private academy for their kind whose resident superhero team must + oppose a terrorist organization with similar powers. + + + + + + + DVD + 1979 + R + """"""""" + + + + + DVD + 1986 + PG13 + Funny movie about a funny guy + + + blue-ray + 2000 + Unrated + psychopathic Bateman + + + + + + + + DVD,VHS + 1966 + PG + What a joke! + + + + + DVD + 2010 + PG--13 + Emma Stone = Hester Prynne + + + DVD,digital,Netflix + 2011 + Unrated + Tim (Rudd) is a rising executive + who succeeds in finding the perfect guest, + IRS employee Barry (Carell), for his boss monthly event, + a so-called dinner for idiots, which offers certain + advantages to the exec who shows up with the biggest buffoon. + + + + + + Online,VHS + 1984 + PG + Who ya gonna call? + + + + + Blu_Ray + 1991 + Unknown + Robin Hood slaying + + + + + VHS + 1992 + PG13 + NA. + + \ No newline at end of file