diff --git a/#dec12list comprehension.py b/#dec12list comprehension.py new file mode 100644 index 0000000..0d759a8 --- /dev/null +++ b/#dec12list comprehension.py @@ -0,0 +1,33 @@ +#list comprehension +expression for variable in sequence (optional predicate) +my_list=[] +for i in range(1,10,2): + my_list.append(i**2) + +my_list2=[i**2 for i in range(1,10,2)] +print(my_list) +print(my_list2) + +odd_square=[] +for x in range(1,11): + if x % 2==1: + odd_square.append(x**2) + +odd_square2 = [x**2 for x in range(1,11) if x %2 ==1] + print(odd_square2) + + +def dec(func, n): + def wrapper(): + for _ in range(n): + func() + return wrapper + +@dec +('say_hello', 5) +def say_hello(): + print('hello') + +#say_hello = dec(say_hello, 5) +say_hello() + diff --git a/12_09_practice.py b/12_09_practice.py index 7914563..0326e1a 100644 --- a/12_09_practice.py +++ b/12_09_practice.py @@ -1,29 +1,148 @@ #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]. +list1=[-1, 3, 5, -5] + +def make_it_big(list1): + list=[] + for i,a in enumerate(list1): + if a < 0: + list.append("big") + else: + list.append(a) + print(list) +make_it_big(list1) + #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). -#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 +list1=[-1,1,1,1] -#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 count_positives(list1): + list=[] + sum=0 + for i,a in enumerate(list1): + if a < 0: + list.append(a) + else: + sum+=a + list.append(a) + list[-1]=sum + print(list) +count_positives(list1) +#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 +list1=[1,2,3,4] +def sum_total(list1): + sum=0 + for i in list1: + sum+=i + print (sum) + return sum +sum_total(list1) +#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 +list1=[1,2,3,4] +def average(list1): + sum=0 + for i in list1: + sum+=i + avg1=sum/len(list1) + print (avg1) + return avg1 +average(list1) #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 - +list1=[1,2,3,4] +def length(list1): + count=0 + for i in list1: + count+=1 + print (count) + return count +length(list1) #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. -# +list1=[0,-3, 5,2] +def minimum(list1): + if len(list1)==0: + print("False") + else: + return min(list1) + print(min(list1)) +minimum(list1) #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. - +list1=[0,-3, 5,2] +def maximum(list1): + if len(list1)==0: + print("False") + else: + return max(list1) + print(max(list1)) +maximum(list1) #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. - +lis1=[0,-3, 5,2] +def ultimateaalyze(list1): + dict={ + "sum_total":sum_total(list1), + "average":average(list1), + "minimum":minimum(list1), + "maximum":maximum(list1), + "length":length(list1) + } + print(dict) +ultimateaalyze(list1) + #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. +list1=[1,2,3,4] +def reverse(list1): + print (list1[::-1]) + return list1[::-1] +reverse(list1) #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. +#string1="radar" +def ispalindrome(string1): + if string1==string1[::-1]: + print(f"{string1} is palindrome") + else: + print(f"{string1} is not palindrome") +string1 = input('Enter any string ') +ispalindrome(string1) + #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(): + for num in range(0,101): + if num%3==0 and num%5==0: + print("FizzBuzz") + elif num%3== 0: + print("Fizz") + elif num%5==0: + print("Buzz") + else: + print(num) +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(num): + num1 = 0 + num2 = 1 + seq = 0 + if num == 0: + return 0 + elif num== 1: + return 1 + for i in range(num): + print(seq, end=' ') + num1 = num2 + num2 = seq + seq = num1 + num2 + +num = int(input('Enter any number ')) +fibonacci(num) + + diff --git a/12_12_pythonpractice.py b/12_12_pythonpractice.py new file mode 100644 index 0000000..44b666b --- /dev/null +++ b/12_12_pythonpractice.py @@ -0,0 +1,80 @@ +#practice on Generator,lamda +from functools import reduce +#1. Use list comprehension to create a list containing a solution for the +#famous FizzBuzz problem. For integers 1 to 100, inclusively, the value +#should be: +# 'Fizz' if divisible by 3 +# 'Buzz' if divisible by 5 +# 'FizzBuzz' if divisible by both 3 and 5 +# The integer itself if not divisible by both 3 and 5 +list2=['FizzBuzz' if (num%3==0 and num%5==0) else "Fizz" if (num%3==0)else "Buzz"if (num%5==0) else num for num in range(1,101)] +print(list2) + +#1. Create a generator, primes_gen that generates prime numbers +#starting from 2. +def primes_gen(): + i = 2 + while i < 100 : + prime = True # reset the `prime` variable before the inner loop + for a in range(2, i): + if i%a == 0: + prime = False + break + if prime: + yield i + i += 1 # don't forget to advance `i` + +gen = primes_gen() +for _ in range(10): + print(next(gen), end=' ') +print(end='\n') +#2. 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(str1): + unique="" + for i in str1: + if i not in unique: + unique=unique+' '+i + yield unique +for letter in unique_letters('hello'): + print(letter, end=' ') +print(end='\n') + +#Consider the list: + +#1. Sort the list by each language's version in ascending order. +prog_lang = [('Python', 3.8), +('Java', 13), +('JavaScript', 2019), +('Scala', 2.13)] +list1=prog_lang +list1.sort(key=lambda x: x[1]) +print(list1) +#2. Sort the list by the length of the name of each language in descending +##order. +list2=prog_lang +list2.sort(key=lambda x: len(x[0]),reverse=True) +print(list2) +#3. Filter the list so that it only contains languages with 'a' in it. +prog_lang = [('Python', 3.8), +('Java', 13), +('JavaScript', 2019), +('Scala', 2.13)] +list3=list(filter(lambda x: 'a' in x[0], prog_lang)) +print(list3) +#4. Filter the list so that it only contains languages whose version is in int +list4=list(filter(lambda x: type(x[1])== int, prog_lang)) +print(list4) +#5. Transform the list so that it contains the tuples in the form, +#("language in all lower case", length of the language string) +list5=list(map(lambda x : (x[0].lower(),len(x[0])), prog_lang)) +print(list5) +#6. Generate a tuple in theform, +#("All languages separated by commas", +#"All versions separated by commas") +print(reduce(lambda x,y :(f'{x[0]},{y[0]}',f'{x[1]},{y[1]}'),prog_lang)) + + + + diff --git a/12_13_python_decorators.py b/12_13_python_decorators.py new file mode 100644 index 0000000..c781afe --- /dev/null +++ b/12_13_python_decorators.py @@ -0,0 +1,121 @@ +#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 multiply(k): + print([i for i in range(n, k, n)]) + return multiply + +m3 = multiples_of(3) +m3_under30 = m3(30) +m7_under30 = multiples_of(7)(30) + +print(type(m3_under30)) +print(m3(60)) +print(m3_under30) +print(m7_under30) + +#Create following decorators: +#1. make_upper – make every letter of a string returned from the decorated +#function uppercase. + +def make_upper(f): + def wrapper(): + str1=f() + return str1.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: Anynt the name of the decorated function before +#executing the function. +def print_func_name(f): + def wrapper(): + print(f.__name__,"is running...") + f() + 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(str1): + def wrapper(f): + return f()+" "+str1 + return wrapper +@give_name('Theresa') +def greeting(): + return 'Hello' + +print(greeting) # output: Hello Theresa + +print("---------------------------------------------------------------------------------------------------------") + + + +#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!! \ No newline at end of file diff --git a/json_practise.py b/json_practise.py new file mode 100644 index 0000000..c9bb77a --- /dev/null +++ b/json_practise.py @@ -0,0 +1,12 @@ +import json +import requests +#from pprint import pp + +data={ "user"} : { + "name" : "William Williams", + "age" : 98 +} +with open ("data_file.json","w")as write_file: + json.dump(data,write_file,indent=4) + + diff --git a/json_practise1.py b/json_practise1.py new file mode 100644 index 0000000..710b3e4 --- /dev/null +++ b/json_practise1.py @@ -0,0 +1,11 @@ + + +count = 0 +todos_by_user ={} +for item in todos: + print(item) + if item["completed"] == True: + count += 1 + todos_by_user[item["userId"] ]= count +print(count) +print(todos_by_user) diff --git a/movies.xml b/movies.xml new file mode 100644 index 0000000..84aca3e --- /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 + + + + + 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. + + + VHS + 1992 + PG13 + NA. + + + Online + 1992 + R + WhAtEvER I Want!!!?! + + + +​ + + + + 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 + + + + \ No newline at end of file diff --git a/newdatabase.ipynb b/newdatabase.ipynb new file mode 100644 index 0000000..c384c2e --- /dev/null +++ b/newdatabase.ipynb @@ -0,0 +1,254 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [], + "source": [ + "import mysql.connector as mariadb" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Connecting to Mariadb database...\n" + ] + } + ], + "source": [ + "con = mariadb.connect(\n", + " host=\"localhost\",\n", + " user=\"root\",\n", + " password=\"password\",\n", + " database=\"classicmodels\"\n", + ")\n", + "print(\"Connecting to Mariadb database...\")\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [], + "source": [ + "cur=con.cursor()\n", + "st= \"SELECT productLine,COUNT(*)\\\n", + " FROM products\\\n", + " WHERE productLine='{}'\"\n", + "cur.execute(st.format('Motorcycles'))\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[('Motorcycles', 13)]\n" + ] + } + ], + "source": [ + "result=cur.fetchall()\n", + "print(result)\n", + "con.close()" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "now create a new database\n", + "we are not connecting to a specific database\n", + "strings can be passed directly into execute method" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Connecting to Mariadb database...\n", + "test_db created\n" + ] + } + ], + "source": [ + "con = mariadb.connect(\n", + " host=\"localhost\",\n", + " user=\"root\",\n", + " password=\"password\"\n", + "\n", + ")\n", + "print(\"Connecting to Mariadb database...\")\n", + "cur=con.cursor()\n", + "st=\"CREATE DATABASE test_db\"\n", + "cur.execute(st)\n", + "print(\"test_db created\")\n", + "con.close()\n", + " " + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "create table to test_db" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Connecting to Mariadb database...\n", + "Registration table created\n" + ] + } + ], + "source": [ + "con = mariadb.connect(\n", + " host=\"localhost\",\n", + " user=\"root\",\n", + " password=\"password\",\n", + " database=\"test_db\"\n", + "\n", + ")\n", + "print(\"Connecting to Mariadb database...\")\n", + "cur=con.cursor()\n", + "st=\"CREATE TABLE Registration\\\n", + " (id INTEGER,age INTEGER,\\\n", + " first VARCHAR(50),last VARCHAR(50))\"\n", + "cur.execute(st)\n", + "print(\"Registration table created\")\n", + "con.close()" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Connecting to Mariadb database...\n", + "Values are inserted\n" + ] + } + ], + "source": [ + "con = mariadb.connect(\n", + " host=\"localhost\",\n", + " user=\"root\",\n", + " password=\"password\",\n", + " database=\"test_db\"\n", + "\n", + ")\n", + "print(\"Connecting to Mariadb database...\")\n", + "cur=con.cursor()\n", + "st=\"INSERT INTO Registration \\\n", + " (id, age, first, last) VALUES \\\n", + " (100, 29, 'Michael', 'Jordan'), \\\n", + " (101, 29, 'Diego', 'Maradona'), \\\n", + " (102, 33, 'Babe', 'Ruth'), \\\n", + " (103, 40, 'Wayne', 'Gretzky'), \\\n", + " (104, 27, 'Michelle', 'Kwan'), \\\n", + " (105, 35, 'Steffi', 'Graf')\"\n", + "cur.execute(st)\n", + "con.commit()\n", + "print(\"Values are inserted\") \n", + "con.close()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Connecting to Mariadb database...\n", + "Values are Updated\n" + ] + } + ], + "source": [ + "con = mariadb.connect(\n", + " host=\"localhost\",\n", + " user=\"root\",\n", + " password=\"password\",\n", + " database=\"test_db\"\n", + "\n", + ")\n", + "print(\"Connecting to Mariadb database...\")\n", + "cur=con.cursor()\n", + "st=\"UPDATE Registration\\\n", + " SET age=30 WHERE id IN (100,101)\"\n", + "cur.execute(st)\n", + "con.commit()\n", + "print(\"Values are Updated\") \n", + "con.close() " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.0" + }, + "orig_nbformat": 4, + "vscode": { + "interpreter": { + "hash": "f884144a6e149779c8b893bcebed488774240f991d9527b1f28d134615f7f1b6" + } + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/xml_practice.py b/xml_practice.py new file mode 100644 index 0000000..3c12bb3 --- /dev/null +++ b/xml_practice.py @@ -0,0 +1,12 @@ +import xml.etree.ElementTree as ET +tree = ET.parse('movies.xml') +root = tree.getroot() +print(tree) +#print(root) + +#print(root.tag) +#print(root.attrib) + +#for child in root: + #print(child.tag,child.attrib) +#print([elem.tag for elem in root.iter()]) diff --git a/xml_practice1.py b/xml_practice1.py new file mode 100644 index 0000000..16b8aeb --- /dev/null +++ b/xml_practice1.py @@ -0,0 +1,47 @@ + +import xml.etree.ElementTree as ET +tree = ET.parse('movies.xml') +root = tree.getroot() + +# we got the tree and went in root +print(len(root)) # how many children element has +print(root.tag) # name of the elemnt tag-collection +# giving us element attributes in a adictionary###blank dict means no attributes +print(root.attrib) + +print([elem.tag for elem in root.iter()]) + +for movie in root.iter('movie'): # iterate over movie tag starting from root + print(movie.attrib) + +for rating in root.iter('rating'): + print(rating.text) + # giving us all the text in rating but we cant manipulate the things +for rating in root.findall("./genre/decade/movie/[rating='PG']"): + print(rating.attrib) + # find the particular + +# in movies there is one movie in uppercase - convert it into normal way + +kkid = root.find("./genre/decade/movie[@title='THE KARATE KID']") + +kkid.attrib['title'] = "The Karate Kid" +print(kkid.attrib) + +# add a new genre tag + + +anime_genre = ET.SubElement(root, 'genre') + +# we add attribute to new genre anime_genre now +anime_genre.attrib['catogory'] = 'Anime' +print(ET.tostring(root, encoding='utf8').decode('utf8')) +# to create a new decade with in this new genre and add a movie into it movie the batman return into this movie category here +#Add a new decade to the new anime genre. + +#-Add the Batman from into the anime genre under the correct decade WITHOUT just typing it out. (Append it from the old genre to the new one). + +#-Delete Batman from the old genre. + +add_anime = root.find("./genre[@category='Anime']") +new_genre = ET.SubElement(add_anime, 'decade') diff --git a/xml_practice2.py b/xml_practice2.py new file mode 100644 index 0000000..8a74401 --- /dev/null +++ b/xml_practice2.py @@ -0,0 +1,39 @@ + +import xml.etree.ElementTree as ET +tree = ET.parse('movies.xml') +root = tree.getroot() + +# we got the tree and went in root +print(len(root)) # how many children element has +print(root.tag) # name of the elemnt tag-collection +# giving us element attributes in a adictionary###blank dict means no attributes +print(root.attrib) + +print([elem.tag for elem in root.iter()]) + +for movie in root.iter('movie'): # iterate over movie tag starting from root + print(movie.attrib) + +for rating in root.iter('rating'): + print(rating.text) + # giving us all the text in rating but we cant manipulate the things +for rating in root.findall("./genre/decade/movie/[rating='PG']"): + print(rating.attrib) + # find the particular + +# in movies there is one movie in uppercase - convert it into normal way + +kkid = root.find("./genre/decade/movie[@title='THE KARATE KID']") + +kkid.attrib['title'] = "The Karate Kid" +print(kkid.attrib) + +# add a new genre tag + + +anime_genre = ET.SubElement(root, 'genre') + +# we add attribute to new genre anime_genre now +anime_genre.attrib['catogory'] = 'Anime' +print(ET.tostring(root, encoding='utf8').decode('utf8')) +# to create a new decade with in this new genre and add a movie into it movie the batman return into this movie category here