├── Advanced ├── Hospital.py ├── Hotel_Management.py ├── Modern_Gambling │ ├── .vscode │ │ └── settings.json │ ├── event.py │ ├── fields_of_classes.txt │ ├── main.py │ └── user.py ├── Music player application │ ├── file.png │ └── main.py ├── Snake_Game.py ├── Warehouse_Management.py └── chatroom application using socket │ ├── .vscode │ └── settings.json │ ├── client.py │ ├── client_2.py │ └── server.py ├── BeginnerTOIntermediate ├── DimmerSwitch.py ├── HigherOrLower.py ├── Isosceles triangle.py ├── Tv.py ├── clock.py ├── email_sender.py ├── generate_random_password.py ├── guess_number.py ├── leapyear.py ├── min_max_approach.py ├── num-triangle.py ├── number_to_year.py ├── qrcode.py ├── quizGame.py ├── straigt.py ├── text_to_morse_code.py ├── time_coundown.py └── unique.py ├── LICENSE ├── Leetcode ├── Majority Element II.py ├── MedianSortedArray.py ├── Squares of a Sorted Array.py ├── addTwoNumbers.py └── addnums.py └── README.md /Advanced/Hospital.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import smtplib 3 | import time 4 | import psycopg2 5 | import random 6 | from colorama import * 7 | 8 | #? Connect to Database 9 | connection = psycopg2.connect(database="hospital", user = "postgres", password = "1234", host = "127.0.0.1", port = "5432") 10 | cursor = connection.cursor() 11 | 12 | 13 | #TODO Base Class Of Program 14 | class ReserveTime: 15 | def __init__(self,name,family,number,doctor,date,payed,registration,codingtrack): 16 | self.name = name 17 | self.family = family 18 | self.number = number 19 | self.doctor = doctor 20 | self.date = date 21 | self.payed = payed 22 | self.registration = registration 23 | self.codingtrack = codingtrack 24 | 25 | 26 | doctors = ['david auth','nora kian','sam hana','lona siami','aria roohi','yai chi','rami moled','kia amiri','ana moali','kave kooshan'] 27 | 28 | while True: 29 | #! Program Starts 30 | menu = int(input("""----- MENU -----\n 31 | 1-LIST OF DOCTORS 32 | 2-RESERVE A TIME 33 | 3-CRITISM AND SUGGESTION 34 | 4-SEE YOUR HISTORY 35 | 6-WANNA SEE PEOPLES SUGGESTION ABOUT US? 36 | 7-EXIT: """)) 37 | 38 | # todo Show list of doctors 39 | if menu == 1: 40 | docnumber = -1 41 | for doctor in doctors: 42 | docnumber = docnumber + 1 43 | print(f"{docnumber}:",doctor, end="\n") 44 | 45 | next_move = int(input("Exit:0 Menu:1 >> ")) 46 | if next_move == 1: 47 | print(Fore.CYAN,"redirecting...") 48 | time.sleep(3.5) 49 | pass 50 | 51 | elif next_move == 0: 52 | print(Fore.GREEN,"Thanks for choosing our app") 53 | break 54 | else: 55 | print(Fore.RED,"Choose from list please!") 56 | time.sleep(3) 57 | pass 58 | 59 | if menu == 2: 60 | sure_idea = int(input("are you sure? << y:1 OR n:0 >>: ")) 61 | if sure_idea == 1 : 62 | 63 | sender_email = 'pyaireza7@gmail.com' 64 | receiver_email = input("Enter yor email: ") 65 | password = 'sdlrjodkrmawxgdc' 66 | password = str(password) 67 | message = str(random.randrange(11111111,99999999)) 68 | int_email= int(message) 69 | # todo connect to smtp server and login to our email account 70 | server = smtplib.SMTP('smtp.gmail.com',587) 71 | server.ehlo() 72 | server.starttls() 73 | server.login(sender_email,password) 74 | print(Fore.MAGENTA , "Loading...") 75 | server.sendmail(sender_email,receiver_email,message) 76 | print("Email has been sent to",receiver_email) 77 | time.sleep(5) 78 | email_code = int(input("Enter code that we sent for you: ")) 79 | if email_code == int_email: 80 | print("please fill in the list with your specifications!") 81 | time.sleep(2) 82 | obj = ReserveTime( 83 | input("Enter Your name: "), 84 | input("Enter Your family: "), 85 | int(input("Enter Your phone number: ")), 86 | input("Enter Your doctors name: "), 87 | datetime.datetime.now(), 88 | 30, 89 | True, 90 | email_code 91 | ) 92 | print("Your reservation completed \n loading...") 93 | time.sleep(1.5) 94 | print(f"This is your tracking code:{obj.codingtrack}") 95 | time.sleep(3) 96 | else: 97 | print("sorry code was wrong! ") 98 | time.sleep(2) 99 | 100 | elif sure_idea == 0: 101 | print(Fore.GREEN,"Thanks!") 102 | time.sleep(3) 103 | break 104 | 105 | else: 106 | print("please choose from the list") 107 | time.sleep(3) 108 | 109 | if menu == 3: 110 | print("loading the box...") 111 | time.sleep(2) 112 | critism_box = input("Enter your suggestion and critistm: ") 113 | your_name = input("Enter your name: ") 114 | try: 115 | cursor.execute(f"INSERT INTO critism(name,content) \ 116 | VALUES ('{your_name}','{critism_box}')"); 117 | connection.commit() 118 | sender_email = 'pyaireza7@gmail.com' 119 | receiver_email = input("Enter yor email: ") 120 | password = 'sdlrjodkrmawxgdc' 121 | password = str(password) 122 | message = "Thanks for sharing your opinion we will fix the problem" 123 | # todo connect to smtp server and login to our email account 124 | server = smtplib.SMTP('smtp.gmail.com',587) 125 | server.ehlo() 126 | server.starttls() 127 | server.login(sender_email,password) 128 | print(Fore.MAGENTA , "Loading...") 129 | server.sendmail(sender_email,receiver_email,message) 130 | print(Fore.GREEN,"your opinion saved we will answer you in couple of days!") 131 | except BaseException: 132 | raise(TypeError) 133 | 134 | if menu == 4: 135 | account = int(input("you have account? yes:1 no:0 ")) 136 | if account == 1: 137 | name = input("Enter your name: ") 138 | cursor.execute(f"SELECT * from onlinetimetable WHERE name='{name}'") 139 | rows = cursor.fetchall() 140 | for row in rows: 141 | print ("name = ", row[0]) 142 | print( "family = ", row[1]) 143 | print ("number = ", row[2]) 144 | print ("doctor = ", row[3]) 145 | print ("payed = ", row[4]) 146 | print ("registration = Done") 147 | print ("coding track = ", row[6], "\n") 148 | 149 | print(Fore.GREEN,"Operation done successfully") 150 | time.sleep(5) 151 | if menu == 5: 152 | cursor.execute("SELECT * from critism") 153 | rows = cursor.fetchall() 154 | for row in rows: 155 | print ("name = ", row[0]) 156 | print ("suggestion = ", row[1], "\n") 157 | time.sleep(5) 158 | 159 | if menu == 6: 160 | print("Thank's for using our app Good luck! ") 161 | time.sleep(2) 162 | break 163 | 164 | cursor.close() 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | -------------------------------------------------------------------------------- /Advanced/Hotel_Management.py: -------------------------------------------------------------------------------- 1 | from asyncio import sleep 2 | import os 3 | import time 4 | import pickle 5 | class rooms: 6 | def __init__(self,number,floor, area): 7 | self.number=number 8 | self.area=area 9 | self.floor=floor 10 | 11 | room1=rooms( 12 | number=1, 13 | floor=1, 14 | area=85 15 | ) 16 | room2=rooms( 17 | number=2, 18 | floor=2, 19 | area=120 20 | ) 21 | room3=rooms( 22 | number=3, 23 | floor=2, 24 | area=85 25 | ) 26 | room4=rooms( 27 | number=4, 28 | floor=3, 29 | area=120 30 | ) 31 | room5=rooms( 32 | number=5, 33 | floor=2, 34 | area=85 35 | ) 36 | room6=rooms( 37 | number=6, 38 | floor=3, 39 | area=120 40 | ) 41 | 42 | empty_rooms=["room1","room3","room5","room6"] 43 | full_rooms = ["room2","room4"] 44 | while True: 45 | os.system("cls") 46 | print("------ m e n u -----") 47 | print("1.Empty Rooms") 48 | print("2.Description Of Rooms") 49 | print("3.Get a Room") 50 | print("4.Tell Us Specifications in Question ") 51 | print("Some Facts About Our Hotel") 52 | print("5.Talk to Manager") 53 | print("6.Exit") 54 | number=int(input("Please select From 1-6:")) 55 | 56 | os.system("cls") 57 | if number == 1 : 58 | time.sleep(1.10) 59 | while True: 60 | print (empty_rooms) 61 | print("Exit == 0") 62 | select = int(input("Enter Number Of Room To See Specifications:")) 63 | 64 | if select == 1: 65 | print ("Number is:",room1.number) 66 | print ("Floor is:",room1.floor) 67 | print("area is:",room1.area) 68 | time.sleep(2) 69 | elif select == 2: 70 | print("Its Not Empty Room") 71 | print("Please Try Another") 72 | time.sleep(2) 73 | elif select == 3: 74 | print ("Number is:",room3.number) 75 | print ("Floor is:",room3.floor) 76 | print("area is:",room3.area) 77 | time.sleep(2) 78 | elif select == 4: 79 | print("Its Not Empty Room") 80 | print("Please Try Another") 81 | time.sleep(2) 82 | elif select == 5: 83 | print ("Number is:",room5.number) 84 | print ("Floor is:",room5.floor) 85 | print("area is:",room5.area) 86 | time.sleep(2) 87 | elif select == 6: 88 | print ("Number is:",room6.number) 89 | print ("Floor is:",room6.floor) 90 | print("area is:",room6.area) 91 | time.sleep(2) 92 | elif select > 6: 93 | print("Sorry We Dont That Room") 94 | print("Please Select From The List") 95 | time.sleep(2) 96 | elif select ==0 : 97 | break 98 | elif number == 2: 99 | print("Room 1 : its clean Big With Wide Windows") 100 | print("Room 2 : its Not Well Made But it has Great Kitchen") 101 | print("Room 3 : Not a Great Windows But Trust Me its Bigger Than Other Rooms") 102 | print("Room 4 : Thats a Well-Made room With Garden And So Many Flowers") 103 | print("Room 5 : Walls With Nice Color Big Bathroom and a Well-made one ") 104 | print("Room 6 : full Option Room I can say its the Best Room we have and Actualy the Most Expensive") 105 | print("This Page will Disappear After 20 Seconds") 106 | time.sleep(20) 107 | 108 | elif number == 3 : 109 | print(empty_rooms) 110 | x = (input("Witch Room Do You Want?")) 111 | empty_rooms.remove(x) 112 | full_rooms.append(x) 113 | 114 | x=input("your name:") 115 | x2=input("last name:") 116 | x3=input("how many days:") 117 | x4=input("for how many people:") 118 | x5=input("Do you want special services:") 119 | x6=input("when do you want to come:") 120 | print("That Room Will Reserve For you Until You Pay For It") 121 | time.sleep(2) 122 | print("Thanks To Choose Our Hotel , Its An Honor") 123 | time.sleep(3) 124 | elif number == 4: 125 | print("Specifications and Questions") 126 | x = input ("Write Here:") 127 | time.sleep(1) 128 | print("Thanks For Sharing With US") 129 | time.sleep(3) 130 | elif number == 5: 131 | print("Hello Im Hashemi . the Hotels Manager , How Can I Do For You?:") 132 | answer=input("write everything You Want To Manager Read He Will Sends You Feed Back:") 133 | print("Thanks For Sharing Your Opinion With Us") 134 | time.sleep(3) 135 | elif number == 6: 136 | break 137 | else: 138 | print("Please Choose From The List") 139 | time.sleep(4) 140 | 141 | 142 | 143 | 144 | 145 | -------------------------------------------------------------------------------- /Advanced/Modern_Gambling/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.linting.pylintEnabled": true, 3 | "python.linting.enabled": true 4 | } -------------------------------------------------------------------------------- /Advanced/Modern_Gambling/event.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | import datetime 3 | 4 | class Event: 5 | def __init__(self,event_name,capacity): 6 | self.event_name = event_name 7 | self.maximum_participant = capacity 8 | self.event_id = uuid.uuid4() 9 | self.date = datetime.datetime.utcnow() 10 | 11 | def __str__(self) -> str: 12 | return f"{self.event_id} - {self.event_id}" 13 | -------------------------------------------------------------------------------- /Advanced/Modern_Gambling/fields_of_classes.txt: -------------------------------------------------------------------------------- 1 | -- User -- 2 | 1-Name 3 | 2-Lastname 4 | 3-Age 5 | 4-Id 6 | 5-accountValue 7 | 6-gamblesHistory 8 | 9 | 10 | -- Event -- 11 | 1-EventName 12 | 2-Date 13 | 3-Event_id 14 | 4-maximum_participants 15 | -------------------------------------------------------------------------------- /Advanced/Modern_Gambling/main.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alireza-hashemii/PythonApps/d6e2ccb21c2d0a9669a1e9e3b177c9f5155301bf/Advanced/Modern_Gambling/main.py -------------------------------------------------------------------------------- /Advanced/Modern_Gambling/user.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | 3 | 4 | class User: 5 | users = [] 6 | def __init__(self, information:list): 7 | self.Name,self.Lastname,self.Age,self.passsword, *_ = information 8 | self.Id = uuid.uuid4() 9 | self.accountValue = "" 10 | self.gamblesHistory = {} 11 | 12 | 13 | def __str__(self) -> str: 14 | return f"{self.Name} {self.Lastname}" -------------------------------------------------------------------------------- /Advanced/Music player application/file.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alireza-hashemii/PythonApps/d6e2ccb21c2d0a9669a1e9e3b177c9f5155301bf/Advanced/Music player application/file.png -------------------------------------------------------------------------------- /Advanced/Music player application/main.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | window = Tk() 4 | window.geometry("300x300") 5 | window.title("Python Music Player") 6 | 7 | textlabel = Label(window,text="This is a play Button") 8 | textlabel.pack() 9 | 10 | def something(): 11 | print("i am being clicked") 12 | 13 | photo = PhotoImage(file='file.png') 14 | Play_Button = Button(window,image=photo,command=something) 15 | Play_Button.pack() 16 | window.mainloop() -------------------------------------------------------------------------------- /Advanced/Snake_Game.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | import random 3 | 4 | GAME_WIDTH = 700 5 | GAME_HEIGHT = 700 6 | SPEED = 100 7 | SPACE_SIZE = 50 8 | BODY_PARTS = 3 9 | SNAKE_COLOR = "#00FF00" 10 | FOOD_COLOR = "#FF0000" 11 | BACKGROUND_COLOR = "#000000" 12 | 13 | 14 | class Snake: 15 | 16 | def __init__(self): 17 | self.body_size = BODY_PARTS 18 | self.coordinates = [] 19 | self.squares = [] 20 | 21 | for i in range(0, BODY_PARTS): 22 | self.coordinates.append([0, 0]) 23 | 24 | for x, y in self.coordinates: 25 | square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR, tag="snake") 26 | self.squares.append(square) 27 | 28 | 29 | class Food: 30 | 31 | def __init__(self): 32 | 33 | x = random.randint(0, (GAME_WIDTH / SPACE_SIZE)-1) * SPACE_SIZE 34 | y = random.randint(0, (GAME_HEIGHT / SPACE_SIZE) - 1) * SPACE_SIZE 35 | 36 | self.coordinates = [x, y] 37 | 38 | canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=FOOD_COLOR, tag="food") 39 | 40 | 41 | def next_turn(snake, food): 42 | 43 | x, y = snake.coordinates[0] 44 | 45 | if direction == "up": 46 | y -= SPACE_SIZE 47 | elif direction == "down": 48 | y += SPACE_SIZE 49 | elif direction == "left": 50 | x -= SPACE_SIZE 51 | elif direction == "right": 52 | x += SPACE_SIZE 53 | 54 | snake.coordinates.insert(0, (x, y)) 55 | 56 | square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR) 57 | 58 | snake.squares.insert(0, square) 59 | 60 | if x == food.coordinates[0] and y == food.coordinates[1]: 61 | 62 | global score 63 | 64 | score += 1 65 | 66 | label.config(text="Score:{}".format(score)) 67 | 68 | canvas.delete("food") 69 | 70 | food = Food() 71 | 72 | else: 73 | 74 | del snake.coordinates[-1] 75 | 76 | canvas.delete(snake.squares[-1]) 77 | 78 | del snake.squares[-1] 79 | 80 | if check_collisions(snake): 81 | game_over() 82 | 83 | else: 84 | window.after(SPEED, next_turn, snake, food) 85 | 86 | 87 | def change_direction(new_direction): 88 | 89 | global direction 90 | 91 | if new_direction == 'left': 92 | if direction != 'right': 93 | direction = new_direction 94 | elif new_direction == 'right': 95 | if direction != 'left': 96 | direction = new_direction 97 | elif new_direction == 'up': 98 | if direction != 'down': 99 | direction = new_direction 100 | elif new_direction == 'down': 101 | if direction != 'up': 102 | direction = new_direction 103 | 104 | 105 | def check_collisions(snake): 106 | 107 | x, y = snake.coordinates[0] 108 | 109 | if x < 0 or x >= GAME_WIDTH: 110 | return True 111 | elif y < 0 or y >= GAME_HEIGHT: 112 | return True 113 | 114 | for body_part in snake.coordinates[1:]: 115 | if x == body_part[0] and y == body_part[1]: 116 | return True 117 | 118 | return False 119 | 120 | 121 | def game_over(): 122 | 123 | canvas.delete(ALL) 124 | canvas.create_text(canvas.winfo_width()/2, canvas.winfo_height()/2, 125 | font=('consolas',70), text="GAME OVER", fill="red", tag="gameover") 126 | 127 | 128 | window = Tk() 129 | window.title("Snake game") 130 | window.resizable(False, False) 131 | 132 | score = 0 133 | direction = 'down' 134 | 135 | label = Label(window, text="Score:{}".format(score), font=('consolas', 40)) 136 | label.pack() 137 | 138 | canvas = Canvas(window, bg=BACKGROUND_COLOR, height=GAME_HEIGHT, width=GAME_WIDTH) 139 | canvas.pack() 140 | 141 | window.update() 142 | 143 | window_width = window.winfo_width() 144 | window_height = window.winfo_height() 145 | screen_width = window.winfo_screenwidth() 146 | screen_height = window.winfo_screenheight() 147 | 148 | x = int((screen_width/2) - (window_width/2)) 149 | y = int((screen_height/2) - (window_height/2)) 150 | 151 | window.geometry(f"{window_width}x{window_height}+{x}+{y}") 152 | 153 | window.bind('', lambda event: change_direction('left')) 154 | window.bind('', lambda event: change_direction('right')) 155 | window.bind('', lambda event: change_direction('up')) 156 | window.bind('', lambda event: change_direction('down')) 157 | 158 | snake = Snake() 159 | food = Food() 160 | 161 | next_turn(snake, food) 162 | 163 | window.mainloop() -------------------------------------------------------------------------------- /Advanced/Warehouse_Management.py: -------------------------------------------------------------------------------- 1 | # import needed libraries 2 | import time 3 | from colorama import Fore 4 | import psycopg2 5 | import datetime 6 | 7 | # connect to Database with psycopg2 8 | connection = psycopg2.connect(database="chart", user="postgres", password="1234", host="127.0.0.1", port="5432") 9 | # Making Cursor To Work With Database 10 | cursor = connection.cursor() 11 | 12 | class Product: 13 | def __init__(self , name , id , price , date_joined): 14 | self.name = name 15 | self.id = id 16 | self.price = price 17 | self.date_joined = date_joined 18 | 19 | while True: 20 | User_selection = int(input(""" ---- MENU STOREROOM ---- 21 | 1- Add a product 22 | 2- List of products 23 | 3- delete a product 24 | 4- Show product description 25 | 5- Update specific Product 26 | 6- Exit \n 27 | Enter a number from the list: """)) 28 | # add a product to db. 29 | 30 | if User_selection == 1: 31 | user_product = Product( 32 | input("Enter name of product: "), 33 | int(input("Enter Id of product: ")), 34 | int(input("Price of Product: ")), 35 | datetime.datetime.now() 36 | ) 37 | date = user_product.date_joined.strftime("%x") 38 | name , id , price , date_joined = str(user_product.name) , int(user_product.id) , int(user_product.price) , date 39 | 40 | cursor.execute(f"INSERT INTO Product (name,id,price,datejoined) \ 41 | VALUES ('{name}',{id},{price},'{date_joined}')"); 42 | connection.commit() 43 | print (Fore.GREEN + "Operation Done successfully") 44 | time.sleep(1) 45 | cursor.close() 46 | 47 | # show list of products 48 | 49 | if User_selection == 2: 50 | cursor.execute("SELECT * from Product") 51 | rows = cursor.fetchall() 52 | rows = list(rows) 53 | if len(rows) >= 1: 54 | for row in rows: 55 | print ("Name = ", row[0]) 56 | print ("Id = ", row[1]) 57 | print ("Price = ", row[2]) 58 | print ("Date Joined = ", row[3]) 59 | print("--------------------------------") 60 | else: 61 | print(Fore.RED + "Sorry List has no Products !") 62 | time.sleep(3.5) 63 | cursor.close() 64 | 65 | # delete product 66 | if User_selection == 3: 67 | result = input(Fore.YELLOW + "Show The Results After Proccess? yes/no: ") 68 | if result == "yes": 69 | 70 | User_deleted_record = (input("Which Product You want To Delete Enter It's Id: ")) 71 | id = int(User_deleted_record) 72 | cursor.execute("DELETE from Product where id=id;") 73 | print (f"Total number of rows deleted :{cursor.rowcount}") 74 | connection.commit() 75 | print(Fore.RED + "Product Deleted sucusfully and it's the result!","\n") 76 | cursor.execute("SELECT name,id,price, datejoined from Product") 77 | rows = cursor.fetchall() 78 | for row in rows: 79 | print ("Name = ", row[0]) 80 | print ("Id = ", row[1]) 81 | print ("Price = ", row[2]) 82 | print ("Date Joined = ", row[3]) 83 | print("--------------------------------") 84 | time.sleep(4) 85 | cursor.close() 86 | elif result != 'yes' and 'no': 87 | print(Fore.RED , "please Choose from legal options!") 88 | else: 89 | User_deleted_record = (input("Which Product You want To Delete Enter It's Id: ")) 90 | cursor.execute("DELETE from Product where id=id;") 91 | connection.commit() 92 | print(Fore.RED + "Product Deleted succusfully! ") 93 | time.sleep(1) 94 | cursor.close() 95 | 96 | # see on product details 97 | 98 | if User_selection == 4: 99 | which_product = int(input("Which Product Description you Want to see Specificly: it's id: ")) 100 | id = int(which_product) 101 | try: 102 | product_detail = cursor.execute("SELECT * FROM Product WHERE id=id") 103 | product_detail = str(product_detail) 104 | rows = cursor.fetchone() 105 | print(f"name: {rows[0]}") 106 | print(f"id: {rows[1]}") 107 | print(f"Price: {rows[2]}") 108 | print(f"date Joined: {rows[3]}") 109 | except(Exception): 110 | print(Fore.RED + "Sorry - no Product !") 111 | time.sleep(4) 112 | cursor.close() 113 | 114 | # change detail of product 115 | 116 | if User_selection == 5: 117 | which_product = (input("Which Product you Want to make change Specificly: it's id: ")) 118 | id = int(which_product) 119 | change_part = int(input("Enter 1 for name - 2 for id - 3 for price: ")) 120 | if change_part == 1: 121 | new_name = input("Enter new name: ") 122 | cursor.execute(f"UPDATE Product set name = '{new_name}' WHERE id = {id}") 123 | print ("Total number of rows updated :", cursor.rowcount) 124 | connection.commit() 125 | print(Fore.GREEN, "It changed successfully") 126 | time.sleep(1) 127 | cursor.close() 128 | 129 | elif change_part == 2: 130 | new_id = int(input("Enter new id: ")) 131 | cursor.execute(f"UPDATE Product set id = {new_id} WHERE id = {id}") 132 | print ("Total number of rows updated :", cursor.rowcount) 133 | connection.commit() 134 | print(Fore.GREEN, "id changed successfully") 135 | time.sleep(1) 136 | cursor.close() 137 | 138 | elif change_part == 3: 139 | new_price = int(input("Enter new price: ")) 140 | cursor.execute(f"UPDATE Product set price = {new_price} WHERE id = {id}") 141 | print ("Total number of rows updated :", cursor.rowcount) 142 | connection.commit() 143 | print(Fore.GREEN, "price changed successfully") 144 | 145 | # exit from program 146 | if User_selection == 6: 147 | print(Fore.BLUE , "Have a Great Day") 148 | time.sleep(3) 149 | break 150 | cursor.close() 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | -------------------------------------------------------------------------------- /Advanced/chatroom application using socket/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.linting.enabled": false 3 | } -------------------------------------------------------------------------------- /Advanced/chatroom application using socket/client.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import tkinter 3 | from tkinter import * 4 | import threading 5 | 6 | 7 | def receive(): 8 | while True: 9 | try: 10 | msg= sock.recv(1024).decode("utf8") 11 | msg_list.insert(tkinter.END,msg) 12 | except: 13 | print("There is an unexpected Error occured") 14 | 15 | def send(): 16 | msg = my_msg.get() 17 | my_msg.set("") 18 | sock.send(bytes(msg,"utf8")) 19 | if msg=="#quit": 20 | sock.close() 21 | window.close() 22 | 23 | def on_closing(): 24 | my_msg.set("#quit") 25 | send() 26 | 27 | 28 | window = Tk() 29 | window.title("Chatroom application") 30 | window.configure(bg="green") 31 | message_frame = Frame(window,height=100,width=100,bg="red") 32 | message_frame.pack() 33 | my_msg = StringVar() 34 | my_msg.set("") 35 | 36 | scroll_bar = Scrollbar(message_frame) 37 | msg_list = Listbox(message_frame,height=15,width=100,bg="red",yscrollcommand=scroll_bar.set) 38 | scroll_bar.pack(side=RIGHT,fill=Y) 39 | msg_list.pack(side=LEFT,fill=BOTH) 40 | msg_list.pack() 41 | 42 | label = Label(window,text="Enter your message",fg="blue",font="Aeria",bg="red") 43 | label.pack() 44 | entry_field = Entry(window,textvariable=my_msg,fg="red",width=50) 45 | entry_field.pack() 46 | 47 | send_Button = Button(window,text="send",font="Aerial",fg="white",command=send) 48 | send_Button.pack() 49 | 50 | quit_Button = Button(window,text="Quit",font="Aerial",fg="white",command=on_closing) 51 | quit_Button.pack() 52 | 53 | 54 | host = "localhost" 55 | port = 8080 56 | 57 | sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 58 | sock.connect((host,port)) 59 | 60 | receive_Thread = threading.Thread(target=receive) 61 | receive_Thread.start() 62 | 63 | 64 | 65 | mainloop() -------------------------------------------------------------------------------- /Advanced/chatroom application using socket/client_2.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import tkinter 3 | from tkinter import * 4 | import threading 5 | 6 | 7 | def receive(): 8 | while True: 9 | try: 10 | msg= sock.recv(1024).decode("utf8") 11 | msg_list.insert(tkinter.END,msg) 12 | except: 13 | print("There is an unexpected Error occured") 14 | 15 | def send(): 16 | msg = my_msg.get() 17 | my_msg.set("") 18 | sock.send(bytes(msg,"utf8")) 19 | if msg=="#quit": 20 | sock.close() 21 | window.close() 22 | 23 | def on_closing(): 24 | my_msg.set("#quit") 25 | send() 26 | 27 | 28 | window = Tk() 29 | window.title("Chatroom application") 30 | window.configure(bg="green") 31 | message_frame = Frame(window,height=100,width=100,bg="red") 32 | message_frame.pack() 33 | my_msg = StringVar() 34 | my_msg.set("") 35 | 36 | scroll_bar = Scrollbar(message_frame) 37 | msg_list = Listbox(message_frame,height=15,width=100,bg="red",yscrollcommand=scroll_bar.set) 38 | scroll_bar.pack(side=RIGHT,fill=Y) 39 | msg_list.pack(side=LEFT,fill=BOTH) 40 | msg_list.pack() 41 | 42 | label = Label(window,text="Enter your message",fg="blue",font="Aeria",bg="red") 43 | label.pack() 44 | entry_field = Entry(window,textvariable=my_msg,fg="red",width=50) 45 | entry_field.pack() 46 | 47 | send_Button = Button(window,text="send",font="Aerial",fg="white",command=send) 48 | send_Button.pack() 49 | 50 | quit_Button = Button(window,text="Quit",font="Aerial",fg="white",command=on_closing) 51 | quit_Button.pack() 52 | 53 | 54 | host = "localhost" 55 | port = 8080 56 | 57 | sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 58 | sock.connect((host,port)) 59 | 60 | receive_Thread = threading.Thread(target=receive) 61 | receive_Thread.start() 62 | 63 | 64 | 65 | mainloop() -------------------------------------------------------------------------------- /Advanced/chatroom application using socket/server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | from threading import Thread 3 | 4 | host = "localhost" 5 | port = 8080 6 | 7 | sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 8 | sock.bind((host,port)) 9 | 10 | clients = {} 11 | addresses = {} 12 | 13 | def handle_clients(conn,addr): 14 | name = conn.recv(1024).decode() 15 | welcome = f"welcome {name}. tab #quit to get out of chatroom" 16 | conn.recv(bytes(welcome,"utf8")) 17 | msg = name + "has already joined to chatroom" 18 | broadcast(bytes(msg,"utf8")) 19 | clients[conn] = name 20 | 21 | while True: 22 | msg = conn.recv(1024) 23 | if msg != "#quit": 24 | broadcast(msg,name,":") 25 | else: 26 | conn.send(bytes("#quit","utf8")) 27 | conn.close() 28 | del clients[conn] 29 | 30 | def accept_clients_connection(): 31 | while True: 32 | client_conn,conn_address=sock.accept() 33 | print(conn_address,"Has connected...") 34 | client_conn.send("Welcome to chatroom. please type your name to continue ".encode("utf8")) 35 | addresses[client_conn] = conn_address 36 | Thread(target=handle_clients,args=[client_conn,conn_address]) 37 | 38 | def broadcast(msg,prefix=""): 39 | for x in clients: 40 | x.send(bytes(prefix,"utf8")+msg) 41 | 42 | 43 | if __name__ == "__main__": 44 | sock.listen(5) 45 | print("server is listening to requests sent by clients...") 46 | thread = Thread(target=accept_clients_connection) 47 | thread.start() 48 | thread.join() -------------------------------------------------------------------------------- /BeginnerTOIntermediate/DimmerSwitch.py: -------------------------------------------------------------------------------- 1 | class DimmerSwitch: 2 | def __init__(self): 3 | self.IsOn = False 4 | self.IsMute = False 5 | self.MaximumVolume = 10 6 | self.volume = 0 7 | 8 | def turn_on(self): 9 | self.IsOn = True 10 | return None 11 | 12 | def raise_volume(self): 13 | if self.IsOn == False: 14 | print("it's not on") 15 | return None 16 | 17 | elif self.IsMute == True: 18 | self.IsMute = not self.IsMute 19 | if self.volume < self.MaximumVolume: 20 | self.volume += 1 21 | print("Done") 22 | 23 | elif self.volume < self.MaximumVolume: 24 | self.volume += 1 25 | return None 26 | else: 27 | print("It's not possible") 28 | 29 | def reduce_volume(self): 30 | if self.volume < 1: 31 | print("lowest volume") 32 | return None 33 | else: 34 | self.volume -= 1 35 | return None 36 | 37 | 38 | odimmer = DimmerSwitch() 39 | odimmer.IsOn = True 40 | odimmer.raise_volume() 41 | print(odimmer.volume) 42 | odimmer.reduce_volume() 43 | odimmer.reduce_volume() 44 | odimmer.reduce_volume() 45 | odimmer.reduce_volume() 46 | odimmer.reduce_volume() 47 | odimmer.reduce_volume() 48 | print(odimmer.volume) 49 | 50 | 51 | -------------------------------------------------------------------------------- /BeginnerTOIntermediate/HigherOrLower.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | SuitTuple = ("Spades","Hearts","Diamons","Clubs") 4 | RankTuple = ("Ace","2","3","4","5","6","7","8","9","Jack","Queen","King") 5 | 6 | NCARDS = 8 7 | starting_deck_list = [] 8 | 9 | def getcard(DeckListIn:list): 10 | this_card = DeckListIn.pop() 11 | return this_card 12 | 13 | 14 | def change_order(DeckListIn:list): 15 | DeckListOut = DeckListIn.copy() 16 | random.shuffle(DeckListOut) 17 | return DeckListOut 18 | 19 | 20 | for suit in SuitTuple: 21 | for value,rank in enumerate(RankTuple,1): 22 | card_dict = {"suit":suit,"value":value,"rank":rank} 23 | starting_deck_list.append(card_dict) 24 | 25 | score = 50 26 | 27 | while True: 28 | gameDeckList = change_order(starting_deck_list) 29 | currentCardDict = getcard(gameDeckList) 30 | currentCardRank = currentCardDict['rank'] 31 | currentCardValue = currentCardDict['value'] 32 | currentCardSuit = currentCardDict['suit'] 33 | print('Starting card is:', currentCardRank + ' of ' +currentCardSuit) 34 | print() 35 | 36 | for carditem in range(0,NCARDS): 37 | answer = input("would next card be greater or tinyer than currnt card l or h: ") 38 | answer = answer.casefold() 39 | nextCardDict = getcard(gameDeckList) 40 | nextCardSuit = nextCardDict["suit"] 41 | nextCardRank = nextCardDict["rank"] 42 | nextCardValue = nextCardDict["value"] 43 | 44 | if answer == "l": 45 | if currentCardValue > nextCardValue: 46 | print("You are right") 47 | score = score + 15 48 | else: 49 | print("You lose") 50 | score = score - 15 51 | 52 | elif answer == "h": 53 | if currentCardValue < nextCardValue: 54 | print("You are right") 55 | score = score + 15 56 | else: 57 | print("You lose") 58 | score = score - 15 59 | 60 | print(f"your score is {score}") 61 | currentCardRank = nextCardRank 62 | currentCardValue = nextCardValue 63 | 64 | continue_or_not = input("y-n: ") 65 | if continue_or_not == "n": 66 | break 67 | 68 | 69 | -------------------------------------------------------------------------------- /BeginnerTOIntermediate/Isosceles triangle.py: -------------------------------------------------------------------------------- 1 | rows = int(input("Enter number of rows: ")) 2 | k = 0 3 | 4 | for i in range(1, rows+1): 5 | for space in range(0,(rows-i)): 6 | print(end=" ") 7 | 8 | while k!=(2*i-1): 9 | print("* ", end="") 10 | k += 1 11 | 12 | k = 0 13 | print() 14 | 15 | -------------------------------------------------------------------------------- /BeginnerTOIntermediate/Tv.py: -------------------------------------------------------------------------------- 1 | class Tv: 2 | def __init__(self): 3 | self.ListChannels = [4,5,6,9,10,12] 4 | self.IsMute = False # tv is unmute by default 5 | self.IsOn = False # tv is off by default 6 | self.current_chanell = False # at commence there is no channel running on Tv 7 | 8 | def power(self): 9 | pass 10 | 11 | def raise_vol(self): 12 | pass 13 | 14 | def reduce_vol(self): 15 | pass 16 | 17 | def raise_channel(self): 18 | pass 19 | 20 | def reduce_channel(self): 21 | pass -------------------------------------------------------------------------------- /BeginnerTOIntermediate/clock.py: -------------------------------------------------------------------------------- 1 | import tkinter 2 | 3 | # retrieve system's time 4 | from time import strftime 5 | 6 | # ------------------main code----------------------- 7 | # initializing the main UI object 8 | top = tkinter.Tk() 9 | # setting title of the App 10 | top.title("Clock") 11 | # restricting the resizable property 12 | top.resizable(0, 0) 13 | 14 | 15 | def time(): 16 | string = strftime("%H:%M:%S %p") 17 | clockTime.config(text=string) 18 | clockTime.after(1000, time) 19 | 20 | 21 | clockTime = tkinter.Label( 22 | top, font=("calibri", 40, "bold"), background="black", foreground="white" 23 | ) 24 | 25 | clockTime.pack(anchor="center") 26 | time() 27 | 28 | 29 | top.mainloop() 30 | -------------------------------------------------------------------------------- /BeginnerTOIntermediate/email_sender.py: -------------------------------------------------------------------------------- 1 | import smtplib 2 | 3 | # ! receiveing sender email and password 4 | 5 | sender_email = 'pyaireza7@gmail.com' 6 | receiver_email = 'ahashemi5665@gmail.com' 7 | password = 'sdlrjodkrmawxgdc' 8 | password = str(password) 9 | message = "hey here we have something" 10 | 11 | # todo connect to smtp server and login to our email account 12 | 13 | server = smtplib.SMTP('smtp.gmail.com',587) 14 | server.ehlo() 15 | server.starttls() 16 | server.login(sender_email,password) 17 | print("Login success") 18 | server.sendmail(sender_email,receiver_email,message) 19 | print("Email has been sent to",receiver_email) 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /BeginnerTOIntermediate/generate_random_password.py: -------------------------------------------------------------------------------- 1 | import random 2 | import math 3 | 4 | # All available options and their amount. 5 | alpha = "abcdefghijklmnopqrstuvwxyz" 6 | numeric = "0123456789" 7 | other = "%?@$^#" 8 | 9 | # Get input from the user (Length of password). 10 | password_len = int(input("Enter Password Length: ")) 11 | 12 | # Select the value of each option based on 50-30-20 formula. 13 | alpha_element = password_len // 2 14 | numeric_element = math.ceil(password_len * 30/100) 15 | other_element = password_len - (alpha_element + numeric_element) 16 | 17 | password = [] 18 | 19 | # Core of program(generate password). 20 | def generate_password(length,array,is_alpha=False): 21 | for i in range(length): 22 | item = random.randint(0 , len(array) -1) 23 | character = array[item] 24 | if is_alpha: 25 | case =random.randint(0,1) 26 | if case == 1: 27 | character = character.upper() 28 | password.append(character) 29 | 30 | # Alpha part of password 31 | generate_password(alpha_element,alpha,True) 32 | # numeric part of password 33 | generate_password(numeric_element,numeric) 34 | # other part of password 35 | generate_password(other_element,other) 36 | 37 | # mix the elements 38 | random.shuffle(password) 39 | 40 | # Convert list to string 41 | gen_password = "" 42 | for i in password: 43 | gen_password += str(i) 44 | print(gen_password) 45 | 46 | -------------------------------------------------------------------------------- /BeginnerTOIntermediate/guess_number.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | laps = 10 4 | number_of_guesses = 1 5 | 6 | for i in range(laps): 7 | random_number = random.randint(0,5) 8 | user_number = int(input("Enter a number in range 0-10: ")) 9 | if random_number == user_number: 10 | print(f"Congrats you have guessed right with {number_of_guesses} guesses.") 11 | break 12 | else: 13 | number_of_guesses += 1 14 | continue 15 | -------------------------------------------------------------------------------- /BeginnerTOIntermediate/leapyear.py: -------------------------------------------------------------------------------- 1 | # get input from user 2 | 3 | year = int(input("Enter the year:-")) 4 | 5 | # calculate if it's leap year or not 6 | 7 | if ((year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)): 8 | 9 | # return the answer 10 | 11 | print(f"{year} is a leap year.") 12 | else: 13 | print(f"{year} it's not a leap year") -------------------------------------------------------------------------------- /BeginnerTOIntermediate/min_max_approach.py: -------------------------------------------------------------------------------- 1 | first_number = int(input("Enter first number: ")) 2 | second_number = int(input("Enter second number: ")) 3 | third_number = int(input("Enter third number: ")) 4 | numbers_list = [] 5 | numbers_list.append(first_number) 6 | numbers_list.append(third_number) 7 | numbers_list.append(second_number) 8 | if first_number > second_number: 9 | max = first_number 10 | else : 11 | max = second_number 12 | if max < third_number: 13 | max = third_number 14 | else: 15 | max = max * 1 16 | x1= max 17 | numbers_list.remove(max) 18 | if numbers_list[0] > numbers_list[1]: 19 | x2 = numbers_list[0] 20 | x3 = numbers_list[1] 21 | else: 22 | x2 = numbers_list[1] 23 | x3 = numbers_list[0] 24 | print(x1,">",x2,">",x3) 25 | print("\U0001F605") 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /BeginnerTOIntermediate/num-triangle.py: -------------------------------------------------------------------------------- 1 | rows = int(input("Enter number of rows: ")) 2 | number = 1 3 | 4 | for i in range(1, rows+1): 5 | for j in range(1, i+1): 6 | print(number, end=" ") 7 | number += 1 8 | print() -------------------------------------------------------------------------------- /BeginnerTOIntermediate/number_to_year.py: -------------------------------------------------------------------------------- 1 | from math import ceil 2 | number = int(input("Enter a number: ")) 3 | 4 | if number in range(1,187): 5 | day = number % 31 if number % 31 != 0 else 31 6 | month = number / 31 7 | print(f"Day is {day}") 8 | print(f"Month is {ceil(month)}") 9 | 10 | elif number in range(187, 367): 11 | n_new = number - 186 12 | day = n_new % 30 if n_new % 30 != 0 else 30 13 | month = n_new / 30 14 | print(f"Day is {day}") 15 | print(f"Month is {ceil(month) + 6}") -------------------------------------------------------------------------------- /BeginnerTOIntermediate/qrcode.py: -------------------------------------------------------------------------------- 1 | import pyqrcode 2 | import png 3 | from pyqrcode import QRCode 4 | 5 | # Text which is to be converted to QR code 6 | print("Enter text to convert") 7 | s = input(": ") 8 | # Name of QR code png file 9 | print("Enter image name to save") 10 | n = input(": ") 11 | # Adding extension as .pnf 12 | d = n + ".png" 13 | # Creating QR code 14 | url = pyqrcode.create(s) 15 | # Saving QR code as a png file 16 | url.show() 17 | url.png(d, scale=6) 18 | 19 | -------------------------------------------------------------------------------- /BeginnerTOIntermediate/quizGame.py: -------------------------------------------------------------------------------- 1 | print(" Welcome To My Quiz Game \n Interesting Game to Play") 2 | Player = input(" Do you want to play the game? \n" ) 3 | if Player.lower() != 'yes': 4 | print("Good Bye") 5 | quit() 6 | 7 | name_player = input("Enter Your Name: ") 8 | 9 | print("Let's Start the Game :) ",name_player) 10 | 11 | score = 0 12 | 13 | answer = input(' What is CPU stands for? \n ') 14 | if answer.lower() == 'central processing unit': 15 | print("Correct") 16 | score += 1 17 | else: 18 | print('Wrong') 19 | 20 | answer = input(' What is GPU stands for? \n ') 21 | if answer.lower() == 'graphical processing unit': 22 | print("Correct") 23 | score += 1 24 | else: 25 | print('Wrong') 26 | 27 | answer = input(' What is RAM stands for? \n ') 28 | if answer.lower() == 'random access memory': 29 | print("Correct") 30 | score += 1 31 | else: 32 | print('Wrong') 33 | 34 | answer = input(' What is ROM stands for? \n ') 35 | if answer.lower() == 'read only memory': 36 | print("Correct") 37 | score += 1 38 | else: 39 | print('Wrong') 40 | 41 | answer = input(' Mouse is an input device or output device? \n ') 42 | if answer.lower() == 'input device': 43 | print("Correct") 44 | score += 1 45 | else: 46 | print('Wrong') 47 | 48 | print("You got the " + str(score)+ " correct answers") 49 | print("You got the " + str((score/5) *100)+ " correct answers") 50 | -------------------------------------------------------------------------------- /BeginnerTOIntermediate/straigt.py: -------------------------------------------------------------------------------- 1 | row = int(input("Enter: ")) 2 | for i in range(1): 3 | j = 1 4 | for j in range(row+1): 5 | print(j * "* ") -------------------------------------------------------------------------------- /BeginnerTOIntermediate/text_to_morse_code.py: -------------------------------------------------------------------------------- 1 | #all_the symbols 2 | symbols = { 3 | "a": ".-", 4 | "b": "-...", 5 | "c": "-.-.", 6 | "d": "-..", 7 | "e": ".", 8 | "f": "..-.", 9 | "g": ".-", 10 | "h": "....", 11 | "i": "..", 12 | "j": ".---", 13 | "k": "-.-", 14 | "l": ".-..", 15 | "m": "--", 16 | "n": "-.", 17 | "o": "---", 18 | "p": ".--.", 19 | "q": "--.-", 20 | "r": ".-.", 21 | "s": "...", 22 | "t": "-", 23 | "u": "..-", 24 | "v": "...-", 25 | "w": ".--", 26 | "x": "-..-", 27 | "y": "-.--", 28 | "z": "--..", 29 | } 30 | 31 | #the user has to type a word 32 | ask = input("type: ") 33 | 34 | 35 | length = len(ask) 36 | output = "" 37 | 38 | for i in range(length): 39 | if ask[i] in symbols.keys(): 40 | output = output + " " + symbols.get(ask[i]) 41 | 42 | print(output) 43 | -------------------------------------------------------------------------------- /BeginnerTOIntermediate/time_coundown.py: -------------------------------------------------------------------------------- 1 | import time 2 | # core of program find (min) and (sec) with divmod func. 3 | 4 | def countdown(t): 5 | while t: 6 | minutes , seconds = divmod(t,60) 7 | timer = f'{minutes}:{seconds}' 8 | print(timer,end="\r") 9 | time.sleep(1) 10 | t -= 1 11 | 12 | print("Time Completed!") 13 | 14 | # input seconds from the user 15 | 16 | t = input("Enter time in seconds: ") 17 | countdown(int(t)) -------------------------------------------------------------------------------- /BeginnerTOIntermediate/unique.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | # script to fetch unique sorted words from a text file. 4 | list_of_words = [] 5 | 6 | # Alternate Method to insert file 7 | # filename = input("Enter file name: ") 8 | filename = "text_file.txt" 9 | 10 | with open(filename, "r") as f: 11 | for line in f: 12 | # if case is ignored then Great and great are same words 13 | list_of_words.extend(re.findall(r"[\w]+", line.lower())) 14 | # else use this alternate method: 15 | # list_of_words.extend(re.findall(r"[\w]+", line)) 16 | 17 | 18 | # Creating a dictionary to store the number of occurence of a word 19 | unique = {} 20 | for each in list_of_words: 21 | if each not in unique: 22 | unique[each] = 0 23 | unique[each] += 1 24 | 25 | # Creating a list to sort the final unique words 26 | s = [] 27 | 28 | # If occurence of a word(val) is 1 then it is unique 29 | for key, val in unique.items(): 30 | if val == 1: 31 | s.append(key) 32 | 33 | print(sorted(s)) 34 | 35 | 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 alireza-hashemii 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Leetcode/Majority Element II.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def majorityElement(self, nums: list[int]) -> list[int]: 4 | if len(nums) < 3: 5 | return (list(set(nums))) 6 | else: 7 | counter = Counter(nums) 8 | treshhold = len(nums) // 3 9 | return [key for key,val in counter.items() if val > treshhold] 10 | 11 | # runtime 86 ms Beats 97.99% of users with Python3 12 | # space 17.86mg Beats 78.71% of users with Python3 13 | 14 | 15 | 16 | 17 | #? space optimized answer1 18 | # def majorityElement(nums: List[int]) -> List[int]: 19 | # treshold = len(nums) / 3 20 | # return [n for n, c in Counter(nums).items() if c > treshold] 21 | # with open('user.out', 'w') as f: 22 | # for case in map(loads, stdin): 23 | # f.write(f"{majorityElement(case)}\n") 24 | # exit(0) 25 | 26 | 27 | #? space opimized answer2 28 | # class Solution: 29 | # def majorityElement(self, nums: List[int]) -> List[int]: 30 | 31 | # dct = {} 32 | # sol = [] 33 | # n = len(nums) 34 | # for no in nums: 35 | # if(no in dct.keys()): 36 | # dct[no]+=1 37 | # else: 38 | # dct[no]=1 39 | # if(dct[no]==n//3+1): 40 | # sol.append(no) 41 | 42 | # return(sol) 43 | 44 | 45 | 46 | #? runtime optimized answer1 47 | # class Solution: 48 | # def majorityElement(self, nums: List[int]) -> List[int]: 49 | # x = y = None 50 | # cx = cy = 0 51 | 52 | # for num in nums: 53 | # if cx == 0 and num != y: 54 | # x = num 55 | # cx = 1 56 | # elif cy == 0 and num != x: 57 | # y = num 58 | # cy = 1 59 | # elif num == x: 60 | # cx += 1 61 | # elif num == y: 62 | # cy += 1 63 | # else: 64 | # cx -= 1 65 | # cy -= 1 66 | 67 | # cx = cy = 0 68 | # for num in nums: 69 | # if num == x: 70 | # cx += 1 71 | # elif num == y: 72 | # cy += 1 73 | 74 | # result = [] 75 | # if cx > len(nums) // 3: 76 | # result.append(x) 77 | # if cy > len(nums) // 3: 78 | # result.append(y) 79 | # return result -------------------------------------------------------------------------------- /Leetcode/MedianSortedArray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float: 3 | nums1.extend(nums2) 4 | nums1.sort() 5 | 6 | if len(nums1) % 2 != 0: 7 | mid = nums1[len(nums1) // 2] 8 | return float(mid) 9 | else: 10 | t = len(nums1) // 2 11 | median = (nums1[t] + nums1[t-1]) / 2 12 | return median 13 | 14 | # runtime 74 ms Beats 88.16 of users with Python3 15 | # space 16.88 Beats 87.40 of users with Python3 -------------------------------------------------------------------------------- /Leetcode/Squares of a Sorted Array.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alireza-hashemii/PythonApps/d6e2ccb21c2d0a9669a1e9e3b177c9f5155301bf/Leetcode/Squares of a Sorted Array.py -------------------------------------------------------------------------------- /Leetcode/addTwoNumbers.py: -------------------------------------------------------------------------------- 1 | # import time 2 | 3 | # class ListNode: 4 | # def __init__(self, val=0, next=None): 5 | # self.val = val 6 | # self.next = next 7 | 8 | # innermost = ListNode(7 , None) 9 | # lnode_inner = ListNode(6 , innermost) 10 | # lnode= ListNode(4 , lnode_inner) 11 | 12 | 13 | # l1_content = [] 14 | 15 | # while True: 16 | # if lnode.next is None: 17 | # l1_content.insert(0 , lnode.val) 18 | # break 19 | 20 | # l1_content.insert(0, lnode.val) 21 | # lnode = lnode.next 22 | 23 | 24 | # l1_copy = l1_content.copy() 25 | # num = str(int(''.join(str(i) for i in l1_content))) 26 | 27 | # for i in range(-1 , -(len(num) + 1), -1): 28 | # if i == -1: 29 | # n_one_to_last = None 30 | # n_last = ListNode(int(num[i])) 31 | 32 | # else: 33 | # n_one_to_last = n_last 34 | # n_last = ListNode(int(num[i]), n_one_to_last) 35 | 36 | 37 | 38 | 39 | # gpt suggested 40 | class ListNode: 41 | def __init__(self, val=0, next=None): 42 | self.val = val 43 | self.next = next 44 | 45 | class Solution: 46 | def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: 47 | dummy_head = ListNode(0) # Placeholder for the result list 48 | current = dummy_head # Pointer to build the new list 49 | carry = 0 # Initialize carry to 0 50 | 51 | # Loop until both lists are processed and no carry remains 52 | while l1 is not None or l2 is not None or carry: 53 | val1 = l1.val if l1 else 0 # Get value from l1 or 0 if l1 is None 54 | val2 = l2.val if l2 else 0 # Get value from l2 or 0 if l2 is None 55 | 56 | # Calculate the sum and carry 57 | total = val1 + val2 + carry 58 | carry = total // 10 # Update carry for next iteration 59 | current.next = ListNode(total % 10) # Create new node for the result 60 | current = current.next # Move to the next node 61 | 62 | # Move to the next nodes in l1 and l2 if possible 63 | if l1: l1 = l1.next 64 | if l2: l2 = l2.next 65 | 66 | return dummy_head.next # Return the next node after the dummy head -------------------------------------------------------------------------------- /Leetcode/addnums.py: -------------------------------------------------------------------------------- 1 | # import itertools 2 | # # def best_practice(n:list,target:int): 3 | # # itertools.accumulate 4 | 5 | # nlist = [0,3,2,4,0] 6 | # target = 8 7 | # nlist.sort() 8 | # new_list = [x for x in nlist if x <= target] 9 | # r = itertools.accumulate([1,2,3,4]) 10 | # ri = itertools.combinations(new_list, 2) 11 | # items = [] 12 | # # for i in ri: 13 | # # if i[0] + i[1] == target and i[0] != i[1]: 14 | # # items.append(new_list.index(i[0])) 15 | # # items.append(new_list.index(i[1])) 16 | # # print(items) 17 | # # print("x") 18 | # # elif i[0] == i[1]: 19 | # # items.append(new_list.index(i[0])) 20 | # # ne = new_list.index(i[0]) 21 | # # new_list[ne] = "X" 22 | # # items.append(new_list.index(i[1])) 23 | # # print(items) 24 | 25 | # for i in ri: 26 | # print(i) 27 | 28 | e = [ 29 | 2,5,3 30 | ] 31 | 32 | r = [5,90] 33 | 34 | e.extend(r) 35 | print(e) 36 | if len(e) % 2 != 0: 37 | d = e[len(e) // 2] 38 | print((float(d))) 39 | else: 40 | t = len(e) // 2 41 | ans = (e[t] + e[t-1]) / 2 42 | print(ans) 43 | # print(d) 44 | # print(e) 45 | 46 | # t = len(r) // 2 47 | # print(r[t]) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python_apps --------------------------------------------------------------------------------