├── .gitignore ├── Artificial Intelligence ├── Fast API │ └── README.md └── README.md ├── Assignments ├── Beginner Python │ ├── Assignments-01 │ │ ├── Part 1 - Conditional Statements │ │ │ ├── Conditional Statements Q01.py │ │ │ ├── Conditional Statements Q02.py │ │ │ ├── Conditional Statements Q03.py │ │ │ ├── Conditional Statements Q04.py │ │ │ ├── Conditional Statements Q05.py │ │ │ ├── Conditional Statements Q06.py │ │ │ ├── Conditional Statements Q07.py │ │ │ ├── Conditional Statements Q08.py │ │ │ ├── Conditional Statements Q09.py │ │ │ ├── Conditional Statements Q10.py │ │ │ ├── Conditional Statements Q11.py │ │ │ ├── Conditional Statements Q12.py │ │ │ ├── Conditional Statements Q13.py │ │ │ ├── Conditional Statements Q14.py │ │ │ ├── Conditional Statements Q15.py │ │ │ ├── Conditional Statements Q16.py │ │ │ ├── Conditional Statements Q17.py │ │ │ ├── Conditional Statements Q18.py │ │ │ ├── Conditional Statements Q19.py │ │ │ └── Conditional Statements Q20.py │ │ ├── Part 2 - Loops │ │ │ ├── Loops Q01.py │ │ │ ├── Loops Q02.py │ │ │ ├── Loops Q03.py │ │ │ ├── Loops Q04.py │ │ │ ├── Loops Q05.py │ │ │ ├── Loops Q06.py │ │ │ ├── Loops Q07.py │ │ │ ├── Loops Q08.py │ │ │ ├── Loops Q09-redo.py │ │ │ ├── Loops Q09.py │ │ │ ├── Loops Q10.py │ │ │ ├── Loops Q11.py │ │ │ ├── Loops Q12.py │ │ │ ├── Loops Q13.py │ │ │ ├── Loops Q14.py │ │ │ ├── Loops Q15.py │ │ │ ├── Loops Q16.py │ │ │ ├── Loops Q17.py │ │ │ ├── Loops Q18.py │ │ │ ├── Loops Q19.py │ │ │ └── Loops Q20.py │ │ └── README.md │ ├── Assignments-02 │ │ ├── Advanced Function │ │ │ ├── Q01.py │ │ │ ├── Q02.py │ │ │ ├── Q03.py │ │ │ ├── Q04.py │ │ │ ├── Q05.py │ │ │ └── Q06.py │ │ ├── Basic Function │ │ │ ├── Q01.py │ │ │ ├── Q02.py │ │ │ ├── Q03.py │ │ │ ├── Q04.py │ │ │ ├── Q05.py │ │ │ └── Q06.py │ │ ├── Intermediate Function │ │ │ ├── Q01.py │ │ │ ├── Q02.py │ │ │ ├── Q03.py │ │ │ ├── Q04.py │ │ │ ├── Q05.py │ │ │ └── Q06.py │ │ ├── README.md │ │ └── Real-world Scenarios │ │ │ ├── Q01.py │ │ │ └── Q02.py │ └── Assignments-03 │ │ ├── Advanced Dictionary Usage │ │ ├── Q11.py │ │ ├── Q12.py │ │ ├── Q13.py │ │ ├── Q14.py │ │ └── Q15.py │ │ ├── Applications of Dictionaries │ │ ├── Q20.py │ │ ├── Q21.py │ │ ├── Q22.py │ │ ├── Q23.py │ │ └── Q24.py │ │ ├── Basic Operations │ │ ├── Q01.py │ │ ├── Q02.py │ │ ├── Q03 (Updating Dictionaries).py │ │ ├── Q04.py │ │ └── Q05 (Removing Values from a dictionary).py │ │ ├── Challenging Problems │ │ ├── Q25.py │ │ ├── Q26.py │ │ ├── Q27.py │ │ ├── Q28.py │ │ ├── Q29.py │ │ └── Q30.py │ │ ├── Iterating through Dictionaries │ │ ├── Q06.py │ │ ├── Q07.py │ │ ├── Q08.py │ │ ├── Q09.py │ │ └── Q10.py │ │ ├── Nested Dictionaries │ │ ├── Q16.py │ │ ├── Q17.py │ │ ├── Q18.py │ │ └── Q19.py │ │ ├── README.md │ │ ├── create_files.sh │ │ └── move_files.sh ├── FastAPI Assignments │ └── Assignment _ University Registration Form API │ │ ├── My Solution │ │ └── learn.py │ │ └── README.md ├── README.md └── rename_files.fish ├── Getting Started with Git Uploading Code on Github ├── Day 1 - Intro to Git, Version Control and Github │ └── README.md ├── Day 2 - Making Repository and Uploading Changes, Cloning Repo │ └── README.md └── Day 3 - Personal Access Token │ ├── Assignment No. 2 Create 5 Github Repos │ └── README.md │ └── README.md ├── Leetcode Chronicles and Adventures ├── Missing Number Leetcode 268.py ├── README.md ├── Star-Pattern-Programs-To-Practice-Loops │ ├── Numbered Rectangle.py │ ├── Numbered Reversed Right Angle Triangle.py │ ├── Numbered Right Angle Triangle.py │ ├── Pyramid Star RIght Angled.py │ ├── README.md │ ├── Star Pyramid.py │ └── Star Traingle.py └── fibonacci_series_using_loops.py ├── README.md ├── Setting Up Virtual Enviroments and using Poetry ├── README.md └── README_original_copy.md └── index.html /.gitignore: -------------------------------------------------------------------------------- 1 | # We want to ignore idea file, to ignore files on github from being staged 2 | # We use .gitignore 3 | 4 | .idea/ # this is file created by pycharm we want to ignore this 5 | 6 | -------------------------------------------------------------------------------- /Artificial Intelligence/Fast API/README.md: -------------------------------------------------------------------------------- 1 | 2 | # Running a fastapi server using both virtualenv and poetry (Any Operating System) 3 | 4 | ##### virtualenv 5 | 6 | In case of virtualenv we can use pip to install uvicorn and fastapi i.e. 7 | 8 | ```python3 9 | pip install fastapi 10 | pip install uvicorn 11 | ``` 12 | 13 | ##### poetry 14 | 15 | ```python3 16 | poetry add fastapi 17 | poetry add uvicorn 18 | ``` 19 | 20 | Now to run a fast api server in virtualenv or poetry environment we need to paste this code into any python file in my case the file is called randomcode.py 21 | 22 | ```python3 23 | from fastapi import FastAPI 24 | 25 | # Create an instance of the FastAPI class 26 | app = FastAPI() 27 | 28 | # Define a root route 29 | @app.get("/") 30 | async def read_root(): 31 | return {"message": "hello, world!"} 32 | 33 | if __name__ == "__main__": 34 | import uvicorn 35 | uvicorn.run(app, host="127.0.0.1", port=8000) 36 | ``` 37 | 38 | To simply run this code for fast api we need to run this command in IDE's terminal: 39 | 40 | uvicorn main:app --reload 41 | 42 | As soon as we run this our fastapi server will be up and running at 127.0.0.1 IP which is also known as localhost and the port will be 8000. 43 | For a more detailed approach to understand this code we can check out [KDNuggets](https://www.kdnuggets.com/beginners-guide-to-fastapi) and it is a better approach to follow fastapi's official [documentation](https://fastapi.tiangolo.com/tutorial/first-steps/) as fastapi is well-known for having a good documentation. -------------------------------------------------------------------------------- /Artificial Intelligence/README.md: -------------------------------------------------------------------------------- 1 | ### Begin 2 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q01.py: -------------------------------------------------------------------------------- 1 | # Write a program that checks if a given number is positive, negative, or zero. 2 | 3 | num = float(input("Enter any number:\n")) 4 | 5 | if num > 0: 6 | print(f"{num} is a Postive Number") 7 | elif num < 0: 8 | print(f"{num} is a Negative Number") 9 | else: 10 | print(f"This number is 0") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q02.py: -------------------------------------------------------------------------------- 1 | """ 2 | Take a user’s age as input and display whether they are a minor, 3 | adult, or senior citizen 4 | 5 | https://courtingthelaw.com/2017/12/27/commentary/legal-rights-of-children-under-laws-of-pakistan/ 6 | According to this source age of minor according to law in Pakistan is less than equal to 18 7 | but anyone having a guardian his age should be less than equal to 21 8 | 9 | """ 10 | 11 | age = int(input("Enter Your Age:\n")) 12 | guardian = input("Do you have a guardians other than Parents? (y, n)\n").lower() 13 | 14 | if guardian == 'y': 15 | guardian == True 16 | 17 | 18 | if guardian: 19 | if age <= 21: 20 | print("You are a minor according to some laws") 21 | elif age > 21 and age < 60: 22 | print("You are an adult") 23 | else: 24 | print("Respected Sir you are a Senior Citizen") 25 | else: 26 | if age <=18: 27 | print("You are a minor according to some laws") 28 | elif age >18 and age < 60: 29 | print("You are an adult") 30 | else: 31 | print("Respected Sir you are a Senior Citizen") 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q03.py: -------------------------------------------------------------------------------- 1 | # Write a program that checks if a given year is a leap year. 2 | 3 | # https://airandspace.si.edu/stories/editorial/science-leap-year 4 | # https://www.quora.com/Why-does-a-leap-year-have-to-be-divisible-by-100 5 | 6 | """ 7 | We could do this in any pattern we wanted… but it’s best if we make the pattern as easy 8 | to remember as possible. So we add a leap day to every calendar year that 9 | is evenly divisible by 4… except for century years. 10 | A century year is only a leap year if it is divisible by 400. 11 | """ 12 | 13 | year = input("Enter any Year:\n") 14 | if len(year) > 3: # If user enters something like 200 we will ask him to enter a valid year 15 | year = int(year) 16 | if year % 100 == 0: # this is to filter out century year 17 | if year % 400 == 0: # for a century year to be a leap year it has to be 18 | print(f"{year} is a leap year") # divisible by both 400 and 100 19 | else: 20 | print(f"{year} is not a leap year") 21 | else: 22 | if year % 4 == 0: # a leap year is always divible by 4 23 | print(f"{year} is a leap year") 24 | elif year % 4!= 0 : 25 | print(f"{year} is not a leap year") 26 | else: 27 | print(f"Enter a Valid Year") 28 | 29 | 30 | ''' 31 | These are some leap years we can check the program against: 32 | 1804, 1808, 1812, 1816, 1820, 1824, 1824, 1832, 1836, 1840, 33 | 1844, 1848, 1852, 1856, 1860, 1864, 1868, 1872, 1876, 1880, 34 | 1884, 1888, 1892, 1896, 1904, 1908, 1912, 1916, 1920, 1924, 35 | 1928, 1932, 1936, 1940, 1944, 1948, 1952, 1956, 1960, 1964, 36 | 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1996, 2000, 2004, 37 | 2008, 2012, 2016, 2020, 2024, 2028, 2032, 2036, 2040, 2044, 38 | 2048, 2052, 2056, 2060, 2064, 2068, 2072, 2076, 2080, 2084, 39 | 2088, 2092, 2096 40 | ''' 41 | 42 | # We could improve this code: 43 | 44 | if len(year) > 3: 45 | year = int(year) 46 | if year % 100 == 0 and year % 400 == 0: 47 | print(f"{year} is a leap year") 48 | else: 49 | if year % 4 == 0: 50 | print(f"{year} is a leap year") 51 | elif year % 4!= 0 : 52 | print(f"{year} is not a leap year") 53 | else: 54 | print(f"Enter a Valid Year") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q04.py: -------------------------------------------------------------------------------- 1 | # Take an integer and check if it’s even or odd. 2 | 3 | num = int(input("Enter an integer:\n")) 4 | if num % 2 == 0: 5 | print(f"{num} is an even integer") 6 | else: 7 | print(f"{num} is an odd integer") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q05.py: -------------------------------------------------------------------------------- 1 | ''' Ask the user for a grade percentage and display the corresponding 2 | letter grade (A, B, C, D, F) 3 | 4 | A-Grade Range (80(inclusive) - 100(inclusive)) 5 | B-Grade Range (70(inclusive) - 80(exclusive)) 6 | C-Grade Range (60(inclusive) - 70(exclusive)) 7 | D-Grade Range (50(inclusive) - 60(exclusive)) 8 | Below 50 Fail 9 | ''' 10 | 11 | grade_percentage = float(input("Enter You Grade Percentage:\n")) 12 | grade_percentage = round(grade_percentage) 13 | 14 | if grade_percentage >= 80 and grade_percentage <=100: 15 | print("You scored an A Grade, Congrats!") 16 | elif grade_percentage >= 70 and grade_percentage < 80: 17 | print("You scored a B Grade, There was room for improvement!") 18 | elif grade_percentage >= 60 and grade_percentage <70: 19 | print("You scored an C Grade, Come on Man!") 20 | elif grade_percentage >= 50 and grade_percentage < 60: 21 | print("You scored a D Grade, Goodluck Explaining this to your Parents!") 22 | elif grade_percentage < 50: 23 | print("You have failed, You had one job!") 24 | else: 25 | print("Enter Valid Grade Percentage!!!") 26 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q06.py: -------------------------------------------------------------------------------- 1 | # Write a program to find the largest of two numbers. 2 | 3 | num1 = float(input("Enter First Number:\n")) 4 | num2 = float(input("Enter Second Number:\n")) 5 | if num1 > num2: 6 | print(f"{num1} is greater than {num2}") 7 | elif num2 > num1: 8 | print(f"{num2} is greater than {num1}") 9 | else: 10 | print("The numbers are equal") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q07.py: -------------------------------------------------------------------------------- 1 | # Write a program to find the largest of three numbers. 2 | 3 | num1 = float(input("Enter First Number:\n")) 4 | num2 = float(input("Enter Second Number:\n")) 5 | num3 = float(input("Enter Third Number:\n")) 6 | 7 | if num1 == num2 == num3: 8 | print(f"All the numbers are equal") 9 | elif num1 == num2: 10 | if num3 > num1: 11 | print(f"{num3} is the greatest number") 12 | else: 13 | print("Number-1 and Number-2 are greater") 14 | elif num2 == num3: 15 | if num1 > num2: 16 | print(f"{num1} is the greatest number") 17 | else: 18 | print("Number-2 and Number-3 are greater") 19 | elif num3 == num1: 20 | if num2 > num1: 21 | print(f"{num2} is the greatest number") 22 | else: 23 | print("Number-3 and Number-1 are greater") 24 | else: 25 | # both implementations are essentially the same 26 | # if num2 > num3 > num1: 27 | # print(f"{num2} is the greatest number") 28 | # elif num3 > num2 >num1: 29 | # print(f"{num2} is the greatest number") 30 | # elif num1 > num2 >num3: 31 | # print(f"{num2} is the greatest number") 32 | 33 | if num2 > num3 and num2 > num1: 34 | print(f"{num2} is the greatest number") 35 | elif num3 > num2 and num3 > num1: 36 | print(f"{num3} is the greatest number") 37 | elif num1 > num2 and num1 > num3: 38 | print(f"{num1} is the greatest number") 39 | 40 | 41 | 42 | 43 | 44 | 45 | ''' 46 | We could have taken input from user in a single line using a list 47 | 48 | nums = [] 49 | nums = input("Enter Numbers seperated by comma:\n").split(",") 50 | # but the elements of the list currently are strings ''' -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q08.py: -------------------------------------------------------------------------------- 1 | # Create a program that checks if a given string is a palindrome. 2 | 3 | palindrome = input("Enter any palindrome:\n").lower() 4 | 5 | reverse = palindrome[::-1] 6 | if palindrome == reverse: 7 | print("Yay Man This is a palindrome") 8 | else: 9 | print("This isn't a palindrome") 10 | 11 | 12 | ''' 13 | 14 | Some words we can check against: 15 | Level, Radar, Civic, Noon, Racecar, Refer, Madam, Rotator, Deified, Kayak 16 | ''' -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q09.py: -------------------------------------------------------------------------------- 1 | ''' Take three sides of a triangle as input and check if they form a valid triangle. 2 | The sum of any two sides of a triangle is greater than or equal to the third side 3 | according to Triangle Inequality Theorem from Euclidean geometry. 4 | 5 | https://www.youtube.com/watch?v=BiagrTl2y4o 6 | 7 | To form a valid triangle 8 | all three of the following conditions must be satisfied: 9 | 10 | side1 + side2 > side3 11 | side2 + side3 > side1 12 | side3 + side1 > side2 13 | 14 | For example: 15 | 16 | 3 + 4 > 5 17 | 4 + 5 > 3 18 | 3 + 5 > 4 19 | ''' 20 | 21 | 22 | side1 = input("Enter Side1 Length:\n") 23 | side2 = input("Enter Side2 Length:\n") 24 | side3 = input("Enter Side3 Length:\n") 25 | 26 | side1, side2, side3 = float(side1), float(side2), float(side3) 27 | 28 | if side1 + side2 > side3 and side2 + side3 > side1 and side1 + side3 > side2: 29 | print("This is a valid Triangle") 30 | else: 31 | print("According to Triangle Inequality Theorem\nThis wouldn't be a valid triangle") 32 | 33 | ''' We could also nest this condition i.e. 34 | The above code block and this one that I commented are the same 35 | if side1 + side2 > side3: 36 | if side2 + side3 > side1: 37 | if side1 + side3 > side2: 38 | print("This is a valid Triangle") 39 | else: 40 | print("According to Triangle Inequality Theorem\nThis wouldn't be a valid triangle") 41 | ''' -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q10.py: -------------------------------------------------------------------------------- 1 | # Write a program to determine if a given character is a vowel or consonant. 2 | # A consonant is a speech sound that is not a vowel. 3 | 4 | char = input("Enter any character:\n") 5 | 6 | if char == 'a' or 'e' or 'i' or 'o' or 'u': 7 | print(f"{char} is a vowel.") 8 | else: 9 | print(f"{char} is a consonant.") 10 | 11 | # We could also check this like this: 12 | 13 | # vowels = 'aeiou' 14 | # if char in vowels: 15 | # print(f"{char} is a vowel.") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q11.py: -------------------------------------------------------------------------------- 1 | # Check if a given number is a multiple of both 3 and 5. 2 | 3 | num = int(input("Enter Any Number:\n")) 4 | if num % 3 == 0 and num % 5 == 0: 5 | print(f"{num} is a multiple of 3 and 5") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q12.py: -------------------------------------------------------------------------------- 1 | """ Write a program that takes a temperature in Celsius and checks 2 | if it’s freezing, moderate, or hot. 3 | According to Appalachian State University Water freezes at 0°C 4 | So tempratures below 0 are freezing 5 | https://www.appstate.edu/~goodmanjm/rcoe/asuscienceed/six6energytransfer/temperature.html 6 | 7 | Tempratures above 35 are hot 8 | and tempratures between 20 and 35 can be considered moderate 9 | whereas tempratures 5 and 20 can be considered chilly 10 | """ 11 | 12 | temprature = int(input("Enter Temprature in Celcius:\n")) 13 | if temprature < 5: 14 | print("It's Freezing") 15 | elif temprature > 5 and temprature <=20: 16 | print("It's Chilly") 17 | elif temprature >= 20 and temprature <=35: 18 | print("It's moderate") 19 | else: 20 | print("It's pretty hot") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q13.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Take two numbers and an operator (+, -, *, /) as input and perform 3 | the corresponding operation. ''' 4 | 5 | num1 = float(input("Enter 1st Number:\n")) 6 | num2 = float(input("Enter 2nd Number:\n")) 7 | print("\n") 8 | 9 | print("What do you want to do with these numbers:\nEnter +, -, * or / only:\t") 10 | operation = input("\n") 11 | 12 | if operation == '+': 13 | print(f"sum = {num1 + num2}") 14 | elif operation == '-': 15 | print(f"difference = {num1 - num2}") 16 | elif operation == '/': 17 | print(f"division = {num1 / num2}") 18 | elif operation == '*': 19 | print(f"product = {num1 * num2}") 20 | else: 21 | print(f"Enter a valid symbol\nYou entered: {operation}") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q14.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Check if a year input by the user is a century year. 3 | A number can be a century year if it is 100% divisible by 100 4 | and a year has to be in thousands i.e. 2000 5 | Make sure user isn't able to enter something like 200 or 300 ''' 6 | 7 | year = int(input("Enter any year:\n")) 8 | 9 | if year >= 1000: 10 | if year % 100 == 0: 11 | print(f"{year} is a century year.") 12 | else: 13 | print("No {year} isn't a century year.") 14 | else: 15 | print("Enter a Valid Year") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q15.py: -------------------------------------------------------------------------------- 1 | # Write a program to check if a number is within a specified range. 2 | 3 | 4 | print("Specify a range", "Enter a minimum value and a maximum value when asked:\n") 5 | 6 | minimum = int(input("Enter Minimum Number:\n")) 7 | maximum = int(input("Enter Maximum Number:\n")) 8 | num = int(input("Enter a number:\n")) 9 | 10 | 11 | if minimum > maximum: 12 | print("The maximum needs to be larger than minimum.") 13 | elif num >= minimum and num <= maximum: 14 | print(f"Yes {num} is in the specified range.") 15 | elif minimum == maximum: 16 | print("There can be no integer within this range.") 17 | 18 | ''' A very different logic could have been: 19 | range() in python is just like a sequence of numbers of range object 20 | So when we check if this number is in the range it returns True if 21 | The number is actually there 22 | 23 | elif num in range(minimum, maximum): 24 | print(f"Yes {num} is in the specified range.") ''' -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q16.py: -------------------------------------------------------------------------------- 1 | # Take the length of three sides and classify the triangle 2 | ''' (equilateral, isosceles, or scalene). 3 | In case of Equilateral Triangle all sides must be equal 4 | For Isosceles any two sides must be equal 5 | For Scalene no need for any equal side. 6 | 7 | ''' 8 | 9 | length1 = int(input("Enter Side 1 Length:\n")) 10 | length2 = int(input("Enter Side 2 Length:\n")) 11 | length3 = int(input("Enter Side 3 Length:\n")) 12 | 13 | if length1 == length2 == length3: 14 | print("This is an Equilateral Traingle.") 15 | elif length1 == length2 or length2 == length3 or length3 == length1: 16 | print("This is an Isosceles Triangle.") 17 | else: 18 | print("This is a Scalene Triangle") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q17.py: -------------------------------------------------------------------------------- 1 | # Write a program that asks for an integer and checks 2 | # if it’s divisible by 2, 3, or both. 3 | 4 | num = int(input("Enter a number:\n")) 5 | 6 | if num % 2 == 0 or num % 3 == 0: 7 | if num % 2 == 0 and num % 3 == 0: 8 | print(f"{num} is divisible by both 2 and 3.") 9 | elif num % 2 == 0 and num % 3 != 0: 10 | print(f"{num} is divisible by 2 only.") 11 | else: 12 | print(f"{num} is divisble by 3 only.") 13 | else: 14 | print(f"{num} isn't divisble by either of the numbers.") 15 | 16 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q18.py: -------------------------------------------------------------------------------- 1 | # Take a user’s score and determine if they pass or fail (pass if 50 or above). 2 | 3 | score = float(input("Enter Your Score:\n")) 4 | if score < 50: 5 | print("You have failed.") 6 | elif score >= 50 and score < 101: 7 | print("You have passed.") 8 | elif score >=100: 9 | print("Score is between 1-100. Enter Again") 10 | 11 | # If we don't limit the second elif then even if we enter 101 second conditional is hit 12 | # which it shouldn't so limiting is a good idea -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q19.py: -------------------------------------------------------------------------------- 1 | # Check if a string input is uppercase, lowercase, or a mix. 2 | 3 | string = input("Enter a string:\n") 4 | if string.islower() == True: 5 | print(f"'{string}' is in lowercase.") 6 | elif string.isupper() == True: 7 | print(f"'{string}' is in uppercase.") 8 | else: 9 | print(f"'{string}' is a mixed string.") 10 | 11 | ''' 12 | isupper() and islower() are built-in python string functions that return True or False. 13 | If all alphabets in the string are uppercase the isupper() will return True. 14 | If all alphabets in the string are lowercase the islower() will return True. 15 | If neither of these conditions are met this means that the string is a mixed one. 16 | ''' -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 1 - Conditional Statements/Conditional Statements Q20.py: -------------------------------------------------------------------------------- 1 | # Create a program that evaluates if an inputted number is prime. 2 | 3 | num = int(input("Enter Any Number:\n")) 4 | 5 | if num % 2 == 0 or num % 3 == 0 or num % 5 == 0 or num % 7 == 0 or num % 11 == 0 or num % 13 == 0: 6 | if num == 2 or num == 3 or num == 5 or num == 7 or num == 11 or num == 11 or num == 13: 7 | print(f"{num} is a prime number.") 8 | else: 9 | print(f"{num} is not a prime number.") 10 | else: 11 | print(f"{num} is a prime number.") 12 | 13 | 14 | ''' 15 | These are some prime numbers we can check the code against: 16 | 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 17 | 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 18 | 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 19 | 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 20 | 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293. 21 | From: https://byjus.com/maths/prime-numbers-from-1-to-1000/ 22 | 23 | It's ovbious that for the code to be accurate we would need a for loop 24 | But for prime numbers between 1-300 this code works just fine 25 | ''' -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q01.py: -------------------------------------------------------------------------------- 1 | # Print numbers from 1 to 20 using a for loop. 2 | 3 | for num in range(1, 21): 4 | print(num, end=" ") 5 | 6 | ''' 7 | This is the full syntax of print function: 8 | print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) 9 | Meaing we can pass any number of strings or even variables, by default sep = ' ' 10 | and end='\n' if we don't write/specify behaviour of these parameters the print function 11 | automatically adds a space after each string and adds \n after each time the print 12 | statement fully runs. We can overide this by specifiying a value to both or just one of 13 | these parameters. 14 | Default syntax of range function: 15 | range(start, stop, step) 16 | By default the value of start is 0 and step is 1. The range will never provide a 17 | sequence if we do not give an end value. start and stop are optional parameters but in code 18 | I have given value to start so the sequence starts from 1 instead of 0 19 | Also start is inclusive and end is exclusive meaning the range stops 1 before the given end. 20 | i.e. if we wanted range to end on 20 we would need to give 21. 21 | ''' -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q02.py: -------------------------------------------------------------------------------- 1 | # Use a while loop to print even numbers from 1 to 50. 2 | 3 | num = 1 4 | while num < 51: 5 | if num % 2 == 0: 6 | print(num) 7 | num += 1 8 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q03.py: -------------------------------------------------------------------------------- 1 | # Write a program to calculate the sum of all numbers between 1 and 100. 2 | # By between here we mean from 2 to 99 3 | 4 | counter = 2 5 | sum = 0 6 | 7 | while counter < 100: 8 | sum += counter 9 | counter += 1 10 | print(sum) 11 | 12 | # counter is iterating over numbers i.e. 2, 3, 4, 5 ..... 99 13 | # sum is adding previous value with current count value 14 | # i.e. for 1st iteration sum = 0 + 2, then for 2nd iteration 15 | # sum = 2 + 3, then for 3rd iteration sum = 5 + 4 16 | # here the second value is the counter value and the first one 17 | # being added is the previous value stored in some value -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q04.py: -------------------------------------------------------------------------------- 1 | # Print the multiplication table of a given number. 2 | 3 | num = int(input("Enter Number you want a table for:\n")) 4 | 5 | if num > 1: 6 | counter = 1 7 | while counter != 11: # as soon as counter reaches 11 and loop will break 8 | print(f"{num} x {counter} = {num * counter}") 9 | counter += 1 -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q05.py: -------------------------------------------------------------------------------- 1 | # Print all odd numbers between 1 and 100 using a loop. 2 | 3 | num = 1 4 | while num < 101: 5 | if num % 2 != 0: 6 | print(num, end=" ") 7 | num += 1 8 | 9 | ''' 10 | It seems we can also get odd numbers by adding 2 to the previous ones 11 | we can do that using this logic: 12 | ''' 13 | 14 | # counter = 1 15 | # while counter < 101: 16 | # print(counter, end=" ") 17 | # counter += 2 -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q06.py: -------------------------------------------------------------------------------- 1 | # Use a for loop to print each character of a string. 2 | string = input("Enter any string:\n") 3 | 4 | for char in string: 5 | print(char) 6 | 7 | ''' 8 | We can also achieve this using while loop like this: 9 | runs = 0 10 | while runs != len(string): 11 | print(string[runs]) 12 | runs += 1 13 | ''' -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q07.py: -------------------------------------------------------------------------------- 1 | # Find the factorial of a number using a while loop. 2 | 3 | num = int(input("Enter Any Number:\n")) 4 | 5 | counter = 2 # starting from 2 so multiplying actually starts from 2 instead of 1 6 | fact = 1 7 | while counter < num + 1: # for example user entered 5, this will multiply like 1 x 2 x 3 x 4 x 5 which is 120 8 | fact *= counter 9 | counter += 1 10 | 11 | print(f"The factorial is: {fact}") 12 | 13 | 14 | 15 | ''' 16 | Here's how we can achieve the same thing iterating reversely i.e. 5, 4, 3, 2, 1... 17 | 18 | factu = 1 19 | count = num -1 20 | while count > 1: 21 | factu *= count 22 | count -= 1 23 | 24 | print(f"The factorial is: {factu*num}") 25 | Such Code must always be dry-run 26 | ''' 27 | 28 | 29 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q08.py: -------------------------------------------------------------------------------- 1 | # Use a for loop to print numbers from 10 down to 1. 2 | 3 | for num in range(10, 0, -1): 4 | print(num) 5 | 6 | # remember end is exclusive therefore to end at 1 we wrote 0 7 | # step = -1 means go in reverse order 8 | # end = 0 means end 1 before 0 i.e. at 1 -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q09-redo.py: -------------------------------------------------------------------------------- 1 | ''' 0 1 1 2 3 5 8 13 21 34 55 2 | Some People say that Fibonacci Series starts with 0 and some say it starts with 1. 3 | We are going to start it with 1 4 | Each Next number is the sum of previous/preceding 2 numbers 5 | In this implementation I am using for loop to print fibonacci series 6 | there is no need to use list but i am using it so we actually see how varaible sum is being created 7 | in each iteration. 8 | ''' 9 | 10 | a, b = 0, 1 11 | for i in range(9): 12 | sum = a + b # 1 2 3 5 8 13 21 34 55 13 | a = b # 1 1 2 3 5 8 13 21 34 14 | print(a, end=" ") # 1 1 2 3 5 8 13 21 34 55 15 | b = sum 16 | 17 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q09.py: -------------------------------------------------------------------------------- 1 | # Write a program to print the first 10 Fibonacci numbers. 2 | # these are the first 10: 3 | # 1 1 2 3 5 8 13 21 34 55 4 | 5 | li = [1, 1] 6 | 7 | count = 0 8 | for num in range(1, 9): 9 | li.append(li[count]+li[num]) 10 | count += 1 11 | 12 | ''' 13 | We used list so we don't have to make logic up for the first two ones we already have 14 | in the list. List datastructure is used because it has functions such as append or insert 15 | to insert values being created by for loop 16 | List values can be changed in place 17 | ''' -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q10.py: -------------------------------------------------------------------------------- 1 | # Use a loop to count the number of digits in an integer. 2 | 3 | nums = int(input("Enter any integer:\n")) 4 | 5 | counter = 0 6 | for num in str(nums): # for example number is 123 7 | counter+=1 # num = 1 in first iteration and counter is incremented to 1 8 | print(counter) # then counter is incremented to 2 when num = 2 9 | # then counter is incremented to 3 when num = 3 10 | 11 | # This could be done in easier way using built-in python functions i.e. 12 | # print(len(str(nums))) 13 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q11.py: -------------------------------------------------------------------------------- 1 | # Print the reverse of a given number. 2 | 3 | number = int(input("Enter a number:\n")) 4 | 5 | for num in str(number)[::-1]: 6 | print(num, end="") 7 | 8 | 9 | ''' 10 | We can also do this without a loop 11 | print(str(number)[::-1]) 12 | ''' 13 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q12.py: -------------------------------------------------------------------------------- 1 | # Print all prime numbers between 1 and 50. 2 | ''' 3 | A prime number has only 2 factors 4 | Whereas a non prime number has more than 2 factors 5 | ''' 6 | 7 | factors = [] 8 | 9 | number = int(input("Enter any integer:\n")) 10 | 11 | for elem in range(1, number + 1): 12 | if number % elem == 0: 13 | factors.append(elem) 14 | 15 | if len(factors) == 2: 16 | print(f"{number} is a prime number.") 17 | else: 18 | print(f"{number} is not a prime number.") 19 | 20 | # We can also do this without a list using a counter 21 | 22 | ''' 23 | number = int(input("Enter any integer:\n")) 24 | counter = 0 25 | for elem in range(1, number + 1): 26 | if number % elem == 0: 27 | counter += 1 28 | 29 | if counter == 2: 30 | print(f"{number} is a prime number.") 31 | else: 32 | print(f"{number} is not a prime number.") 33 | ''' -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q13.py: -------------------------------------------------------------------------------- 1 | """ 2 | * 3 | *** 4 | ***** 5 | ******* 6 | Question: Use nested loops to print a pyramid pattern of *. 7 | 3 spaces at start and 3 after the first star, we need to print 1 star 8 | 2 spaces at the start for 2nd row of stars, we need to print 3 stars 9 | 1 space at the start for 3rd row, we need to print 5 stars 10 | no space in the last row, we need to print 7 stars 11 | Here we printed without use of nested loop 12 | """ 13 | 14 | space_count = 3 # in each row number of spaces are getting reduced that's why we need this variable 15 | num = 0 # in each row the number of star is increasing by two from the previous one 16 | 17 | for row in range(1, 5): # We need 4 rows so we run this 4 times 18 | spaces = ' ' * space_count # a new string of spaces is made each time loop restarts 19 | print(spaces, end="") # in the first iteration 3 spaces are added to the start of stars 20 | # and then the end doesn't take the flow to the next line 21 | # instead the * in next line of code will start printing from spaces 22 | print('*' * (row + num)) # in first iteration row = 1 and num = 0 so * is printed 1 time 23 | # in the second iteration row = 2 and num = 1, 2 + 1 = 3 so 3 * are printed 24 | num += 1 # after each print statement value of num increases by 1 25 | space_count -= 1 # after each print statement value of space_count decreases by 1 26 | print() 27 | # Using Nested Loops 28 | 29 | space_count = 3 # we made this to keep track of spaces 30 | count = 0 # this is made to keep track of the extra * in each row for example 31 | # if row = 2, * is printed two times we add required number of *, it keeps on increasing 32 | for row in range(1, 5): 33 | for col in range(0,4): 34 | spaces = ' ' * space_count 35 | print(spaces, end='') 36 | print(('*' * row) + ('*' * count) , end="\n") 37 | count += 1 38 | break 39 | space_count -= 1 40 | print() 41 | 42 | # better nested logic 43 | # but still we aren't using an internal loop like an internal loop 44 | 45 | space_count = 3 # there are 3 spaces at start, this keeps decrementing 46 | spaces = space_count * ' ' # but we later inside the for loop don't use it 47 | # we re allocate a new variable using if condition 48 | for row in range(1, 8, 2):# this stores 1, 3, 5, 7 respectively in row variable 49 | for col in range(1): # the internal loop will always run 1 time per row i.e. if row = 3, 3 x 1 50 | if row == 1: 51 | spaces = ' ' * 3 # spaces keep on decrementing per row 52 | elif row == 3: 53 | spaces = ' ' * 2 54 | elif row == 5: 55 | spaces = ' ' * 1 56 | elif row == 7: 57 | spaces = ' ' * 0 58 | print(spaces, end="") 59 | print('*' * row, end="") 60 | print() # after each set of '*' patterns print along with current space, then we shift to new line 61 | 62 | print() 63 | 64 | # this is the best logic because it uses separate loop for spaces and separate for * 65 | spaces = 3 66 | for row in range(1, 8, 2): # 1 3 5 7 67 | 68 | # loop for spaces 69 | for space in range(spaces): 70 | print(" ", end="") 71 | spaces -= 1 72 | 73 | # loop for * pattern 74 | for _ in range(row): # will iterate run 0 to 4 times fetching values 1 3 5 7 75 | # as it's an internal loop it will run them times the value in row variable 76 | print("*", end="") # after each run we override end argument so that flow doesn't go to next line 77 | 78 | print() # to take flow to next line 79 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q14.py: -------------------------------------------------------------------------------- 1 | # Write a program that breaks the loop when a certain condition is met. 2 | 3 | for num in range(1, 11): 4 | if num == 5: 5 | break 6 | print(num) -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q15.py: -------------------------------------------------------------------------------- 1 | # Print the sum of even and odd numbers separately up to a given number. 2 | 3 | num = int(input("Enter a number:\n")) 4 | sum_even = 0 5 | sum_odd = 0 6 | 7 | print("\n") 8 | for number in range(1, num): 9 | if number % 2 == 0: 10 | sum_even += number 11 | elif number % 2 != 0: 12 | sum_odd += number 13 | print("\n") 14 | print(f"Even Number Sum is: {sum_even}") 15 | print(f"Odd Number Sum is: {sum_odd}") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q16.py: -------------------------------------------------------------------------------- 1 | # Create a program to calculate the sum of the digits of an inputted integer. 2 | 3 | nums = int(input("Enter a number:\n")) 4 | 5 | sum = 0 6 | for num in str(nums): 7 | sum += int(num) 8 | print(f"The sum is: {sum}") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q17.py: -------------------------------------------------------------------------------- 1 | # Write a program that continues to ask for a number until 2 | # the correct number is guessed. 3 | 4 | nums = '173942006000' 5 | print("Guess a number, a single digit or multi-digit one:") 6 | guess = input() 7 | 8 | condition = True 9 | while condition == True: 10 | if guess not in nums: 11 | print("You guessed it wrong, guess again") 12 | guess = input() 13 | elif guess in nums: 14 | print("You guessed it—great!") 15 | condition = False -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q18.py: -------------------------------------------------------------------------------- 1 | # Use a loop to print numbers in reverse order within a given range. 2 | 3 | print("We want to print the given number in reverse order") 4 | 5 | 6 | number = int(input("Enter a number:\n")) 7 | start = int(input("Enter The Value you want to start range from:\n")) 8 | end = int(input("Enter The Value you want to end range on:\n")) 9 | 10 | for num in str(number)[start:end:-1]: 11 | print(num, end="") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q19.py: -------------------------------------------------------------------------------- 1 | # Use a for loop to print the square of each number from 1 to 10. 2 | 3 | for num in range(1, 11): 4 | print(num * num) -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/Part 2 - Loops/Loops Q20.py: -------------------------------------------------------------------------------- 1 | # Create a program that simulates a countdown timer 2 | # starting from a given number down to zero. 3 | 4 | num = int(input("Enter a starting number:\n")) 5 | end = 1 6 | for num in range(num, end, -1): 7 | print(num) 8 | 9 | # Try starting the counter with something like 1000000 -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-01/README.md: -------------------------------------------------------------------------------- 1 | # Part 1: Conditional Statements (20 Questions) 2 | 3 | 1. **Write a program that checks if a given number is positive, negative, or zero.** 4 | 2. **Take a user’s age as input and display whether they are a minor, adult, or senior citizen.** 5 | 3. **Write a program that checks if a given year is a leap year.** 6 | 4. **Take an integer and check if it’s even or odd.** 7 | 5. **Ask the user for a grade percentage and display the corresponding letter grade (A, B, C, D, F).** 8 | 6. **Write a program to find the largest of two numbers.** 9 | 7. **Write a program to find the largest of three numbers.** 10 | 8. **Create a program that checks if a given string is a palindrome.** 11 | 9. **Take three sides of a triangle as input and check if they form a valid triangle.** 12 | 10. **Write a program to determine if a given character is a vowel or consonant.** 13 | 11. **Check if a given number is a multiple of both 3 and 5.** 14 | 12. **Write a program that takes a temperature in Celsius and checks if it’s freezing, moderate, or hot.** 15 | 13. **Take two numbers and an operator (+, -, x, /) as input and perform the corresponding operation.** 16 | 14. **Check if a year input by the user is a century year.** 17 | 15. **Write a program to check if a number is within a specified range.** 18 | 16. **Take the length of three sides and classify the triangle (equilateral, isosceles, or scalene).** 19 | 17. **Write a program that asks for an integer and checks if it’s divisible by 2, 3, or both.** 20 | 18. **Take a user’s score and determine if they pass or fail (pass if 50 or above).** 21 | 19. **Check if a string input is uppercase, lowercase, or a mix.** 22 | 20. **Create a program that evaluates if an inputted number is prime.** 23 | 24 | --- 25 | 26 | # Part 2: Loops (20 Questions) 27 | 28 | 1. **Print numbers from 1 to 20 using a for loop.** 29 | 2. **Use a while loop to print even numbers from 1 to 50.** 30 | 3. **Write a program to calculate the sum of all numbers between 1 and 100.** 31 | 4. **Print the multiplication table of a given number.** 32 | 5. **Print all odd numbers between 1 and 100 using a loop.** 33 | 6. **Use a for loop to print each character of a string.** 34 | 7. **Find the factorial of a number using a while loop.** 35 | 8. **Use a for loop to print numbers from 10 down to 1.** 36 | 9. **Write a program to print the first 10 Fibonacci numbers.** 37 | 10. **Use a loop to count the number of digits in an integer.** 38 | 11. **Print the reverse of a given number.** 39 | 12. **Print all prime numbers between 1 and 50.** 40 | 13. **Use nested loops to print a pyramid pattern of `*`.** 41 | 14. **Write a program that breaks the loop when a certain condition is met.** 42 | 15. **Print the sum of even and odd numbers separately up to a given number.** 43 | 16. **Create a program to calculate the sum of the digits of an inputted integer.** 44 | 17. **Write a program that continues to ask for a number until the correct number is guessed.** 45 | 18. **Use a loop to print numbers in reverse order within a given range.** 46 | 19. **Use a for loop to print the square of each number from 1 to 10.** 47 | 20. **Create a program that simulates a countdown timer starting from a given number down to zero.** 48 | 49 | # Fibonacci Series Question i.e. Q9 is the most interesting question in this series a must if you want to get good at Leetcode: 50 | 51 | ![](https://i.imgur.com/UkbfjeT.png) 52 | 53 | 54 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Advanced Function/Q01.py: -------------------------------------------------------------------------------- 1 | # Write a function that calculates the power of a number without using the ** operator. 2 | 3 | def calculate_power(): 4 | num = int(input("Enter a number:\t")) 5 | print() 6 | power = int(input("Enter a number:\t")) 7 | print() 8 | result = 1 9 | 10 | for _ in range(1, power + 1): 11 | result *= num 12 | print(f"{num}^{power} = {result}") 13 | 14 | calculate_power() 15 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Advanced Function/Q02.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function that converts a given temperature from Celsius to Fahrenheit and vice versa. 3 | Fahrenheit = Celsius × 1.8 + 32 according to www.rapidtables.com/convert/temperature/celsius-to-fahrenheit.html 4 | Celsius = (Fahrenheit - 32) / 1.8 5 | 0 °F = -17.77778 °C 6 | 0 °C = 32 °F 7 | """ 8 | temperature = float(input("Enter Temperature:\n")) 9 | 10 | def convert_celsius(temp: float): 11 | """ 12 | If temperature is entered here it means it's currently in fahrenheit and we need to convert it to celsius 13 | """ 14 | if temp == 0: 15 | return -17.77778 # 0 °F = -17.77778 °C 16 | else: 17 | celsius = (temp - 32) / 1.8 18 | return celsius 19 | 20 | def convert_fahrenheit(temp: float): 21 | """ 22 | If temperature is entered here it means it's currently in celsius and we need to convert it to fahrenheit 23 | """ 24 | if temp == 0: 25 | return 32 # 0 °C = 32 °F 26 | else: 27 | fahrenheit = temp * 1.8 + 32 28 | return fahrenheit 29 | 30 | choice = input("Enter c for convert temperature to celsius and f to convert temperature to Fahrenheit:\n").lower() 31 | if choice == 'c': 32 | print(f"The temperature in Celsius is {convert_celsius(temperature)}°C") 33 | elif choice == 'f': 34 | print(f"The temperature in Celsius is {convert_fahrenheit(temperature)}°F") 35 | else: 36 | print("Invalid Choice Try Again") 37 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Advanced Function/Q03.py: -------------------------------------------------------------------------------- 1 | """ 2 | Flattening a list of lists is a process of transforming a two-Dimensional list into a One-Dimensional 3 | list by un-nesting every list element kept in the list of lists, that is, transforming 4 | [[9, 8, 7], [6, 5, 4], [3, 2, 1]] to [9, 8, 7, 6, 5, 4, 3, 2, 1]. 5 | According to www.javatpoint.com/flatten-list-in-python 6 | Write a function to flatten a nested list. 7 | """ 8 | from build.lib.setuptools.namespaces import flatten 9 | 10 | a_list = [[10, 20, 30, 40], [50, 60, 70], [80, 90]] 11 | ''' 12 | Some more lists we can check this against: 13 | [[9, 8, 7], [6, 5, 4], [3, 2, 1]] 14 | [[10, 20, 30, 40], [50, 60, 70], [80, 90, 100]] 15 | [[10, 20, 30, 40], [50, 60, 70], [80, 90]] 16 | ''' 17 | 18 | def flatten_li(nums): 19 | flattened_li = [] 20 | for li_elem in a_list: 21 | for elem in li_elem: 22 | flattened_li.append(elem) 23 | return flattened_li 24 | 25 | # This can also be done using a list comprehension 26 | 27 | print(f"The flattened list is {flatten_li(a_list)}") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Advanced Function/Q04.py: -------------------------------------------------------------------------------- 1 | """ Create a function to check if two strings are anagrams. 2 | An anagram is a word or phrase formed by rearranging the letters of another word or phrase, 3 | using all the original letters exactly once. 4 | For example, the word 'listen' can be rearranged to form the word 'silent'. 5 | """ 6 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Advanced Function/Q05.py: -------------------------------------------------------------------------------- 1 | # Write a function that takes a list and removes all duplicate elements. 2 | 3 | nums = input("Enter numbers separated by comma:\n").split(",") 4 | nums = [int(num) for num in nums] 5 | def remove_duplicates(numbers): 6 | a_set = {nums[0]} # had to add a number to make the dictionary a set 7 | for num in numbers: 8 | a_set.add(num) 9 | 10 | return a_set 11 | 12 | non_duplicates = remove_duplicates(nums) 13 | 14 | # There is another way of doing this we could also have a used a dictionary 15 | # and make the keys the same as values, a python dictionary does not accept 16 | # duplicate keys so only 1 instance of a number in a list would have been kept 17 | print(non_duplicates) 18 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Advanced Function/Q06.py: -------------------------------------------------------------------------------- 1 | # Create a function that takes a string and counts the frequency of each character. 2 | # we are using python's builtin function list.count to count instances of a character in list 3 | 4 | word = input("Enter a string:\n").lower() 5 | char_counts = {} 6 | def count_characters(word): 7 | for char in word: 8 | char_counts[char] = word.count(char) 9 | return char_counts 10 | 11 | character_instances = count_characters(word) 12 | for character, frequency in character_instances.items(): 13 | print(f"{character} appeared {frequency} time(s) in String") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Basic Function/Q01.py: -------------------------------------------------------------------------------- 1 | # Write a function to calculate the area of a circle given its radius. 2 | rad = float(input("Enter Radius:\n")) 3 | def area_circle(radius): 4 | pi = 3.14 5 | area = radius * pi 6 | return area 7 | 8 | print(area_circle(3)) -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Basic Function/Q02.py: -------------------------------------------------------------------------------- 1 | # Create a function that takes two numbers and returns their sum. 2 | 3 | def add(num1, num2): 4 | num1, num2 = float(num1), float(num2) 5 | return num1 + num2 6 | 7 | number1 = input("Enter Num1:\n") 8 | number2 = input("Enter Num2:\n") 9 | 10 | print(f"Sum is {add(number1, number2)}") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Basic Function/Q03.py: -------------------------------------------------------------------------------- 1 | # Write a function to find the factorial of a number using recursion. 2 | num = int(input("enter num:\n")) 3 | 4 | ''' Equivalent Loop Structure 5 | fact = num 6 | for i in range(num - 1, 1, -1): 7 | fact *= i 8 | ''' 9 | 10 | def rec_fact(number): 11 | if number == 1: 12 | return 1 13 | 14 | return number * rec_fact(number - 1) 15 | 16 | print(rec_fact(num)) -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Basic Function/Q04.py: -------------------------------------------------------------------------------- 1 | # Write a function that takes a string and returns it reversed. 2 | 3 | word = input("Enter any string:\n") 4 | 5 | reversed_word = "" # global variable 6 | def reverse_word(string): 7 | global reversed_word # this helps change value of variable outside the scope of this function 8 | for i in range(1, len(string) + 1): 9 | # here the loops is traversing in reverse fashion 10 | # for example the user enter the string word, the last element 11 | # of the string has index of -1, then comes -2, then -3 and the first one from negative indexing is -4 12 | # so we are using negative indexing to reverse the string 13 | # and concatenating the empty string called reversed_word 14 | reversed_word += word[-i] 15 | 16 | return reversed_word 17 | 18 | print(f"The word reversed is {reverse_word(word)}") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Basic Function/Q05.py: -------------------------------------------------------------------------------- 1 | # Create a function to check if a given number is prime. 2 | 3 | import math # importing to use sqrt 4 | 5 | primes = [] 6 | def value_has_decimal(value): 7 | after_decimal, number = math.modf(value) # the functions returns both decimal value and number separately 8 | # if after_decimal = 0.2243000000000004 ceil will convert it to 1 9 | if after_decimal > 0: # for example (0.35, 5) 10 | number = math.ceil(number) 11 | return after_decimal, number 12 | else: 13 | return after_decimal 14 | 15 | def is_prime(num: int) -> str: 16 | check = '' 17 | if num <= 1: 18 | return f"{num} is not a prime." 19 | elif num == 2 or num == 3: 20 | return f"{num} is a prime." 21 | elif num > 3: 22 | num_sqrt = math.sqrt(num) # 11 23 | upper_range = math.ceil(num_sqrt) # 4 24 | if value_has_decimal(num_sqrt) == 0: 25 | return f"{num} is not a prime." 26 | lower_range = value_has_decimal(num_sqrt)[1] 27 | for i in range(upper_range, 1, -1): 28 | if num % i == 0: 29 | check = 0 30 | break 31 | if check == 0: 32 | return f"{num} is not prime number" 33 | else: 34 | primes.append(num) 35 | return f"{num} is a prime number" 36 | 37 | print(is_prime(num := int(input("Enter a number:\n")))) 38 | # here we are using a walrus operator that will input and feed it to is_prime function -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Basic Function/Q06.py: -------------------------------------------------------------------------------- 1 | """ Write a function to count the vowels in a given string. 2 | these are vowels: a, e, i, o, u """ 3 | 4 | vowels_in_each_word = {} 5 | sentence = input("Enter A Sentence:\n").split(" ") # this splitting a sentence string if a space occurs, each word is then stored into a list 6 | # so sentence is essentially a list now 7 | def is_vowel(user_input_sentence): 8 | 9 | vowels = ('a', 'e', 'i', 'o', 'u') 10 | for word_num in range(len(user_input_sentence)): # this is give us each word in the list sentence (a list is being passed) 11 | vowel_ch = "" # this is an empty string each time after the nested for loop runs it again becomes empty 12 | for ch in user_input_sentence[word_num]: # this is a nested for loop extracting each character of each word inside the list 13 | if ch in vowels: # if character is in the list vowels then the if statement is hit 14 | vowel_ch += ch # every time while the characters from a single word are traversed the character 15 | # that is in the vowels list is appended to vowel_ch list 16 | # If a word like Banana comes the vowel_ch string will store the first a, then the second 17 | # a and then the third a i.e. vowel_ch will look like aaa 18 | vowels_in_each_word[word_num] = vowel_ch # The variable 'aaa' will be stored in a global dictionary 19 | # The key represents the position of the word in the current sentence, starting at 0 20 | # For example, the dictionary would have an entry like {0: 'aaa'} 21 | 22 | 23 | show_vowels(sentence) # here we are calling another function, after first function's work is done the second one is being called 24 | # we are also passing the exact sentence that is_vowel has 25 | # if we call show_vowels inside any for loop it will call be called after each vowel is appended to the dictionary 26 | # this isn't required but we can see that here a function can be used exactly like a variable 27 | # let's say we call show_vowels() inside the if in nested loop a user enters the word like Procrastinate 28 | # Then something like this will happen: 29 | # The word "Procrastinate" has 1 vowel(s) which is/are: o 30 | # The word "Procrastinate" has 2 vowel(s) which is/are: oa 31 | # The word "Procrastinate" has 3 vowel(s) which is/are: oai 32 | # The word "Procrastinate" has 4 vowel(s) which is/are: oaia 33 | # The word "Procrastinate" has 5 vowel(s) which is/are: oaiae 34 | def show_vowels(user_input_sentence): 35 | 36 | for word_num in range(len(user_input_sentence)): 37 | # Here we are running a for loop again on the passed sentence and each number of sentence is being stored in word_num 38 | if word_num in vowels_in_each_word: # Since Each Word is only appended with a word_num i.e 1, 2 or 3 if it has vowels 39 | # Therefore if a word_num i.e. 0 or 1 etc in inside the dict vowel_in_each_word 40 | # only then this if statement will be triggered 41 | # user_input_sentence[word_num] fetches the current word 42 | # len(vowels_in_each_word[word_num]) fetches number of vowels in vowel_ch for each word 43 | # vowels_in_each_word[word_num] fetches vowels for each word 44 | print(f'The word "{user_input_sentence[word_num]}" has {len(vowels_in_each_word[word_num])} vowel(s) which is/are: {vowels_in_each_word[word_num]}') 45 | else: 46 | print(f'The word "{user_input_sentence[word_num]}" has no vowels') # hitting else means that the current word has no vowels 47 | 48 | is_vowel(sentence) #is_vowel is being called 49 | 50 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Intermediate Function/Q01.py: -------------------------------------------------------------------------------- 1 | # Create a function that takes a list of numbers and returns the largest number. 2 | 3 | def is_largest(): 4 | index_0, index_1, temp = 0, 1, 0 5 | count = 1 6 | nums = input("Enter Any Numbers separated by a comma and a space example: 2, 3, 4, 5:\n").split(", ") 7 | nums = [int(num) for num in nums] # list comprehension to convert the list of string into a list of integers 8 | 9 | 10 | for index_num in range(len(nums) + 1): # this runs to loop 1 more time than length of nums list 11 | # We run this one more time so value of index_1 reaches the 1 more than the length 12 | # as soon index_1 > len(nums) the internal while loops stops running 13 | while index_1 < len(nums): # in each iteration previous two values are compared and if first of those values is greater 14 | # then those values are swapped if not then they are not swapped 15 | count += 1 # to count the iterations it took to make the largest number reach the end of the loop 16 | # 22, 3, 41, 5, 7, 9, 11, 21, 1 17 | if nums[index_0] > nums[index_1]: 18 | temp = nums[index_0] # as we replace value at nums[index_0] we need to store it temporarily and then pass it to nums[index_1] 19 | nums[index_0] = nums[index_1] # here value at nums[index_1] is stored into nums[index_0] 20 | nums[index_1] = temp # here ORIGINAL value at nums[index_0] is stored into nums[index_1] using temp variable 21 | 22 | 23 | index_0 += 1 # to create a sliding window without usage of another nested loop we use both these variables 24 | index_1 += 1 25 | print("The iteration ran:",count,"times") 26 | 27 | return nums[-1] # the largest number reaches the end 28 | 29 | print(f"{is_largest()} is the largest number in the list passed") 30 | 31 | ''' 32 | Here are some inputs this can be checked against: 33 | 22, 3, 41, 5, 7, 9, 11, 21, 1 34 | 13, 27, 35, 4, 8, 10, 19, 23, 2 35 | 6, 18, 29, 31, 3, 15, 20, 14, 8 36 | 12, 25, 7, 2, 33, 11, 9, 5, 17 37 | 30, 21, 1, 16, 28, 24, 19, 13, 4 38 | ''' -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Intermediate Function/Q02.py: -------------------------------------------------------------------------------- 1 | num = int(input("enter Nth Number\n")) 2 | # Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 3 | # we are staring indexing with 0 as first two numbers in fibonacci series are 0 and 1 4 | # indexes 0 1 2 3 4 5 6 7 8 9 10 5 | 6 | def rec_fibonacci(nth): 7 | if nth == 0 or nth == 1: # this is the base case 8 | return nth 9 | # If nth is greater than 1, it is computed as the sum of the two preceding Fibonacci numbers: fibonacci(nth - 1) and fibonacci(nth - 2) 10 | return rec_fibonacci(nth - 1) + rec_fibonacci(nth - 2) 11 | 12 | """For example, if nth = 3, the function will call rec_fibonacci(2) and rec_fibonacci(1). 13 | The result of rec_fibonacci(2) will be computed recursively, 14 | while rec_fibonacci(1) directly hits the base case and returns 1. """ 15 | 16 | print(rec_fibonacci(num)) 17 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Intermediate Function/Q03.py: -------------------------------------------------------------------------------- 1 | # Write a function to check whether a string is a palindrome. 2 | 3 | any_word = input("Enter Any String:\n").lower() 4 | 5 | # lets say any_word = Ana 6 | def is_palindrome(word:str): 7 | """ 8 | Check if a given word is a palindrome. 9 | 10 | Args: 11 | word (str): The string to check. 12 | 13 | Returns: 14 | bool: True if the word is a palindrome, False otherwise. 15 | """ 16 | flag = False # if any of the characters are not same flag remains False 17 | for char_num in range(1, len(word) + 1): # We want to compare strings using negative indexing, the negative indexing starts from 1 18 | # instead of 0 so we start it from 1 and end it 1 after the len(word) as the end in for loop is exclusive 19 | # These are the positive indexes for word if it was Ana. ['a', 'n', 'a'] indexes: [0, 1, 2] read from the left 20 | # These are the negative indexes for word Ana. [-3, -2, -1] start reading from the right 21 | # These are the numbers in char_num respectively: [1, 2, 3] 22 | # we are subtracting 1 from each char_num so character using positive indexing is checked against character at negative indexing 23 | # for example character at 1 - 1 for "Ana" will be a and character for -1 will also be a 24 | # 2 - 1 = 1 will be n and -2 will also be n 25 | if word[char_num - 1] == word[-char_num]: 26 | flag = True # if this is the case for each character the value is set to True again and again 27 | return flag 28 | 29 | if is_palindrome(any_word): 30 | print(f"Yes, {any_word} is a Palindrome!") 31 | else: 32 | print(f"No, {any_word} is not a Palindrome!") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Intermediate Function/Q04.py: -------------------------------------------------------------------------------- 1 | # Create a function that takes a list of integers and returns the sum of all even numbers. 2 | integers = input("Input Integers separated by space:\n").split(" ") 3 | even_nums = [int(num) for num in integers if (int(num) % 2 == 0)] 4 | def sum_of_evens(numbers): 5 | add = 0 6 | for num in even_nums: 7 | add += num 8 | print(f"The sum if all even numbers is: {add}") 9 | sum_of_evens(even_nums) -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Intermediate Function/Q05.py: -------------------------------------------------------------------------------- 1 | # Write a function to calculate the GCD (Greatest Common Divisor) of two numbers. 2 | # GCD is also called Highest Common Factor 3 | 4 | def gcd(num1_factors, num2_factors): 5 | common_factors = [] 6 | for nums in num1_factors: 7 | for num in num2_factors: 8 | if nums == num: 9 | common_factors.append(num) 10 | return max(common_factors) 11 | 12 | def calc_gcd(): 13 | num1 = int(input("Enter First Number:\n")) 14 | num2 = int(input("Enter Second Number:\n")) 15 | factors_of_num1 = [] 16 | factors_of_num2 = [] 17 | 18 | for num in range(1, num1 + 1): 19 | if num1 % num == 0: 20 | factors_of_num1.append(num) 21 | 22 | for count in range(1, num2 + 1): 23 | if num2 % count == 0: 24 | factors_of_num2.append(count) 25 | 26 | print(f"The Greatest Common Divisor between {num1} and {num2} is {gcd(factors_of_num1, factors_of_num2)}") 27 | calc_gcd() -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Intermediate Function/Q06.py: -------------------------------------------------------------------------------- 1 | # Create a function that accepts a dictionary and returns the key with the highest value. 2 | numbers_dict = { 3 | "a": 102, "b": 600, "c": 8, "d": 9898, "e": 12, "f": 2332, "g": 732 4 | } 5 | def highest_dict_value(numbers): 6 | max_value = 0 7 | values_from_dict = [value for value in numbers_dict.values()] # 102 600 8 9898 12 2332 732 8 | keys_from_dict = [key for key in numbers_dict.keys()] # "a", "b", "c", "d", "e", "f", "g" 9 | for index, value in enumerate(values_from_dict): 10 | temp_index = index + 1 11 | if temp_index < len(values_from_dict): 12 | if values_from_dict[index] > values_from_dict[temp_index]: 13 | temp = values_from_dict[index] 14 | values_from_dict[index] = values_from_dict[temp_index] 15 | values_from_dict[temp_index] = temp 16 | else: 17 | break 18 | max_value = values_from_dict[-1] 19 | for key, value in numbers.items(): 20 | if value == max_value: 21 | return key 22 | 23 | 24 | print(f'The key in the current dictionary is "{highest_dict_value(numbers_dict)}"') 25 | 26 | 27 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/README.md: -------------------------------------------------------------------------------- 1 | ### Basic Function Questions 2 | 3 | 1. Write a function to calculate the area of a circle given its radius. 4 | 2. Create a function that takes two numbers and returns their sum. 5 | 3. Write a function to find the factorial of a number using recursion. 6 | 4. Write a function that takes a string and returns it reversed. 7 | 5. Create a function to check if a given number is prime. 8 | 6. Write a function to count the vowels in a given string. 9 | 10 | ### Intermediate Function Questions 11 | 12 | 1. Create a function that takes a list of numbers and returns the largest number. 13 | 2. Write a function to find the nth Fibonacci number using recursion. 14 | 3. Write a function to check whether a string is a palindrome. 15 | 4. Create a function that takes a list of integers and returns the sum of all even numbers. 16 | 5. Write a function to calculate the GCD (Greatest Common Divisor) of two numbers. 17 | 6. Create a function that accepts a dictionary and returns the key with the highest value. 18 | 19 | ### Advanced Function Questions 20 | 21 | 1. Write a function that calculates the power of a number without using the ** operator. 22 | 2. Create a function that converts a given temperature from Celsius to Fahrenheit and vice versa. 23 | 3. Write a function to flatten a nested list. 24 | 4. Create a function to check if two strings are anagrams. 25 | 5. Write a function that takes a list and removes all duplicate elements. 26 | 6. Create a function that takes a string and counts the frequency of each character. 27 | 28 | ### Real-world Scenarios 29 | 30 | 1. Write a function that takes a list of employee salaries and calculates the average salary. 31 | 2. Create a function to generate a random password of given length, containing uppercase, lowercase, numbers, and special characters. 32 | 33 | ## Some Questions That I found Interesting 34 | ### Finding Maximum Value in a list 35 | 36 | 37 | ![](https://i.imgur.com/7aIQIST.png) 38 | 39 | This can be found at: https://excalidraw.com/#json=m4bWt2DSERIDiD8_xPjR4,qADyfXhbbcj1v6m9IQ-aHw 40 | 41 | Although this isn't the most efficient solution the program keeps on running until the largest value in a list reaches the **end** of the list. And the end we are returning that last element of the list as you can see in the image that 30 starts from index 0 and reaches index -1 (negative indexing). In Iteration 1 the loop starts comparing the first two numbers 30 and 21, if the first number is greater than the second number than they will be replaced else nothing will happen. So 30 comes in place of 21 and 21 comes in place of 30 and this keeps happening in each iteration the sliding window keeps on changing i.e. 42 | 43 | ![](https://i.imgur.com/Ij222NJ.png) 44 | 45 | The green combination of first and second variable is like a sliding window and we are comparing each element in each iteration -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Real-world Scenarios/Q01.py: -------------------------------------------------------------------------------- 1 | # Write a function that takes a list of employee salaries 2 | # and calculates the average salary. 3 | 4 | salaries_li = input("Enter Salaries Separated by comma:\n").split(",") 5 | salaries_li = [int(salary) for salary in salaries_li] 6 | def calc_avg_employee_salary(salaries:list): 7 | total_salary, avg_salary = 0, 0 8 | for salary in salaries: 9 | total_salary += salary 10 | avg_salary = total_salary/(len(salaries)) 11 | return avg_salary 12 | 13 | print(f"Average Salary is: {calc_avg_employee_salary(salaries_li)}") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-02/Real-world Scenarios/Q02.py: -------------------------------------------------------------------------------- 1 | # Create a function to generate a random password of given length, 2 | # containing uppercase, lowercase, numbers, and special characters. 3 | import random 4 | 5 | letters = { 6 | 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 7 | 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 8 | 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 9 | 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 10 | 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z' 11 | } 12 | 13 | special_characters = ( 14 | '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', 15 | '-', '=', '+', '[', ']', '{', '}', '|', '\\', ';', 16 | ':', '"', '\'', '<', '>', ',', '.', '?', '/', 17 | '~', '`', '_', ':', '$', '(', ')', '[', ']', 18 | '^', '&', '%', '*', '+', '-', '=', '|', '\\', 19 | '!', '@', '#', '$', '<', '>', '{', '}', ':', 20 | '"', '\'', '/', '?', ';', ',', '.', '¬', '©', 21 | '®', '™', '°', '¶', '÷', '×', '≈', '≠', '∑', '∏', 22 | '√', '∞', '∫', 'Δ', 'π', 'µ', 'λ', 'χ', 'α', 'β' 23 | ) 24 | 25 | 26 | def convert_upper(letter): 27 | return letter.upper() 28 | 29 | def convert_lower(letter): 30 | return letter.lower() 31 | 32 | def generate_alphabets(): 33 | capital_or_small = (convert_upper, convert_lower) 34 | number_of_steps = random.randint(1, 27) # A-Z are 26 characters 35 | letter_size = random.randrange(0,2) 36 | num = random.randrange(1, len(letters) + 1, number_of_steps) # generates unique number from 1 to 26 37 | # I made this to generate an alphabet 38 | alphabet_random = capital_or_small[letter_size](letters[num]) # will either return a capital or small alphabet for the current random number 39 | return alphabet_random # example returns S 40 | 41 | def generate_numbers(): 42 | num = random.randint(10, 10_0000) 43 | return str(num) # example returns 999 44 | 45 | def generate_special_characters(): 46 | num = random.randint(0, len(special_characters) - 1) 47 | return special_characters[num] # example returns & 48 | 49 | def generate_pass(): 50 | 51 | print("What's the length of password that you want?") 52 | pass_len = int(input()) 53 | passwd = "" 54 | while len(passwd) < pass_len: 55 | 56 | passwd += generate_special_characters() # returns 1 character 57 | passwd += generate_alphabets() # returns 1 character 58 | passwd += generate_numbers() # can return any unknown number of characters between 10 and 10_0000 59 | passwd += generate_special_characters() 60 | passwd += generate_alphabets() 61 | passwd += generate_alphabets() 62 | passwd += generate_numbers() 63 | passwd += generate_special_characters() 64 | 65 | if len(passwd) > pass_len: 66 | passwd = passwd[0:pass_len] # since generate_numbers can generate any number of numbers we need to 67 | # make sure that password length remains what the user asked for 68 | return passwd 69 | 70 | def ask_user(): 71 | while True: 72 | password = generate_pass() 73 | print(f"Here is your Password: {password}") 74 | print("Would You Like another password? enter y for yes and q to quit") 75 | user_choice = input().lower() 76 | 77 | if user_choice == 'q': 78 | break 79 | else: 80 | password = generate_pass() 81 | print(f"Here is your Password: {password}") 82 | print("Would You Like another password? enter y for yes and q to quit") 83 | 84 | ask_user() -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Advanced Dictionary Usage/Q11.py: -------------------------------------------------------------------------------- 1 | # Merge the following two dictionaries and print the result: dict1 = {'a': 1, 'b': 2}, dict2 = {'c': 3, 'd': 4}. 2 | dict1 = {'a': 1, 'b': 2} 3 | dict2 = {'c': 3, 'd': 4} 4 | 5 | dict_merged = dict1 | dict2 # The merge operator returns a new dictionary after merging so we are storing the returned dictionary 6 | # new dictionary means new memory address 7 | print(dict_merged) # outputs: {'a': 1, 'b': 2, 'c': 3, 'd': 4} 8 | 9 | # We can also update operator the dictionaries in-place using: 10 | 11 | dict1 |= dict2 12 | print(dict1) # This way the dictionary at left-hand side is merged with 2nd dictionary but in place -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Advanced Dictionary Usage/Q12.py: -------------------------------------------------------------------------------- 1 | # Create a dictionary from a list of tuples: [('name', 'Alice'), ('age', 25), ('city', 'Paris')]. 2 | user_info = [('name', 'Alice'), ('age', 25), ('city', 'Paris')] 3 | 4 | user_dict = {} 5 | user_dict.update(user_info) # The update method for dictionaries allows us to pass tuple 6 | # The function automatically made the first of a tuple key and the second value the value of that key 7 | print(user_dict) # {'name': 'Alice', 'age': 25, 'city': 'Paris'} 8 | 9 | # We can add this tuple to the dictionary this way: 10 | another_user_dict = {} 11 | for key_value in user_info: 12 | another_user_dict.update({key_value[0]: key_value[1]}) 13 | print(another_user_dict) -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Advanced Dictionary Usage/Q13.py: -------------------------------------------------------------------------------- 1 | # Sort the keys of the dictionary {'z': 1, 'a': 2, 'c': 3} in ascending order and print the sorted dictionary. 2 | 3 | some_dict = {'z': 1, 'a': 2, 'c': 3} 4 | 5 | dict_li = [] 6 | for key_value in some_dict.items(): # instead of unpacking both key and value separately 7 | # I am unpacking both in 1 variable 8 | dict_li.append(key_value) # the variable key_value holds a tuple of the key-value pair 9 | # each tuple is appended to the dict_li list 10 | # now we need to sort this list of tuples 11 | 12 | dict_li.sort() # this sorts list in place 13 | some_dict.clear() # Now we need to recreate the dictionary, some_dict is now empty 14 | 15 | some_dict.update(dict_li) # The list of tuples have been added to the dictionary 16 | print(some_dict) # outputs: {'a': 2, 'c': 3, 'z': 1} -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Advanced Dictionary Usage/Q14.py: -------------------------------------------------------------------------------- 1 | # Reverse the dictionary {'a': 1, 'b': 2, 'c': 3} so that keys become values and values become keys. 2 | 3 | some_dict = {'a': 1, 'b': 2, 'c': 3} 4 | li_tuples = [] 5 | for key_value in some_dict.items(): 6 | li_tuples.append(key_value) # We are unpacking each key-value pair as a tuple and appending to an empty list 7 | # Since tuples are immutable we can not sort them that's why we are using a list 8 | 9 | li_tuples.sort(reverse=True) # This sorts list in place in descending order 10 | print(li_tuples) # outputs: [('c', 3), ('b', 2), ('a', 1)] 11 | some_dict.clear() # we remove all elements inside the dict 12 | some_dict.update(li_tuples) # Then we give the list of tuples to the update method of dictionaries 13 | print(some_dict) # outputs: [('c', 3), ('b', 2), ('a', 1)] -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Advanced Dictionary Usage/Q15.py: -------------------------------------------------------------------------------- 1 | # Write a Python function to check if two dictionaries are identical (contain the same key-value pairs). 2 | 3 | dict1 = {'c': 3, 'b': 2, 'a': 1} 4 | dict2 = {'a': 1, 'd': 4, 'e': 5, 'c': 3, 'b': 2} 5 | dict3 = dict1 | dict2 # We can see that keys in dict1 are already present in dict2 in this case keys of dict2 take precedence 6 | # as dict2 comes last 7 | 8 | def check_identical_dicts(first_dict, second_dict): 9 | if first_dict == second_dict: 10 | print('Yes they are identical') 11 | else: 12 | print("Nope! these are not identical") 13 | 14 | check_identical_dicts(dict2, dict3) 15 | 16 | print(dict2) # outputs: {'a': 1, 'd': 4, 'e': 5, 'c': 3, 'b': 2} 17 | print(dict3) # outputs: {'c': 3, 'b': 2, 'a': 1, 'd': 4, 'e': 5} 18 | # Since dictionaries are implementation of hashtable order does not matter in their case 19 | # Because check_identical_dicts is actually comparing keys and their respective values -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Applications of Dictionaries/Q20.py: -------------------------------------------------------------------------------- 1 | # Use a dictionary to count the occurrences of each word in the string 2 | # "hello world hello python world". 3 | 4 | some_dict = {} 5 | sentence = "hello world hello python world" 6 | 7 | words = sentence.split(" ") 8 | for word in words: 9 | if word in some_dict: 10 | some_dict[word] += 1 11 | else: 12 | some_dict[word] = 1 13 | for k,v in some_dict.items(): 14 | if v > 1: 15 | print(k, "appeared", v, "time") 16 | else: 17 | print(k, "appeared", v, "time") -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Applications of Dictionaries/Q21.py: -------------------------------------------------------------------------------- 1 | # Write a Python program to find the key with the maximum value in the dictionary 2 | # {'a': 10, 'b': 15, 'c': 7}. 3 | 4 | numbers_dict = {'a': 10, 'b': 15, 'c': 7} 5 | maximum_value = max(numbers_dict.values()) # number_dict.values returns something like a dictionary tuple i.e. dict_values([10, 15, 7]) 6 | print(maximum_value) # We used built in method max to find the maximum value in a tuple -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Applications of Dictionaries/Q22.py: -------------------------------------------------------------------------------- 1 | # Create a dictionary to map numbers 1 to 5 to their squares (e.g., {1: 1, 2: 4, 3: 9, ...}). 2 | 3 | numbers = {} 4 | for i in range(1, 6): 5 | numbers.update({i: i * i}) 6 | 7 | # Another way to do this is using a dictionary comprehension 8 | 9 | squares = {num : (num * num) for num in range(1, 6)} 10 | print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} 11 | 12 | # oddly a dictionary comprehension is just like a list comprehension 13 | # where instead of using 1 variable we are using a key value pair separated by : -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Applications of Dictionaries/Q23.py: -------------------------------------------------------------------------------- 1 | # Write a Python program to remove duplicate values from the dictionary 2 | # {'a': 10, 'b': 15, 'c': 10, 'd': 15}. 3 | 4 | 5 | some_dict = {'a': 10, 'b': 15, 'c': 10, 'd': 15} 6 | 7 | def remove_duplicates(): 8 | 9 | dict_keys = tuple(some_dict.keys()) # We are fetching all keys of some_dict dictionary, some_dict.keys() returns dict_keys(['a', 'b', 'c', 'd']) 10 | # We are converting returned dict_keys into a tuple 11 | dict_values = tuple(some_dict.values()) # Here we are fetching values 12 | some_dict.clear() # This removes all key-value pairs from some_dict in place 13 | new_dict = {} 14 | for item in zip(dict_values, dict_keys): # zip is a built-in function that is used for looping over multiple iterables 15 | # Here zip helping us iterate over two tuples dict_values and dict_keys 16 | # We could have used two variable, but we are using 1 variable item this way two values are unpacked as a tuple 17 | if item[0] in new_dict: # This checks if 10 or 15 are already a key 18 | continue # if 10 or 15 are already a key we do not want to update dictionary 19 | # This is because i want the first instance of some_dict value to be unique 20 | new_dict.update({item}) # If we pass a tuple to update it will make the first value a key and the next value a value (dictionary) 21 | return new_dict 22 | # The question asks us to remove duplicate values but new_dict after removing duplicates has made keys values and values key we need to change that 23 | 24 | returned_dict = remove_duplicates() 25 | 26 | def format_dict(ret_dict): 27 | some_dict = {val : key for val, key in zip(returned_dict.values(), returned_dict.keys())} 28 | # Here we are using a dictionary comprehension 29 | # But instead of using 1 loop we are using zip which again can fetch two values from two loops 30 | # Instead of storing keys and values of returned_dict into two tuples we are directly getting them from dict_values and dict_keys 31 | # Each key and value are stored in val and key variables and each them a new pair of val: key is added to some_dict 32 | # This makes key and values returned by returned_dict into values and keys of some_dict 33 | print(some_dict) # Outputs: {'a': 10, 'b': 15} 34 | # Since c and d has duplicate values they have been removed 35 | 36 | format_dict(returned_dict) 37 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Applications of Dictionaries/Q24.py: -------------------------------------------------------------------------------- 1 | # Write a Python function that accepts a dictionary and a key, and returns the value associated with the key. 2 | # If the key doesn’t exist, return "Key not found". 3 | 4 | def func(k, some_dict): 5 | if k in some_dict: 6 | return some_dict[k] 7 | else: 8 | return "Key not found" 9 | 10 | student_info = {"Name": "Shehryar", "City": "Faisalabad", "Degree": "Bachelors (CS)", "Programming Languages": ["Python", "JavaScript"], 11 | "Influential Teachers": 12 | ("Sir Amran", "Sir Ahmad Jajja", "Sir Saqib", "Sir Waleed", "Sir Rao Umar", "Sir Ahmad Aftab", "Mam Farwa"), 13 | "Python Learning Channels He Recommends": {"Tech with Tim": "https://www.youtube.com/@TechWithTim", "b001": "https://www.youtube.com/@b001", "Nasir Hussain" : "https://www.youtube.com/@nasirhussain5919", "Corey Schafer": "https://www.youtube.com/@coreyms"}} 14 | 15 | print(func("Influential Teachers", student_info)) -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Basic Operations/Q01.py: -------------------------------------------------------------------------------- 1 | # Create a dictionary student with keys: name, age, and grade. Assign them appropriate values. 2 | # This is syntax of any dictionary: 3 | # dict_name = {key: value()} the Values can be anything i.e. string, number, list, tuple, set etc 4 | 5 | 6 | student_names = ['Hanzala', 'Shehryar', 'Hamza', 'Bilal', 'Ali'] 7 | student_ages = [22, 29, 21, 24, 25] 8 | student_grades = ['B', 'A', 'C', 'A', 'B'] 9 | 10 | students = {"name": student_names, "age": student_ages, "grade": student_grades } 11 | 12 | # student_comp = [student for student in students] Such a List Comprehension fetches keys 13 | student_comp = [student for student in students.values()] # this will fetch values and make them nest 14 | 15 | for val in student_comp: 16 | print(val) # This will return three separate lists as inside the comprehension these were part of nested lists -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Basic Operations/Q02.py: -------------------------------------------------------------------------------- 1 | # Access the value of the key grade in the student dictionary. 2 | name = ['Hanzala', 'Shehryar', 'Hamza', 'Bilal', 'Ali'] 3 | age = [22, 29, 21, 24, 25] 4 | grade = ['B', 'A', 'C', 'A', 'B'] 5 | 6 | students = {"name": name, "age": age, "grade": grade } 7 | 8 | # print(students['grade']) # Outputs: ['B', 'A', 'C', 'A', 'B'] 9 | # To access Let's say Grade of Shehryar we can: 10 | for val in students.values(): # Unpacks each value of dictionary in each iteration 11 | if 'Shehryar' in val: # checks if name 'Shehryar' is in the dictionary 12 | print(students['grade'][1]) # Since Shehryar's grade is at index 1 in grade list therefore we access that specific grade 13 | # We access a dictionary by its keys 'grade' is a key 14 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Basic Operations/Q03 (Updating Dictionaries).py: -------------------------------------------------------------------------------- 1 | # Add a new key city to the student dictionary and set its value to "New York". 2 | # This is a very good resource to learn about updating Key Value pairs of dictionaries: 3 | # https://www.digitalocean.com/community/tutorials/python-add-to-dictionary 4 | # Since methods are removing the same key make sure to comment and uncomment parts of the code 5 | # as required 6 | 7 | students = {"name": 'Shehryar', "age": 29, "grade": 'A' } 8 | 9 | # One way of adding a new key-Value pair is this: 10 | students['city'] = "New York" # Here we are using an assignment operator to assign value to a key 11 | 12 | # Another way of doing this is using .update method: 13 | students.update({'city':'New York'}) # Here we are updating the dictionary and add a new key-value pair 14 | 15 | # Remember Merging Two dictionaries and adding values is a different thing: 16 | # We can also use the Merge Operator i.e. Dictionary_1 | Dictionary_2: 17 | city = {'city': 'New York'} 18 | student = students | city 19 | print(student) # This merging returns a new dictionary that we are storing into student dictionary 20 | # This will be output: {'name': 'Shehryar', 'age': 29, 'grade': 'A', 'city': 'New York'} 21 | 22 | # We can also use Update Operator i.e. Dictionary_1 |= Dictionary_2 23 | city = {'city': 'New York'} 24 | students |= city # This modifies dictionary in-place instead of returning a new dictionary 25 | # and then us having to save the dictionary 26 | print(students) # {'name': 'Shehryar', 'age': 29, 'grade': 'A', 'city': 'New York'} -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Basic Operations/Q04.py: -------------------------------------------------------------------------------- 1 | # Update the value of the age key in the student dictionary to 20. 2 | students = {"name": 'Shehryar', "age": 29, "grade": 'A' } 3 | 4 | students["age"] = 20 5 | 6 | print(students) # {'name': 'Shehryar', 'age': 20, 'grade': 'A'} -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Basic Operations/Q05 (Removing Values from a dictionary).py: -------------------------------------------------------------------------------- 1 | # Remove the key city from the student dictionary. 2 | # Since methods are removing the same key make sure to comment and uncomment parts of the code 3 | # as required 4 | 5 | student = {'name': 'Shehryar', 'age': 29, 'grade': 'A', 'city': 'New York'} 6 | 7 | # We can remove a Key-Value pair using del keyword and the key we want to remove 8 | del student['city'] 9 | # print(student) # Outputs: {'name': 'Shehryar', 'age': 29, 'grade': 'A'} 10 | 11 | # Another way is to use .pop() method and pass it a key, we can not use it without passing a key: 12 | student.pop('city') # Will remove Key-Value pair for key city, we can also set a default value for popping 13 | 14 | # Another way is using .popitem() This doesn't expect an argument and will remove the last most recent key-value pair inserted 15 | student.popitem() 16 | 17 | # This will remove the clear all key-value pairs inside dictionary: 18 | student.clear() 19 | 20 | # This deletes the entire dictionary 21 | del student -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Challenging Problems/Q25.py: -------------------------------------------------------------------------------- 1 | # Given two dictionaries dict1 = {'a': 5, 'b': 10} and dict2 = {'a': 3, 'b': 7}, 2 | # write a Python program to add the values of matching keys and print the result. 3 | 4 | dict1 = {'a': 5, 'd': 12, 'b': 10, 'e': 9} 5 | dict2 = {'c': 19,'a': 3, 'b': 7, 'e': 29} 6 | 7 | def add_dicts(dict1, dict2): # Here in definition two sets are arguments that add_dicts expects 8 | keys_dict1_set = set(dict1.keys()) # This fetches all the keys of dict1 and will only keep unique keys from dict1 and converts the list to a set 9 | keys_dict2_set = set(dict2.keys()) # We converted these into a set because we want to use intersection function/operator of sets 10 | # Intersection means common elements in both sets 11 | # When we take intersection of two sets a new set of common_keys is returned having only common values that are in both sets 12 | common_keys = keys_dict1_set & keys_dict2_set 13 | # Another way of intersection is: 14 | # common_keys = keys_dict1_set.intersection(keys_dict2_set) 15 | # This set contains a, b and e keys 16 | 17 | for key in common_keys: # This loop runs 3 times but each time we are fetching values of dict1 and dict2 of the keys present in common_keys 18 | print(f"Value of {key} in dict1 is {dict1[key]} and value of {key} in dict2 is {dict2[key]}") 19 | print("So sum of the values is:", dict1[key] + dict2[key]) 20 | 21 | add_dicts(dict1, dict2) -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Challenging Problems/Q26.py: -------------------------------------------------------------------------------- 1 | # Write a Python program to create a dictionary where the keys are the first 2 | # n positive integers, and the values are their cubes. Take n as user input. 3 | 4 | 5 | # Here, I am assuming that the instructor wants the user to specify how many elements (key-value pairs) 6 | # should be included in the dictionary. 7 | n = int(input("Enter A Positive Integer Till which you want elements in the dictionary:\n")) 8 | 9 | def create_dict(input_value): 10 | if n <= 0: 11 | return "No Key Value Elements Possible for given number" 12 | else: 13 | cubes_till_n = {num : (num * num * num) for num in range(1, input_value + 1)} # This will keep on making num 14 | # a key till the number entered by the user is reached, and for value each of that num is multiplied thrice 15 | # so that a cubes are found and set as values 16 | return cubes_till_n 17 | 18 | print("Here's the dictionary", create_dict(n)) -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Challenging Problems/Q27.py: -------------------------------------------------------------------------------- 1 | # Flatten the following nested dictionary into a single-level dictionary: 2 | # {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}} 3 | 4 | un_flattened_dict = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}} 5 | 6 | ''' If I clear the dictionary like this all values and keys of the dictionary will be removed even the copied one in dict_values and dict_keys 7 | dict_values = un_flattened_dict.values() 8 | dict_keys = un_flattened_dict.keys() 9 | un_flattened_dict.clear() 10 | 11 | The reason for this behavior is that dictionary_name.values() and dictionary_name.keys() return a view of the dictionary's keys and values. 12 | A view is not a list or a tuple, although it may look similar. Instead, it is a dynamic reflection of the data currently present in the dictionary. 13 | 14 | The variables dict_values and dict_keys hold references to the views returned by un_flattened_dict.values() and un_flattened_dict.keys() rather than independent copies. 15 | As a result, any changes to the original dictionary are immediately reflected in these views. 16 | 17 | To make dict_values and dict_keys independent of the dictionary, they can be converted to a tuple or a list, as needed. ''' 18 | 19 | dict_values = tuple(un_flattened_dict.values()) # this holds {'b': 1, 'c': 2} and {'e': 3, 'f': 4} 20 | dict_keys = tuple(un_flattened_dict.keys()) # this holds a nd d 21 | un_flattened_dict.clear() # Now this will not alter values and keys in dict_values and dict_keys 22 | 23 | for val in dict_values: 24 | un_flattened_dict.update(val) # Each Value is a dictionary itself, We can pass a dictionary directly to a update method 25 | 26 | print(un_flattened_dict) # Outputs: {'b': 1, 'c': 2, 'e': 3, 'f': 4} -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Challenging Problems/Q28.py: -------------------------------------------------------------------------------- 1 | # Write a Python program to split a dictionary into two based on whether the 2 | # values are odd or even. 3 | import random 4 | alphabets = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z') 5 | 6 | def make_random_num(): # This randomly creates a number from 1000 to 10000 7 | num = random.randrange(1000, 10_001) 8 | return num 9 | 10 | evens = {} 11 | for alphabet in alphabets: #This loop will run 26 times 12 | num = make_random_num() # Each time a random number will be stored in num 13 | if num % 2 == 0: # If that number is even it will be added to the dictionary evens 14 | evens.update({alphabet: num}) 15 | 16 | odds = {} 17 | for alphabet in alphabets: 18 | num = make_random_num() 19 | if num % 2 != 0: # If that number is odd it will be added to the dictionary odds 20 | odds.update({alphabet: num}) 21 | 22 | # We could haved solve these using dictionary comprehensions and filter -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Challenging Problems/Q29.py: -------------------------------------------------------------------------------- 1 | # Create a dictionary comprehension to filter out all keys in 2 | # {'a': 1, 'b': 2, 'c': 3, 'd': 4} where the value is less than 3. 3 | 4 | some_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4} 5 | keys = some_dict.keys() 6 | 7 | filtered_keys = {k: v for k, v in some_dict.items() if v < 3} 8 | print(filtered_keys) # Outputs: {'a': 1, 'b': 2} 9 | # Again we could also do this with filter method -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Challenging Problems/Q30.py: -------------------------------------------------------------------------------- 1 | # Create a dictionary comprehension to filter out all keys in {'a': 1, 'b': 2, 'c': 3, 'd': 4} where the value is less than 3. 2 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Iterating through Dictionaries/Q06.py: -------------------------------------------------------------------------------- 1 | # Iterate through the dictionary student and print all keys. 2 | students = { 3 | "names": ['Shehryar', 'Ali', 'Adeel', 'Nabeel', 'Mudassar'], 4 | "ages": [29, 24, 21, 25, 30], 5 | "grades": ['A', 'B', 'A', 'C', 'B'] 6 | } 7 | 8 | for student in students: 9 | print(student) # The variable student sequentially access keys of the dictionary 10 | 11 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Iterating through Dictionaries/Q07.py: -------------------------------------------------------------------------------- 1 | # Iterate through the dictionary student and print all values. 2 | 3 | students = { 4 | "names": ['Shehryar', 'Ali', 'Adeel', 'Nabeel', 'Mudassar'], 5 | "ages": [29, 24, 21, 25, 30], 6 | "grades": ['A', 'B', 'A', 'C', 'B'] 7 | } 8 | 9 | for student in students.values(): 10 | print(student) # This sequentially accesses the values of the keys which are lists -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Iterating through Dictionaries/Q08.py: -------------------------------------------------------------------------------- 1 | # Iterate through the dictionary student and print all key-value pairs in the format key: value. 2 | students = { 3 | "names": ['Shehryar', 'Hassan', 'Adeel', 'Nabeel', 'Mudassar', 'Mubasshar', 'Aqeel'], 4 | "ages": [29, 24, 21, 25, 30, 23, 24], 5 | "grades": ['A', 'B', 'A', 'C', 'B', 'A', 'D'] } 6 | 7 | for student, student_value in students.items(): # .items is unpacking both keys and values 8 | print(f"{student} : {student_value}") 9 | 10 | # To unpack individual student data we can: 11 | 12 | for student_no in range(len(students["names"])): # By using students["names"] we are accessing a list of names student_no contains the current 13 | # index we want to run the internal loop the times the students because we want data for each student 14 | student_data = "Student's Name: " # This is a string that is re-assigned after internal loop runs for each key, value pairs 15 | 16 | 17 | for student, student_value in students.items(): # Keys and Their values are being unpacked in variables student and student_value 18 | if student == 'names': # When key is names we want to access the list element at current index i.e. 0, 1, 2,.. 19 | student_data += student_value[student_no] # Student's Name is concatenated to the string 20 | student_data += " Student's Age: " # Then we concatenate space + "Student's Age: " to student_data string 21 | elif student == 'ages': # When key is ages we want to access the list element at current index i.e. 0, 1, 2,.. 22 | student_data += str(student_value[student_no]) # Since elements inside this list are int we need to convert them to string as we are concatenating to a string 23 | student_data += " Student's Grade: " # Again We concat another string to student_data 24 | elif student == 'grades': # When key is grades we now want to concatenate the grade for the current student 25 | student_data += student_value[student_no] 26 | # internal for loop ends here and the flow exits it because next line is part of outerloop 27 | print(student_data) # This prints Student's Name: Shehryar Student's Age: 29 Student's Grade: A for first iteration of outer_loop 28 | 29 | # There is an easier way to do this: (And this is the better logic utilizing dictionaries features) 30 | print("------------------------------------------------------------------") 31 | for student_no in range(len(students["names"])): 32 | print(f"Student's Name: {students['names'][student_no]} Student's Age: {students['ages'][student_no]} Student's Grade: {students['grades'][student_no]}") 33 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Iterating through Dictionaries/Q09.py: -------------------------------------------------------------------------------- 1 | # Check if the key grade exists in the student dictionary and print True or False. 2 | students = { 3 | "names": ['Shehryar', 'Hassan', 'Adeel', 'Nabeel', 'Mudassar', 'Mubasshar', 'Aqeel'], 4 | "ages": [29, 24, 21, 25, 30, 23, 24], 5 | "grades": ['A', 'B', 'A', 'C', 'B', 'A', 'D'] } 6 | 7 | print(True if 'grades' in students else False) # This Ternary Operator implementation in python 8 | # It means print True if 'grades' is in students dictionary else print False 9 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Iterating through Dictionaries/Q10.py: -------------------------------------------------------------------------------- 1 | # Count the total number of keys in the student dictionary. 2 | 3 | students = { 4 | "names": ['Shehryar', 'Hassan', 'Adeel', 'Nabeel', 'Mudassar', 'Mubasshar', 'Aqeel'], 5 | "ages": [29, 24, 21, 25, 30, 23, 24], 6 | "grades": ['A', 'B', 'A', 'C', 'B', 'A', 'D'] } 7 | 8 | print(len(students)) # Whenever we access dictionary like this it presents it's keys to function calling it -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Nested Dictionaries/Q16.py: -------------------------------------------------------------------------------- 1 | # Create a nested dictionary to represent: Person: Name: John, Age: 30, Address: 2 | # Street: 123 Elm St, City: Boston. 3 | # Access the value of the City 4 | 5 | person = {'Name': 'John', 'Age': 30, 'Address': {'Street': '123 Elm St', 'City': 'Boston'}} 6 | 7 | print(person['Address']['City']) -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Nested Dictionaries/Q17.py: -------------------------------------------------------------------------------- 1 | # Add a new key Phone to the nested dictionary with the value "123-456-7890". 2 | person = {'Name': 'John', 'Age': 30, 'Address': {'Street': '123 Elm St', 'City': 'Boston'}} 3 | 4 | person['Phone'] = "123-456-7890" -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Nested Dictionaries/Q18.py: -------------------------------------------------------------------------------- 1 | 2 | # Delete the Address key from the nested dictionary. 3 | 4 | person = {'Name': 'John', 'Age': 30, 'Address': {'Street': '123 Elm St', 'City': 'Boston'}} 5 | 6 | person.popitem() # Will delete last element/attribute Address in place 7 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/Nested Dictionaries/Q19.py: -------------------------------------------------------------------------------- 1 | # Iterate through all the keys in the outermost level of the nested dictionary and print them. 2 | person = {'Name': 'John', 'Age': 30, 'Phone': "123-456-7890", 'Address': {'Street': '123 Elm St', 'City': 'Boston'}} 3 | 4 | person.popitem() 5 | for k in person.keys(): 6 | print(person[k]) -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/README.md: -------------------------------------------------------------------------------- 1 | ### **Basic Operations** 2 | 3 | 1. Create a dictionary `student` with keys: `name`, `age`, and `grade`. Assign them appropriate values. 4 | 2. Access the value of the key `grade` in the `student` dictionary. 5 | 3. Add a new key `city` to the `student` dictionary and set its value to `"New York"`. 6 | 4. Update the value of the `age` key in the `student` dictionary to `20`. 7 | 5. Remove the key `city` from the `student` dictionary. 8 | 9 | --- 10 | 11 | ### **Iterating through Dictionaries** 12 | 13 | 6. Iterate through the dictionary `student` and print all keys. 14 | 7. Iterate through the dictionary `student` and print all values. 15 | 8. Iterate through the dictionary `student` and print all key-value pairs in the format `key: value`. 16 | 9. Check if the key `grade` exists in the `student` dictionary and print `True` or `False`. 17 | 10. Count the total number of keys in the `student` dictionary. 18 | 19 | --- 20 | 21 | ### **Advanced Dictionary Usage** 22 | 23 | 11. Merge the following two dictionaries and print the result: 24 | 25 | ```python 26 | dict1 = {'a': 1, 'b': 2} 27 | dict2 = {'c': 3, 'd': 4} 28 | ``` 29 | 12. Create a dictionary from a list of tuples: `[('name', 'Alice'), ('age', 25), ('city', 'Paris')]`. 30 | 13. Sort the keys of the dictionary `{'z': 1, 'a': 2, 'c': 3}` in ascending order and print the sorted dictionary. 31 | 14. Reverse the dictionary `{'a': 1, 'b': 2, 'c': 3}` so that keys become values and values become keys. 32 | 15. Write a Python function to check if two dictionaries are identical (contain the same key-value pairs). 33 | 34 | --- 35 | 36 | ### **Nested Dictionaries** 37 | - Create a nested dictionary to represent the following data: 38 | 39 | ``` 40 | Person: 41 | Name: John 42 | Age: 30 43 | Address: 44 | Street: 123 Elm St 45 | City: Boston 46 | ``` 47 | 16. Access the value of the `City` key in the nested dictionary from the previous question. 48 | 17. Add a new key `Phone` to the nested dictionary with the value `"123-456-7890"`. 49 | 18. Delete the `Address` key from the nested dictionary. 50 | 19. Iterate through all the keys in the outermost level of the nested dictionary and print them. 51 | 52 | --- 53 | 54 | ### **Applications of Dictionaries** 55 | 56 | 20. Use a dictionary to count the occurrences of each word in the string `"hello world hello python world"`. 57 | 21. Write a Python program to find the key with the maximum value in the dictionary `{'a': 10, 'b': 15, 'c': 7}`. 58 | 22. Create a dictionary to map numbers 1 to 5 to their squares (e.g., `{1: 1, 2: 4, 3: 9, ...}`). 59 | 23. Write a Python program to remove duplicate values from the dictionary `{'a': 10, 'b': 15, 'c': 10, 'd': 15}`. 60 | 24. Write a Python function that accepts a dictionary and a key, and returns the value associated with the key. If the key doesn’t exist, return `"Key not found"`. 61 | 62 | --- 63 | 64 | ### **Challenging Problems** 65 | 66 | 25. Given two dictionaries `dict1 = {'a': 5, 'b': 10}` and `dict2 = {'a': 3, 'b': 7}`, write a Python program to add the values of matching keys and print the result. 67 | 68 | 26. Write a Python program to create a dictionary where the keys are the first `n` positive integers, and the values are their cubes. Take `n` as user input. 69 | 70 | 27. Flatten the following nested dictionary into a single-level dictionary: 71 | 72 | ```python 73 | {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}} 74 | ``` 75 | 76 | 28. Write a Python program to split a dictionary into two based on whether the values are odd or even. 77 | 78 | 29. Create a dictionary comprehension to filter out all keys in `{'a': 1, 'b': 2, 'c': 3, 'd': 4}` where the value is less than 3. 79 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/create_files.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # I used this to create 30 Python Files that were needed to complete dictionaries assignment 3 | # Check for Fish shell and inform user 4 | if [[ $SHELL != *fish ]]; then 5 | echo "This script assumes you are using Fish shell. Continuing anyway..." 6 | fi 7 | 8 | # Define the problem statements 9 | read -r -d '' problems << 'EOF' 10 | # Create a dictionary student with keys: name, age, and grade. Assign them appropriate values. 11 | # Access the value of the key grade in the student dictionary. 12 | # Add a new key city to the student dictionary and set its value to "New York". 13 | # Update the value of the age key in the student dictionary to 20. 14 | # Remove the key city from the student dictionary. 15 | # Iterate through the dictionary student and print all keys. 16 | # Iterate through the dictionary student and print all values. 17 | # Iterate through the dictionary student and print all key-value pairs in the format key: value. 18 | # Check if the key grade exists in the student dictionary and print True or False. 19 | # Count the total number of keys in the student dictionary. 20 | # Merge the following two dictionaries and print the result: dict1 = {'a': 1, 'b': 2}, dict2 = {'c': 3, 'd': 4}. 21 | # Create a dictionary from a list of tuples: [('name', 'Alice'), ('age', 25), ('city', 'Paris')]. 22 | # Sort the keys of the dictionary {'z': 1, 'a': 2, 'c': 3} in ascending order and print the sorted dictionary. 23 | # Reverse the dictionary {'a': 1, 'b': 2, 'c': 3} so that keys become values and values become keys. 24 | # Write a Python function to check if two dictionaries are identical (contain the same key-value pairs). 25 | # Create a nested dictionary to represent: Person: Name: John, Age: 30, Address: Street: 123 Elm St, City: Boston. 26 | # Access the value of the city key in the nested dictionary from the previous question. 27 | # Add a new key Phone to the nested dictionary with the value "123-456-7890". 28 | # Delete the Address key from the nested dictionary. 29 | # Iterate through all the keys in the outermost level of the nested dictionary and print them. 30 | # Use a dictionary to count the occurrences of each word in the string: "hello world hello python world". 31 | # Write a Python program to find the key with the maximum value in the dictionary: {'a': 10, 'b': 15, 'c': 7}. 32 | # Create a dictionary to map numbers 1 to 5 to their squares (e.g., {1: 1, 2: 4, 3: 9, ...}). 33 | # Write a Python program to remove duplicate values from the dictionary: {'a': 10, 'b': 15, 'c': 10, 'd': 15}. 34 | # Write a Python function that accepts a dictionary and a key, and returns the value associated with the key. If the key doesn’t exist, return "Key not found". 35 | # Given two dictionaries dict1 = {'a': 5, 'b': 10} and dict2 = {'a': 3, 'b': 7}, write a Python program to add the values of matching keys and print the result. 36 | # Write a Python program to create a dictionary where the keys are the first n positive integers, and the values are their cubes. Take n as user input. 37 | # Flatten the following nested dictionary into a single-level dictionary: {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}}. 38 | # Write a Python program to split a dictionary into two dictionaries based on whether the values are odd or even. 39 | # Create a dictionary comprehension to filter out all keys in {'a': 1, 'b': 2, 'c': 3, 'd': 4} where the value is less than 3. 40 | EOF 41 | 42 | # Split problem statements into an array 43 | IFS=$'\n' read -r -d '' -a problem_array <<< "$problems" 44 | 45 | # Create .py files and add the respective problem statement 46 | for i in $(seq -w 1 30); do 47 | filename="Q$i.py" 48 | echo "${problem_array[$((10#$i - 1))]}" > "$filename" 49 | echo "Created $filename" 50 | done 51 | 52 | echo "All files created successfully!" 53 | 54 | -------------------------------------------------------------------------------- /Assignments/Beginner Python/Assignments-03/move_files.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # The 30 files were then move to respective folders using bash 3 | # Define folder names and the corresponding file ranges 4 | declare -A folder_ranges=( 5 | ["Basic Operations"]="Q01.py Q02.py Q03.py Q04.py Q05.py" 6 | ["Iterating through Dictionaries"]="Q06.py Q07.py Q08.py Q09.py Q10.py" 7 | ["Advanced Dictionary Usage"]="Q11.py Q12.py Q13.py Q14.py Q15.py" 8 | ["Nested Dictionaries"]="Q16.py Q17.py Q18.py Q19.py Q20.py" 9 | ["Applications of Dictionaries"]="Q21.py Q22.py Q23.py Q24.py Q25.py" 10 | ["Challenging Problems"]="Q26.py Q27.py Q28.py Q29.py Q30.py" 11 | ) 12 | 13 | # Create folders and move files to the correct folder 14 | for folder in "${!folder_ranges[@]}"; do 15 | mkdir -p "$folder" # Create the folder if it doesn't exist 16 | echo "Created folder: $folder" 17 | 18 | # Move the files to the folder 19 | for file in ${folder_ranges[$folder]}; do 20 | if [ -f "$file" ]; then 21 | mv "$file" "$folder" 22 | echo "Moved $file to $folder" 23 | else 24 | echo "File $file does not exist!" 25 | fi 26 | done 27 | done 28 | 29 | echo "All files moved successfully!" 30 | -------------------------------------------------------------------------------- /Assignments/FastAPI Assignments/Assignment _ University Registration Form API/My Solution/learn.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from fastapi import FastAPI, HTTPException 4 | from enum import Enum 5 | from fastapi import FastAPI, Query 6 | import re 7 | 8 | 9 | from pydantic import BaseModel 10 | 11 | studentID = 0 12 | app = FastAPI() 13 | 14 | @app.get("/") 15 | def homepage(): 16 | return {"Hello": "World"} 17 | 18 | @app.get("/students/all") 19 | def get_student(): # FastAPI automatically validates the type 20 | return "All Students Endpoint" 21 | 22 | @app.get("/students/{student_id}") 23 | def get_student(student_id): # Since we did not use annotations by default we are getting string 24 | global studentID 25 | studentID = student_id 26 | try: 27 | student_id = int(student_id) 28 | except: # General Exception Catching 29 | return "Enter Integers Only" 30 | 31 | try: 32 | if student_id >= 1000 and student_id < 9999: 33 | return f"Hey {student_id} how are you?" 34 | else: 35 | raise ValueError 36 | except ValueError: 37 | return "Enter an id between 1000 and 9999" 38 | 39 | # @app.get("/students/{student_id}") #using pydantic constraints 40 | # def get_student(student_id: int): # FastAPI automatically validates the type 41 | # if 1000 <= student_id < 9999: 42 | # return {"message": f"Your id: {student_id} is valid"} 43 | # else: 44 | # return {"error": "Enter an ID between 1000 and 9999"} 45 | 46 | def true_false_parser(condition: str): 47 | if condition.capitalize(): 48 | return True 49 | elif not condition.capitalize(): 50 | return False 51 | 52 | 53 | @app.get("/students") 54 | def grades_and_session( include_grades:str = False, semester: Optional[str] = None): 55 | if semester is not None: 56 | x = re.search("^(Fall|Spring|Summer|Winter)\d{4}$", semester) # returns None if not match is found 57 | 58 | if x is None: 59 | if str(include_grades) not in ['true', 'True', 'False', 'false']: 60 | raise HTTPException(status_code=422, detail="include_grades can only be a boolean value") 61 | else: 62 | include_grades = true_false_parser(include_grades) 63 | if include_grades: 64 | student_dict = {"student_id": studentID, "grades": {'subject 1': 'empty by default'}} 65 | return student_dict 66 | 67 | elif not include_grades: 68 | student_dict = {"student_id": studentID} 69 | return student_dict 70 | 71 | elif x.string == semester: 72 | if str(include_grades) not in ['true', 'True', 'False', 'false']: 73 | raise HTTPException(status_code=422, detail="include_grades can only be a boolean value") 74 | else: 75 | include_grades = true_false_parser(include_grades) 76 | print(include_grades) 77 | if include_grades: 78 | print("true", include_grades) 79 | student_dict = {"student_id": studentID, "grades": {'subject 1': 'empty by default'}, 80 | 'semester': semester} 81 | return student_dict 82 | 83 | elif not include_grades: 84 | student_dict = {"student_id": studentID, 'semester': semester} 85 | return student_dict 86 | 87 | elif semester is None: 88 | if str(include_grades) not in ['true', 'True', 'False', 'false']: 89 | raise HTTPException(status_code=422, detail="include_grades can only be a boolean value") 90 | else: 91 | include_grades = bool(include_grades) 92 | if include_grades: 93 | student_dict = {"student_id": studentID, "grades": {'subject 1': 'empty by default'}, 94 | 'semester': semester} 95 | return student_dict 96 | 97 | elif not include_grades: 98 | student_dict = {"student_id": studentID, 'semester': semester} 99 | return student_dict 100 | 101 | 102 | ''' 103 | just the learning code 104 | class Blog(Enum): 105 | short = "short" 106 | story = "story" 107 | howto = "howto" 108 | 109 | @app.get("/blog/type/{blog_type}") 110 | def get_blog_type(blog_type: Blog): 111 | return {"message": f"success {blog_type.value} blog fetched"} 112 | 113 | @app.get("/search") 114 | def show_results(search_query): # similar to https://www.google.com/search?q=what 115 | return {"showed": f"results for {search_query}"} # this type of http request is being sent 116 | # http://127.0.0.1:8000/search?search_query=hello 117 | 118 | ''' 119 | 120 | 121 | if __name__ == "__main__": 122 | import uvicorn 123 | uvicorn.run(app, host="127.0.0.1", port=8000) 124 | 125 | -------------------------------------------------------------------------------- /Assignments/FastAPI Assignments/Assignment _ University Registration Form API/README.md: -------------------------------------------------------------------------------- 1 | ### **Assignment 1: University Registration Form API** 2 | 3 | #### **Objective**: 4 | Build a FastAPI application to simulate a university registration system. This API will validate user inputs (path, query, and body parameters) based on specific constraints and provide appropriate error messages if validations fail. 5 | 6 | #### **Requirements**: 7 | You are required to implement an API with the following endpoints and constraints: 8 | 9 | --- 10 | 11 | ### **Endpoints** 12 | 13 | #### 1. **Get Student Information** 14 | - **Endpoint**: `GET /students/{student_id}` 15 | - **Path Parameter**: 16 | - `student_id`: An integer greater than `1000` and less than `9999`. 17 | - **Query Parameters**: 18 | - `include_grades`: A boolean (true/false) to specify if the grades should be included. 19 | - `semester`: An optional string of the format `Fall2024`, `Spring2025`, etc. (Pattern: `^(Fall|Spring|Summer)\d{4}$`). 20 | 21 | --- 22 | 23 | #### 2. **Register Student** 24 | - **Endpoint**: `POST /students/register` 25 | - **Body Parameters**: 26 | - `name`: A string (1-50 characters), must contain only alphabets and spaces. 27 | - `email`: A valid email address. 28 | - `age`: An integer between 18 and 30. 29 | - `courses`: A list of strings with course names (minimum 1 course, maximum 5 courses). 30 | - **Constraints**: 31 | - Each course name should be between 5-30 characters. 32 | - Duplicate course names are not allowed. 33 | - **Example Request**: 34 | ```json 35 | { 36 | "name": "John Doe", 37 | "email": "john.doe@example.com", 38 | "age": 22, 39 | "courses": ["Mathematics", "Physics", "Chemistry"] 40 | } 41 | ``` 42 | 43 | --- 44 | 45 | #### 3. **Update Student Email** 46 | - **Endpoint**: `PUT /students/{student_id}/email` 47 | - **Path Parameter**: 48 | - `student_id`: An integer greater than `1000` and less than `9999`. 49 | - **Body Parameter**: 50 | - `email`: A valid email address. 51 | - **Example Request**: 52 | ```json 53 | { 54 | "email": "new.email@example.com" 55 | } 56 | ``` 57 | 58 | --- 59 | 60 | ### **Validation Requirements** 61 | 1. **Path Parameters**: 62 | - Use Pydantic constraints to enforce the valid range for `student_id`. 63 | - Raise a 422 HTTP error with a message if the `student_id` is invalid. 64 | 65 | 2. **Query Parameters**: 66 | - Validate the semester format and ensure `include_grades` is a boolean. 67 | - If invalid, return a 422 HTTP error with an explanation. 68 | 69 | 3. **Body Parameters**: 70 | - Validate all fields using Pydantic models. 71 | - Return clear error messages for: 72 | - Missing fields. 73 | - Invalid email formats. 74 | - Names that contain non-alphabetic characters. 75 | - Ages that are out of the range. 76 | - Course lists that exceed the size limit or contain duplicates. 77 | 78 | --- 79 | 80 | ### **Deliverables** 81 | 1. FastAPI project folder containing: 82 | - `main.py`: Contains all endpoints and their logic. 83 | - Validation logic implemented using Pydantic models and FastAPI constraints. 84 | - Proper error messages for validation failures. 85 | 2. **Postman Collection**: 86 | - Export and share a Postman collection to test all endpoints. 87 | 88 | --- 89 | 90 | ### **Bonus Points**: 91 | - Add a middleware to log incoming requests. 92 | - Add documentation (using Swagger) with clear examples for each endpoint. 93 | - Implement a feature to save data to an in-memory database (like a Python dictionary). 94 | 95 | --- 96 | 97 | - Submit https://forms.gle/xJJpuVZW3kEesGcJ8 -------------------------------------------------------------------------------- /Assignments/README.md: -------------------------------------------------------------------------------- 1 | ### Python Assignment Questions 2 | 3 | These are the books I used to learn and practice programming concepts: 4 | 5 | Smarter Way to Learn Python: # Learn it faster. Remember it longer by Mark Myers 6 | 7 | The book is structured with short, digestible chapters that focus on building small concepts. I learned and practiced syntax through each chapter, and the exercises at the end of every section helped me reinforce and improve my understanding of the material. This book had had 4-6 chapters for a small concept i.e if it taught conditionals i had 7 chapters that really taught me in detail. 8 | 9 | Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming by Eric Matthes 10 | 11 | After learning and practicing syntax from the first book, I delved deeper into the concepts and theories with this one. It significantly strengthened my programming skills and taught me how to think like a programmer. The book’s practical approach was more detailed than the previous one, and I made sure to take notes in the Obsidian app to reinforce my learning. Mind you Obsidian really is better than many note taking apps and it's better than making notes on register that you would never check again. Here's a guide to obsidian if you're interested: https://www.youtube.com/watch?v=QgbLb6QCK88 12 | 13 | The assignment questions really helped practice and get better at programming gradually 14 | 15 | Assignment 1 16 | 17 |
18 | Part-1 (If Else and Elif) 19 |
20 |
    21 |
  1. Write a program that checks if a given number is positive, negative, or zero.
  2. 22 |
  3. Take a user’s age as input and display whether they are a minor, adult, or senior citizen.
  4. 23 |
  5. Write a program that checks if a given year is a leap year.
  6. 24 |
  7. Take an integer and check if it’s even or odd.
  8. 25 |
  9. Ask the user for a grade percentage and display the corresponding letter grade (A, B, C, D, F).
  10. 26 |
  11. Write a program to find the largest of two numbers.
  12. 27 |
  13. Write a program to find the largest of three numbers.
  14. 28 |
  15. Create a program that checks if a given string is a palindrome.
  16. 29 |
  17. Take three sides of a triangle as input and check if they form a valid triangle.
  18. 30 |
  19. Write a program to determine if a given character is a vowel or consonant.
  20. 31 |
  21. Check if a given number is a multiple of both 3 and 5.
  22. 32 |
  23. Write a program that takes a temperature in Celsius and checks if it’s freezing, moderate, or hot.
  24. 33 |
  25. Take two numbers and an operator (+, -, x, /) as input and perform the corresponding operation.
  26. 34 |
  27. Check if a year input by the user is a century year.
  28. 35 |
  29. Write a program to check if a number is within a specified range.
  30. 36 |
  31. Take the length of three sides and classify the triangle (equilateral, isosceles, or scalene).
  32. 37 |
  33. Write a program that asks for an integer and checks if it’s divisible by 2, 3, or both.
  34. 38 |
  35. Take a user’s score and determine if they pass or fail (pass if 50 or above).
  36. 39 |
  37. Check if a string input is uppercase, lowercase, or a mix.
  38. 40 |
  39. Create a program that evaluates if an inputted number is prime.
  40. 41 |
42 |
43 | 44 |
45 | Part-2 (Loops) 46 |
47 |
    48 |
  1. Print numbers from 1 to 20 using a for loop.
  2. 49 |
  3. Use a while loop to print even numbers from 1 to 50.
  4. 50 |
  5. Write a program to calculate the sum of all numbers between 1 and 100.
  6. 51 |
  7. Print the multiplication table of a given number.
  8. 52 |
  9. Print all odd numbers between 1 and 100 using a loop.
  10. 53 |
  11. Use a for loop to print each character of a string.
  12. 54 |
  13. Find the factorial of a number using a while loop.
  14. 55 |
  15. Use a for loop to print numbers from 10 down to 1.
  16. 56 |
  17. Write a program to print the first 10 Fibonacci numbers. (Interesting Question)
  18. 57 |
  19. Use a loop to count the number of digits in an integer.
  20. 58 |
  21. Print the reverse of a given number. (Logic can be improved)
  22. 59 |
  23. Print all prime numbers between 1 and 50. (Should be done using # Dijkstra's Prime Number Algorithm, thus logic can be improved)
  24. 60 |
  25. Use nested loops to print a pyramid pattern of *. (Yet to be done)
  26. 61 |
  27. Write a program that breaks the loop when a certain condition is met.
  28. 62 |
  29. Print the sum of even and odd numbers separately up to a given number.
  30. 63 |
  31. Create a program to calculate the sum of the digits of an inputted integer.
  32. 64 |
  33. Write a program that continues to ask for a number until the correct number is guessed.
  34. 65 |
  35. Use a loop to print numbers in reverse order within a given range.
  36. 66 |
  37. Use a for loop to print the square of each number from 1 to 10.
  38. 67 |
  39. Create a program that simulates a countdown timer starting from a given number down to zero. (Interesting Question)
  40. 68 |
69 |
70 | 71 | Assignment 2 72 | 73 |
74 | Part-1 (Basic Function Questions) 75 |
76 |
    77 |
  1. Write a function to calculate the area of a circle given its radius.
  2. 78 |
  3. Create a function that takes two numbers and returns their sum.
  4. 79 |
  5. Write a function to find the factorial of a number using recursion (This one needs to be practiced)
  6. 80 |
  7. Write a function that takes a string and returns it reversed. (We are using Negative Indexing)
  8. 81 |
  9. Create a function to check if a given number is prime.
  10. 82 |
  11. Write a function to count the vowels in a given string.
  12. 83 |
84 |
85 | 86 |
87 | Part-2 (Intermediate Function Questions) 88 |
89 |
    90 |
  1. Create a function that takes a list of numbers and returns the largest number.
  2. 91 |
  3. Write a function to find the nth Fibonacci number using recursion. (Recursion is hard concept to master)
  4. 92 |
  5. Write a function to check whether a string is a palindrome.
  6. 93 |
  7. Create a function that takes a list of integers and returns the sum of all even numbers.
  8. 94 |
  9. Write a function to calculate the GCD (Greatest Common Divisor) of two numbers.
  10. 95 |
  11. Create a function that accepts a dictionary and returns the key with the highest value.
  12. 96 |
97 |
98 | 99 |
100 | Part-3 (Advanced Function Questions) 101 |
102 |
    103 |
  1. Write a function that calculates the power of a number without using the ** operator.
  2. 104 |
  3. Create a function that converts a given temperature from Celsius to Fahrenheit and vice versa.
  4. 105 |
  5. Write a function to flatten a nested list.
  6. 106 |
  7. Create a function to check if two strings are anagrams.(Yet to be done, because logic is quite complex)
  8. 107 |
  9. Write a function that takes a list and removes all duplicate elements.
  10. 108 |
  11. Create a function that takes a string and counts the frequency of each character.
  12. 109 |
110 |
111 | 112 |
113 | Part-4 (Real-world Scenarios) 114 |
115 |
    116 |
  1. Write a function that takes a list of employee salaries and calculates the average salary.
  2. 117 |
  3. Create a function to generate a random password of given length, containing uppercase, lowercase, numbers, and special characters (Interesting and Useful)
  4. 118 |
119 |
120 | 121 | Assignment 3 122 |

123 | This section contains 30 Problems 124 |
125 |
126 | Part-1 (Basic Operations) 127 |
128 |
    129 |
  1. Create a dictionary student with keys: name, age, and grade. Assign them appropriate values.
  2. 130 |
  3. Access the value of the key grade in the student dictionary.
  4. 131 |
  5. Add a new key city to the student dictionary and set its value to "New York".
  6. 132 |
  7. Update the value of the age key in the student dictionary to 20.
  8. 133 |
  9. Remove the key city from the student dictionary.
  10. 134 |
135 |
136 | 137 |
138 | Part-2 (Iterating through Dictionaries) 139 |
140 |
    141 |
  1. Iterate through the dictionary student and print all keys.
  2. 142 |
  3. Iterate through the dictionary student and print all values.
  4. 143 |
  5. Iterate through the dictionary student and print all key-value pairs in the format key: value.
  6. 144 |
  7. Check if the key grade exists in the student dictionary and print True or False.
  8. 145 |
  9. Count the total number of keys in the student dictionary.
  10. 146 |
147 |
148 | 149 |
150 | Part-3 (Advanced Dictionary Usage) 151 |
152 |
    153 |
  1. 154 | Merge the following two dictionaries and print the result: 155 |
    156 | dict1 = {'a': 1, 'b': 2}  
    157 | dict2 = {'c': 3, 'd': 4}
    158 | 
    159 |
  2. 160 |
  3. Create a dictionary from a list of tuples: [('name', 'Alice'), ('age', 25), ('city', 'Paris')].
  4. 161 |
  5. Sort the keys of the dictionary {'z': 1, 'a': 2, 'c': 3} in ascending order and print the sorted dictionary. 162 |
  6. Reverse the dictionary {'a': 1, 'b': 2, 'c': 3} so that keys become values and values become keys.
  7. Write a Python function to check if two dictionaries are identical (contain the same key-value pairs).
  8. 163 |
164 |
165 | 166 |
167 | Part-4 (Nested Dictionaries) 168 |
    169 |
  1. Create a nested dictionary to represent the following data:
    170 | Person:  
    171 |   Name: John  
    172 |   Age: 30  
    173 |   Address:  
    174 |     Street: 123 Elm St  
    175 |     City: Boston  
    176 | 
  2. 177 |
  3. Access the value of the city key in the nested dictionary from the previous question.
  4. 178 |
  5. Add a new key Phone to the nested dictionary with the value "123-456-7890".
  6. 179 |
  7. Delete the Address key from the nested dictionary.
  8. 180 |
  9. Iterate through all the keys in the outermost level of the nested dictionary and print them.
  10. 181 |
182 | 183 |
Part-5 (Applications of Dictionaries) 184 |
  1. Use a dictionary to count the occurrences of each word in the string:"hello world hello python world"
  2. 185 |
  3. Write a Python program to find the key with the maximum value in the dictionary: {'a': 10, 'b': 15, 'c': 7}.
  4. 186 |
  5. Create a dictionary to map numbers 1 to 5 to their squares (e.g., {1: 1, 2: 4, 3: 9, ...} ).
  6. Write a Python program to remove duplicate values from the dictionary: `{'a': 10, 'b': 15, 'c': 10, 'd': 15}`.
  7. Write a Python function that accepts a dictionary and a key, and returns the value associated with the key. If the key doesn’t exist, return "Key not found".
187 | 188 |
Part-6 (Challenging Problems) 189 |
190 |
  1. Given two dictionaries dict1 = {'a': 5, 'b': 10} and dict2 = {'a': 3, 'b': 7}, write a Python program to add the values of matching keys and print the result.
  2. Write a Python program to create a dictionary where the keys are the first n positive integers, and the values are their cubes. Take n as user input.
  3. Flatten the following nested dictionary into a single-level dictionary:
    {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}}
  4. Write a Python program to split a dictionary into two dictionaries based on whether the values are odd or even.
  5. Create a dictionary comprehension to filter out all keys in {'a': 1, 'b': 2, 'c': 3, 'd': 4} where the value is less than 3.
191 | 192 | -------------------------------------------------------------------------------- /Assignments/rename_files.fish: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env fish 2 | 3 | for file in q*.py 4 | set number (string replace .py '' $file) # Remove .py extension 5 | set number (string replace q '' $number) # Remove 'q' prefix 6 | mv "$file" "Conditional Statements Q$number.py" 7 | end 8 | -------------------------------------------------------------------------------- /Getting Started with Git Uploading Code on Github/Day 1 - Intro to Git, Version Control and Github/README.md: -------------------------------------------------------------------------------- 1 | # What is Git and What is Github 2 | 3 | We learnt to use commands git add, push, commit and pull. 4 | 5 | ### What is Git? 6 | 7 | Git is an open source technology that Linus Torvalds made while developing the Linux Kernel after a proprietary distributed VCS failed him. Don't confuse it with #github as it's and open source technology while github is an for profit company owned by Microsoft. Github is a distributed version control system. 8 | 9 | #### Core Functionalities of Git when it was being developed were: 10 | 11 | - Speed 12 | - Simplicity 13 | - Non-Linear 14 | - Distributed 15 | - Large 16 | 17 | This is a video that helped me along the way to practice and learn github commands: 18 | 19 | https://youtu.be/mJ-qvsxPHpY 20 | 21 | ### What is Version Control? 22 | 23 | It is a system made to track code changes over time so we can recall specific versions later. Version control systems are known as VCS. VCS can help us see who made a specific change in the code that is causing a problem and can help us revert back to previous version of a code base if we made a problem. 24 | 25 | 26 | 27 | 28 | ![](https://i.imgur.com/7jgX0dP.png) 29 | 30 | 31 | From my GitHub account i changed value of variable current_deployement in my flask project. 32 | 33 | ### Types of Version Control Systems 34 | 35 | There are three types of version control systems namely: 36 | 37 | ### Local Version Control Systems 38 | 39 | Earlier people would copy the same project at different places to keep record of changes or maybe date it. But this wasn't as effective to deal with programmers came up with local version control systems that had a simple database to keep track of changes. One example was RCS. 40 | 41 | ##### Advantages: 42 | 43 | - Simplicity: Easy to use and understand. 44 | - Speed: Operations are very fast as everything is on the local machine. 45 | - Offline Access: No need for network access, allowing for work without an internet connection. 46 | - Reduced Complexity: Less infrastructure and fewer dependencies compared to distributed systems. 47 | 48 | ##### Disadvantages: 49 | 50 | - Limited Collaboration: Difficult to collaborate with multiple developers, as changes are not easily shared. 51 | - Single Point of Failure: If the local machine fails, all version history and changes could be lost. 52 | - Limited History: Typically stores limited history, making it harder to track long-term project evolution. 53 | - Redundancy Issues: Multiple copies of projects can lead to confusion and wasted storage space. 54 | ### Centralized Version Control Systems 55 | 56 | Multiple developers need to work on same project so local VCS weren't a good option. All developers viewed the project at a specific time stamp from one central server. It also provided views that would show who did what and admins had control over who can view/edit what parts of the code. This however was risky aswell as complete code was a single server and if server was down for some time no one would be able to commit code changes. Another risk was if data in the server's storage becomes corrupt and people don't have the complete code with them this would result in a huge loss. 57 | ##### Advantages: 58 | 59 | - Enhanced Collaboration: Multiple developers can work on the same project simultaneously with updates and changes available to everyone in real-time. 60 | - Access Control: Administrators can manage permissions, controlling who can view and edit specific parts of the code. 61 | - Centralized Backup: A single, central repository simplifies backups and management. 62 | - Consistent State: Ensures all developers are working with the most recent version of the code base. 63 | 64 | ##### Disadvantages: 65 | 66 | - Single Point of Failure: If the central server goes down, no one can commit changes, and work can be halted. 67 | - Server Vulnerability: Data corruption or loss on the central server can lead to significant project setbacks if backups are not properly maintained. 68 | - Network Dependency: Requires network access to commit and update code, limiting offline work capabilities. 69 | - Scalability Issues: May struggle with performance and reliability as the number of users and size of the project grows. 70 | ### Distributed Version Control Systems 71 | 72 | In Distributed VCS like #github #Mercurial #Darcs #gist clients (users, developers in this case) can check out latest version of the code spanshot but they can also fully download the repository including full history. So if data is lost or server goes does it full copy can be restored back. Furthermore, many of these systems deal pretty well with having several remote repositories they 73 | can work with, so you can collaborate with different groups of people in different ways simultaneously within the same project. This allows you to set up several types of workflows that aren’t possible in centralized systems, such as hierarchical models. 74 | -------------------------------------------------------------------------------- /Getting Started with Git Uploading Code on Github/Day 2 - Making Repository and Uploading Changes, Cloning Repo/README.md: -------------------------------------------------------------------------------- 1 | # Cloning a GitHub Repository (Repo) 2 | 3 | When it comes to GitHub a repository or repo means the same thing a repository is like a folder we created online instead of locally. A repo had the added ability of being able to be traceable meaning any changes i make be it code, directory or addition or removal of a file it is all tracked by git. 4 | 5 | ![](https://i.imgur.com/iIIwkGw.png) 6 | 7 | We can clone a repository by first copying it's URL from the blue code button. 8 | Then in command prompt (cmd) or any terminal we have to type: 9 | 10 | `git clone repo URL` 11 | 12 | or 13 | 14 | In this case: 15 | 16 | `git clone https://github.com/shery7310/AI-and-Data-Science-Python-Saylani-Mass-IT.git` 17 | 18 | **Remember You Do Not need to be signed in just to clone a repository** 19 | 20 | # Creating a Repository 21 | 22 | Using GUI you can create a repository just by clicking on the plus (+) button next to your GitHub Profile Picture 23 | 24 | ![](https://i.imgur.com/rUdriRz.png) 25 | 26 | Then after this you are shown a page like this: 27 | 28 | ![](https://i.imgur.com/BdcClKB.png) 29 | 30 | Be sure to make a meaningful name and description. If you want your teacher to check your repository make sure it's Public, but if you want to keep some code or something personal use Private option. A README file is an md file which you can use to write detailed description or another post like this one. 31 | 32 | # Making Changes to a repository and Account Sign In 33 | 34 | Before Making any changes to our GitHub repo we need to sign In and there are a number of ways to do that on Windows you might need to install GitHub Desktop App and that will authorize you to make changes to your GitHub repo either you install GitHub Desktop or Not you will have to sign in to your account, here's how you can do that: 35 | 36 | `git config --global user.name "your name"` 37 | `git config --global user.email "your email"` 38 | 39 | Sign In with the email and password for GitHub 40 | 41 | Let's say you have created a GitHub repository and have also cloned it this means that for your repository you have both a local and an online or global version. Local being the directory you cloned and online being the repo you created on GitHub. 42 | 43 | By default your repo only has a README.md file inside. 44 | 45 | Github allows us to edit code files for example.py file or add a text file (.txt) or even add another directory and it will track the changes with messages, and we can see those message/commits later and even undo those if needed. 46 | 47 | Let's say I added a text file called learning.txt locally and this is how i can add it to my GitHub Repository: 48 | 49 | Since we are assuming that we cloned the repo locally we do not need to run `git init`, so follow these steps: 50 | 51 | 1. `git add learning.txt` 52 | 53 | this means we are adding the newly added(changed) file to online repo, for other files it can be like: 54 | 55 | `git add filename` 56 | 57 | We can however also write `git add .` this will add everything different from the previous version of the repo to tracking 58 | 59 | Then after we have added the file this means it is in staging area but still not being tracked with a message, so now we need to commit, this is how we commit: 60 | 61 | 2. `git commit -m "Added Text File"` here Added Text File is a message that we have saved to later remember why we did this. 62 | 63 | Then after committing we have essentially saved the version history or changes history locally now we need to push it to the online repository to do that we do: 64 | 65 | 3. `git push origin main` 66 | 67 | This will push everything to the default branch called main. We will study branches later which is an advanced concept. 68 | 69 | # What if we made changes online and want to bring them to local repo? 70 | 71 | If we made changes online let's say changed some content in README.md or any text file we have in any repo, we need to pull everything and our local and online repo must be on the same level. To do that we can do: 72 | 73 | `git pull` 74 | 75 | **If you too got the PERSONAL TOKEN ISSUE GO THIS REPO: https://github.com/shery7310/AI-and-Data-Science-Python-Saylani-Mass-IT/tree/main/Day%203%20-%20Personal%20Access%20Token** 76 | -------------------------------------------------------------------------------- /Getting Started with Git Uploading Code on Github/Day 3 - Personal Access Token/Assignment No. 2 Create 5 Github Repos/README.md: -------------------------------------------------------------------------------- 1 | # Assignment # 2 2 | 3 | 1. Create 5 GitHub repositories. 4 | 2. Clone these repositories to your local computer. 5 | 3. Make changes to the files on your local computer. 6 | 4. Push the changes back to GitHub. 7 | 5. Make additional changes directly on GitHub (in the cloud). 8 | 6. Pull these cloud changes back to your local computer. -------------------------------------------------------------------------------- /Getting Started with Git Uploading Code on Github/Day 3 - Personal Access Token/README.md: -------------------------------------------------------------------------------- 1 | # How to Obtain Github Personal Access Token and how to commit changes to repo using the personal access token ? 2 | 3 | #### Obtaining Personal Access Token: 4 | 5 | 1. Click on your GitHub Profile Picture and Open Settings 6 | 2. Then from settings scroll down to the bottom of the page and click on Developer Settings 7 | 3. From Developer settings select Personal Access Token: 8 | ![](https://i.imgur.com/vdyOmY4.png) 9 | 4. Select Tokens (Classic) and Generate New Token, give it any name and any duration of validity. 10 | 11 | # Authenticating Personal Access Token 12 | 13 | Let's say you have cloned a repo that belongs to you locally. Now you need to push some files to the online repo, you need to use your OBTAINED personal access token. 14 | 15 | First you need to remove Origin you can do that using: 16 | 17 | 1. `git remote remove origin` 18 | 19 | Then you need to add personal token and a new origin try following this pattern: 20 | 21 | 2. `git remote add origin https://[TOKEN]@github.com/[REPO-OWNER]/[REPO-NAME]` 22 | 23 | Your username is your GitHub Username and the token can be something like: 24 | `yydsiudsdsfbds` 25 | And you repo name can be like sample-repo so this is how your command will look like: 26 | 27 | `git remote add origin https://yydsiudsdsfbds@github.com/shery7310/sample-repo` 28 | 29 | Remember username is repo owner. 30 | 31 | Then you can push anything using: 32 | 33 | 4. `git push origin main` 34 | 35 | -------------------------------------------------------------------------------- /Leetcode Chronicles and Adventures/Missing Number Leetcode 268.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | # Any number can be missing 4 | # https://leetcode.com/problems/missing-number/description/ 5 | # Time Complexity of my Solution: https://i.imgur.com/ejkMIIY.png 6 | 7 | class Solution: 8 | def missingNumber(self, nums: List[int]) -> int: 9 | num_for_loop = -1 10 | nums = sorted(nums) 11 | for num in nums: 12 | num_for_loop += 1 13 | if num_for_loop == num: 14 | if num_for_loop == nums[-1]: 15 | return num + 1 16 | continue 17 | elif num_for_loop != num: 18 | missing_num = num - 1 19 | return missing_num 20 | 21 | li = [9,6,4,2,3,5,7,0,1] 22 | sol = Solution() 23 | result = sol.missingNumber(li) 24 | print(result) 25 | 26 | # These are some more cases we can check this against: 27 | ''' 28 | [0,1] 29 | [3,0,1] 30 | [0, 1, 3, 4, 5, 7, 9, 10, 11] 31 | ''' 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Leetcode Chronicles and Adventures/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Leetcode Chronicles and Adventures/Star-Pattern-Programs-To-Practice-Loops/Numbered Rectangle.py: -------------------------------------------------------------------------------- 1 | """ 2 | 1 2 3 4 5 6 7 8 9 10 3 | 2 4 6 8 10 12 14 16 18 20 4 | 3 6 9 12 15 18 21 24 27 30 5 | 4 8 12 16 20 24 28 32 36 40 6 | 5 10 15 20 25 30 35 40 45 50 7 | 6 12 18 24 30 36 42 48 54 60 8 | 7 14 21 28 35 42 49 56 63 70 9 | 8 16 24 32 40 48 56 64 72 80 10 | 9 18 27 36 45 54 63 72 81 90 11 | 10 20 30 40 50 60 70 80 90 100 12 | 13 | 10 numbers in each row starting 14 | Each Row starts from 1 more than previous one in the col 15 | """ 16 | count = 1 17 | for row in range(1, 11): # will run loop 10 times, representing 10 rows 18 | for col in range(1, 11): # this means run loop 10 time for each iteration of outer loop 19 | print(col * count, end=" ") # count = 1 at start, col = 1 2 3 4 5 6 7 8 9 10 for each iteration 20 | # whereas count keeps increasing 21 | # for example in 2nd iteration count = 2, so each col value i.e. 1 2 3 ... is multiplied by 2 22 | # at 3rd iteration each col value is multiplied by 3 23 | print() 24 | count += 1 -------------------------------------------------------------------------------- /Leetcode Chronicles and Adventures/Star-Pattern-Programs-To-Practice-Loops/Numbered Reversed Right Angle Triangle.py: -------------------------------------------------------------------------------- 1 | """ 2 | 1 2 3 4 5 6 3 | 1 2 3 4 5 4 | 1 2 3 4 5 | 1 2 3 6 | 1 2 7 | 1 8 | """ 9 | 10 | col_num = 7 # After all inner loop iterations run 11 | # we need to reduce the number of times inner loop runs 12 | for rows in range(1, 7): # outer loop represents number of rows 13 | for col in range(1,col_num): #inner loop represent number of columns 14 | print(col, end=" ") # in first iteration this runs from 1 to 6 15 | # in the second it runs from 1 to 5 and then so on 16 | print() # after 6 is printed it means all internal loop iterations have 17 | # successfully ran for first iteration of outer loop, so print() 18 | # takes the control to the next line 19 | col_num -= 1 # after all inner iterations are completed for an iteration 20 | # col_num is reduced so next time inner loop has to run 21 | # 1 number less than the previous number of iterations 22 | 23 | 24 | -------------------------------------------------------------------------------- /Leetcode Chronicles and Adventures/Star-Pattern-Programs-To-Practice-Loops/Numbered Right Angle Triangle.py: -------------------------------------------------------------------------------- 1 | """ 2 | 1 3 | 1 2 4 | 1 2 3 5 | 1 2 3 4 6 | 1 2 3 4 5 7 | """ 8 | 9 | for row in range(1, 6): # row = 1 in first iteration 10 | for col in range(1, row + 1): # col = 1 in first iteration 11 | print(col, end=" ") # 1 is printed and internal loop runs the number of row for example 12 | # if col = 2 the printing starts from 1 then goes to 2 13 | # if col = 3 the printing starts from 1 then goes to 2 then goes to 3 14 | # this keeps happening until row reaches 6 and outer loop terminates 15 | print() # this print() runs after a set of iterations of inner loop complete 16 | 17 | -------------------------------------------------------------------------------- /Leetcode Chronicles and Adventures/Star-Pattern-Programs-To-Practice-Loops/Pyramid Star RIght Angled.py: -------------------------------------------------------------------------------- 1 | """ 2 | * 3 | * * 4 | * * * 5 | * * * * 6 | * * * * * 7 | """ 8 | 9 | 10 | rows = 5 # number of rows 11 | k = 2 * rows - 2 # at row 5 it's 10 - 2 which is 8 12 | for row in range(0, rows): 13 | for space in range(k): 14 | # this will print " " 8 times for first iteration 15 | print(end=" ") 16 | k = k - 2 # after first iteration k = 6, after second k = 4 and so on 17 | for sym in range(row + 1): # in first iteration this will run as 1 time, then 2 time, then 3 time and so on 18 | print("* ", end="") # first time it will print *, then second time it will print * * and so on 19 | print() # after loop runs like this 1 time, 2 times, 3 times, 4 times and 5 times after each run 20 | # we need the pointer to go to next line so we use print() in outer main loop 21 | -------------------------------------------------------------------------------- /Leetcode Chronicles and Adventures/Star-Pattern-Programs-To-Practice-Loops/README.md: -------------------------------------------------------------------------------- 1 | ### I practiced these pattern problems using Pynative's detailed Guide 2 | 3 | Here's the blog post: 4 | 5 | https://pynative.com/print-pattern-python-examples/ 6 | ### Star and Number Patterns Using Python 7 | Number and Star Patterns help us understand and practice nested loops and we can also get better at dynamic programming using these. 8 | Here we have a number of pattern that one must be able to dry run to get good at loops. Here's how these help: 9 | ### 1. Understanding Nested Loops: 10 | 11 | - **Patterns (Number or Star):** Creating patterns like stars (`*`) or numbers requires the use of nested loops. Each level of the pattern often corresponds to an outer loop (rows) and an inner loop (columns). 12 | - Practicing such patterns strengthens your ability to: 13 | - Visualize how nested loops interact. 14 | - Control the flow of execution in loops. 15 | - Manage indices effectively. 16 | 17 | ### 2. Dry-Running the Logic: 18 | 19 | - Patterns force you to carefully analyze how variables change at each iteration, encouraging you to dry-run the code mentally or on paper. 20 | - This practice improves debugging skills and logical thinking, which are critical for writing clean and efficient code. 21 | 22 | ### 3. Link to Dynamic Programming (DP): 23 | 24 | - **Pattern Recognition:** Patterns in star or number problems can help build a mindset for recognizing repetitive sub problems, which is the foundation of dynamic programming. 25 | - **Loop Optimization:** Since DP often involves nested loops (e.g., filling out a grid or table), understanding patterns can help you optimize iterations for time and space complexity. 26 | 27 | ### 4. Skill Transfer-ability: 28 | 29 | - While star and number patterns may seem trivial, the logic-building process directly translates to real-world scenarios like: 30 | - Generating graphical outputs. 31 | - Working with matrices and grids. 32 | - Designing algorithms for problems in DP, where similar iterations are used. 33 | 34 | These are the Questions I did: 35 | ## Numbered Rectangle Pattern 36 | 37 | ``` 38 | 1 2 3 4 5 6 7 8 9 10 39 | 2 4 6 8 10 12 14 16 18 20 40 | 3 6 9 12 15 18 21 24 27 30 41 | 4 8 12 16 20 24 28 32 36 40 42 | 5 10 15 20 25 30 35 40 45 50 43 | 6 12 18 24 30 36 42 48 54 60 44 | 7 14 21 28 35 42 49 56 63 70 45 | 8 16 24 32 40 48 56 64 72 80 46 | 9 18 27 36 45 54 63 72 81 90 47 | 10 20 30 40 50 60 70 80 90 100 48 | ``` 49 | ## Numbered Reversed Right Angle Triangle 50 | 51 | ``` 52 | 1 2 3 4 5 6 53 | 1 2 3 4 5 54 | 1 2 3 4 55 | 1 2 3 56 | 1 2 57 | 1 58 | ``` 59 | 60 | ## Numbered Right Angle Triangle 61 | 62 | ``` 63 | 1 64 | 1 2 65 | 1 2 3 66 | 1 2 3 4 67 | 1 2 3 4 5 68 | ``` 69 | 70 | ## Pyramid Star Right Angled 71 | 72 | ![](https://i.imgur.com/uyKKQYF.png) 73 | 74 | ## Star Pyramid 75 | 76 | ![](https://i.imgur.com/IHtX21A.png) 77 | 78 | ## Star Triangle 79 | 80 | ![](https://i.imgur.com/rHhWksI.png) 81 | -------------------------------------------------------------------------------- /Leetcode Chronicles and Adventures/Star-Pattern-Programs-To-Practice-Loops/Star Pyramid.py: -------------------------------------------------------------------------------- 1 | """ 2 | * 3 | *** 4 | ***** 5 | ******* 6 | 7 | 3 spaces at start and 3 after the first star, we need to print 1 star 8 | 2 spaces at the start for 2nd row of stars, we need to print 3 stars 9 | 1 space at the start for 3rd row, we need to print 5 stars 10 | no space in the last row, we need to print 7 stars 11 | """ 12 | space_count = 3 # in each row number of spaces are getting reduced that's why we need this variable 13 | num = 0 # in each row the number of star is increasing by two from the previous one 14 | 15 | for row in range(1, 5): # We need 4 rows so we run this 4 times 16 | spaces = ' ' * space_count # a new string of spaces is made each time loop restarts 17 | print(spaces, end="") # in the first iteration 3 spaces are added to the start of stars 18 | # and then the end doesn't take the flow to the next line 19 | # instead the * in next line of code will start printing from spaces 20 | print('*' * (row + num)) # in first iteration row = 1 and num = 0 so * is printed 1 time 21 | # in the second iteration row = 2 and num = 1, 2 + 1 = 3 so 3 * are printed 22 | num += 1 # after each print statement value of num increases by 1 23 | space_count -= 1 # after each print statement value of space_count decreases by 1 24 | 25 | # Another logic using two nested loops 26 | spaces = 3 27 | for row in range(1, 8, 2): # 1 3 5 7 28 | 29 | # loop for spaces 30 | for space in range(spaces): 31 | print(" ", end="") 32 | spaces -= 1 33 | 34 | # loop for * pattern 35 | for _ in range(row): # will iterate run 0 to 4 times fetching values 1 3 5 7 36 | # as it's an internal loop it will run them times the value in row variable 37 | print("*", end="") # after each run we override end argument so that flow doesn't go to next line 38 | 39 | print() # to take flow to next line 40 | -------------------------------------------------------------------------------- /Leetcode Chronicles and Adventures/Star-Pattern-Programs-To-Practice-Loops/Star Traingle.py: -------------------------------------------------------------------------------- 1 | """ 2 | * 3 | * * 4 | * * * 5 | * * * * 6 | * * * * * 7 | """ 8 | 9 | for row in range(1, 6): # we need 6 rows 10 | print(('*' + " ") * row, end="\n") # after each * we add a space after it, 11 | # The * is printed times the row. if row is 2 the * is printed * times 12 | # after a pattern of * is printed in a row \n in end takes it to the next line 13 | 14 | -------------------------------------------------------------------------------- /Leetcode Chronicles and Adventures/fibonacci_series_using_loops.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fib(self, n: int) -> int: 3 | a, b = 0, 1 4 | if n <=1: 5 | return n 6 | else: 7 | for _ in range(n): 8 | result = a + b 9 | a = b 10 | b = result 11 | return a 12 | 13 | # you need to create an object and pass it an index to run it -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Artifical Intelligence and Data Science Course by Saylani Mass IT Training Institute (SMIT) - Saylani-AI-Batch2 (Faisalabad) 2 | 3 | This course is being taught by [Sir Ahmed Jajja](https://github.com/Ahmadjajja) and [this](https://github.com/Ahmadjajja/AI_n_DataScience) is the original repository that my instructor created on 1st of October 2024. This is an Advance Artificial Intelligent and Data Science Course the Saylani Welfare is teaching for absolutely free 4 | 5 | This is a course aimed at absolute beginners and I say this as a student of Saylani that it's better than even paid courses by institutes in Pakistan. Saylani is offering this absolutely free, the course is worth hundreds of dollars and they are making careers out of students. The instructor who is the first teacher of this course has been a Section Leader at Standford's code in Place and a number of other international hackathons is determined to make us grind in Leetcode, he has also Co-Founded a Software House and also worked as Full Stack Developer. 6 | 7 |

8 | Artificial Intelligence and Data Science using Python 9 |

10 | 11 | ## Artificial Intelligence Course Duration 12 | This is a one-year program designed for absolute beginners who are passionate about Artificial Intelligence and Data Science. Preparing Pakistan for the new era of computing driven by the rise of AI. 13 | 14 | #### How can students benefit from this? 15 | 16 | If you're eager to learn Python, you can explore the assignments folder and try solving the questions on your own. If you're unable to complete a question, you can refer to the solutions I've provided. This AI program covers skills such as Data Science, Machine Learning, and Deep Learning. You'll always find code examples and solutions available in my repository. 17 | 18 | ## AI and Data Science Proposed Course Outline: 19 | 20 | ### Git and GitHub 21 | 22 | - Version control basics 23 | - Collaborating on projects using GitHub 24 | 25 | ### Python Programming 26 | 27 | - Core Python Syntax and Concepts 28 | - Object-Oriented Programming Approach 29 | - Writing Clean and Efficient Code 30 | 31 | ### Grinding Leetcode 32 | 33 | - How to get really good at data structures 34 | - How to get win hackathons and gain international exposure 35 | 36 | ### FastAPI/Flask 37 | 38 | - Building RESTful APIs with FastAPI or Flask 39 | 40 | ### Database Design and Implementation Using PostgreSQL 41 | 42 | ### Langchain LLM (GPTs, Gemini) 43 | 44 | - Understanding Large Language Models (LLMs) 45 | - Implementing LLMs for various applications 46 | 47 | ### Prerequisite Math Basics 48 | 49 | - Some Math Topics will be taught so students can get better at Mathematics necessary for Machine Learning 50 | 51 | ### Libraries and Tools: 52 | 53 | - Scikit-learn: Machine Learning library for classical models 54 | - NumPy & Pandas: Data Manipulation and Analysis 55 | - Matplotlib: Data Visualization 56 | - TensorFlow (Keras) & PyTorch: Deep Learning Frameworks 57 | 58 | ### Docker 59 | 60 | - Containerization Concepts 61 | - Deploying Applications using Docker 62 | 63 | ### Cloud Platforms 64 | 65 | - Introduction to Cloud Computing 66 | - Deploying and Managing Applications on Cloud Platforms 67 | -------------------------------------------------------------------------------- /Setting Up Virtual Enviroments and using Poetry/README.md: -------------------------------------------------------------------------------- 1 | This is a guide to help you install poetry and virtual environment which is required for poetry to run on any system. For the Windows portion of this guide to work you need to activate Scripts using windows Powershell and use Windows Powershell. You also need to globally install poetry and venv in your system. We will discuss these steps in detail below. 2 | 3 | You can download and install latest version of Powershell from [here](https://github.com/powershell/powershell/releases), make sure you select the correct version i.e. `x64`, `msi` or `exe` which ever you prefer. 4 | # What is a virtual environment in Python? 5 | 6 | ### What is a package and what are package managers? 7 | 8 | Before understanding what a virtual environment is, we must first know what a package and a package manager are in the context of Python. In Python, a package is essentially another term for a library or framework. Python packages are collections of modules that bundle together code to provide specific functionality, making it easier to organize and reuse code across different projects. Each package in Python can have specific versions and a package can he have dependencies meaning that package will not run without those packages. 9 | 10 | A package manager is a tool that helps us download packages from Python Package Index (PyPi) which is like a software repository but instead of GitHub the code is available on this website: https://pypi.org/. The default package manager used by Python Developers is called pip, but before using a package manager Python Documentation suggests that we create a virtual environment. 11 | 12 | A virtual environment in Python provides an isolated space where you can install and manage Python packages independently of the global Python installation. This allows you to create a self-contained directory for each specific project, ensuring that the dependencies and libraries utilized in one project do not conflict with those in another. In essence, it helps maintain a clean and organized development setup, promoting seamless collaboration and project management. Also some packages in Python can be really heavy so it's best to install them in a separate virtual environment rather than installing system wide and then after we are done with developing or running that specific project we can delete that environment. 13 | 14 | ### Looking for Packages and their specific versions 15 | 16 | Whenever we search for any package such as Numpy or Fastapi any search engine such as Brave Search Engine or Google will bring in results from the PyPi website which again in Python Package Index. For example if we search something like install fastapi we will be redirected to this page: 17 | 18 | https://pypi.org/project/fastapi/ and we will see something like: 19 | 20 | ![](https://i.imgur.com/YZr4zDO.png) 21 | 22 | Let's say we want to use an older version of fastapi as it can be a project requirement we visit the Release History portion of this page and select the version we require i.e. 23 | 24 | ![](https://i.imgur.com/q4GuV89.png) 25 | 26 | If we select version 0.113 and click on it PyPi will suggest us to run this command: pip install fastapi==0.113.0 27 | # How to create a virtual environment? 28 | 29 | #### Activating Scripts on Windows PowerShell 30 | 31 | First we need to ensure that powershell allows us to activate scripts which can be python specific scripts we need to run on our system. First check if Default Execution Policy on your Windows is unrestricted or restricted by running: 32 | 33 | Run PowerShell as administrator and then run: 34 | Get-ExecutionPolicy 35 | 36 | If returns returns Restricted it means that we need to unrestrict the default execution policy but if it returns Unrestricted than your powershell already allows us to run python scripts as we wish. However if it returns AllSigned, Bypass, Default, RemoteSigned, Restricted, Undefined it's best to follow this step: 37 | 38 | If execution policy is restricted we need to run Powershell as administrator and then run this command: 39 | 40 | Set-ExecutionPolicy unrestricted 41 | 42 | When we run this command we will be prompted to enter y, type y and then press enter key. 43 | 44 | ![](https://i.imgur.com/W2gydio.png) 45 | 46 | #### How to create and activate a virtual environment on Windows? 47 | 48 | First we need to open the folder where our Python Code exists, if we don't have a folder we can create that folder and then open it using VS Code or any other IDE such as Pycharm. You can also right-click inside that folder and click on the option Open with Code. 49 | 50 | Now we need to run the terminal of whichever IDE we are using and we will see a path of the root directory. A root directory is the main folder of our python project i.e. 51 | 52 | To open the terminal in Visual Studio Code, click on the **View** tab in the top menu and select **Terminal** from the dropdown options. By default, the integrated terminal in VS Code is configured to use PowerShell as its default shell. This allows you to execute commands and scripts directly within the editor without needing to switch to an external terminal application. 53 | 54 | We will a path like this: 55 | 56 | ![](https://i.imgur.com/g7ZzR2Q.png) 57 | The PS we see at the beginning means PowerShell. 58 | 59 | So our root directory is called **`exp`** and the absolute path of the folder exp is : 60 | 61 | ```C:\Users\box_9\Desktop\exp>``` 62 | 63 | An **absolute path** specifies the full path starting from the root of the file system (in Windows, the root is typically a drive like `C:\`). 64 | 65 | **To create a virtual environment using virtualenv or poetry we need to install these packages globally** 66 | 67 | pip install virtualenv 68 | pip install poetry 69 | 70 | **If any problem comes while installing poetry on windows you can check this gist: https://gist.github.com/Isfhan/b8b104c8095d8475eb377230300de9b0** 71 | 72 | **`virtualenv`** is a Python package used to create and activate isolated virtual environments. Additionally, the **Poetry** package also relies on `virtualenv` to create and manage its virtual environments, ensuring efficient dependency isolation and project management. 73 | 74 | After installing virtualenv globally we need to run this command inside vs code's terminal: 75 | 76 | python -m venv myenv 77 | 78 | Here myenv is the name of the virtual environment but we can also change the name of this environment, let's say i name it fastapi-code 79 | 80 | python -m venv fastapi-code 81 | 82 | When we run any of these commands we will see that a folder will be created in our root directory which will have the name of the environment. and our IDE might ask if we want to change the environment (We need to press Yes) i.e. 83 | 84 | ![](https://i.imgur.com/yGRXnAW.png) 85 | 86 | Now we need to activate the created environment, to activate we need to run: 87 | 88 | fastapi-code\Scripts\activate.ps1 89 | 90 | You can modify this command if your virtual environment has a different name. After running the command, you'll notice that the terminal in your IDE displays the name of the activated environment instead of the default `PS` prompt. For example: 91 | 92 | ![](https://i.imgur.com/mjoUDhK.png) 93 | 94 | ##### Installing and Uninstalling Packages inside `virtualenv` using pip. 95 | 96 | We can run `pip freeze` command to see if the current environment has any packages installed or not, you will not get any output as we have not installed any package onto this newly created environment. Let's say we install numpy inside this virtual environment. 97 | 98 | We just need to type `pip install numpy` and the latest version of this package will be downloaded from PyPi and get installed into the current environment. 99 | 100 | Let's say for some reason we need to uninstall numpy we can run: `pip uninstall numpy` 101 | 102 | This is what we will see in the terminal: 103 | 104 | ![](https://i.imgur.com/nJYcpbd.png) 105 | 106 | ### Mac/Linux Based Operating Systems 107 | 108 | #### How to create and activate a virtual environment on Mac/Linux? Using virtualenv package 109 | 110 | The commands for setting up a virtual environment using virtualenv package are pretty much the same for Mac/Linux. 111 | 112 | First we need to globally install virtualenv and poetry package on our Linux distro, just open terminal and then paste these and press enter: 113 | 114 | pip install virtualenv 115 | pip install poetry 116 | 117 | Note: On some Linux Distributions we might need to run this to install Poetry: 118 |
119 |     curl -sSL https://install.python-poetry.org | python3 -
120 | 
121 | 122 | ##### Then to create and activate a virtualenv on Linux/Mac we can type: 123 | 124 | python -m venv env-name 125 | 126 | Let's say i run this: 127 | 128 | python -m venv venv 129 | 130 | Now when we run the above command we will see that a new folder called venv will be created this folder contains files we need to activate the environment, we must be in root/python project directory and we need to run: 131 | 132 | source venv/bin/activate 133 | 134 | For Fish Shell this command is a bit different: 135 | 136 | . venv/bin/activate.fish 137 | 138 | Now when the environment will be activated we will see the name of the environment at start of the path being shown in terminal. i.e. 139 | 140 | Packages can be installed/uninstalled just by using: 141 | 142 |
143 | pip install numpy
144 | 
145 | pip uninstall numpy
146 | 
147 | 148 | ![](https://i.imgur.com/M1pHEL7.png) 149 | # How to create a poetry virtual environment? 150 | 151 | ### Windows Operating System 152 | 153 | Since Our instructor suggested that we use Poetry for creating and using virtual environments let's see how to create and activate virtual environments using poetry. Poetry needs virtualenv package as a dependency so make sure to pip install virtualenv before trying to use poetry package. 154 | #### Create and Activate a poetry environment 155 | 156 | We need to run this command: 157 | poetry new name-of-environment 158 | 159 | You can replace **`name-of-environment`** with any name you wish to assign to your Poetry environment. In the context of Poetry, the environment's folder is referred to as a **Poetry project**, while in the context of a virtual environment, it is simply called an **environment**. 160 | 161 | Let's say i run this: 162 | 163 | poetry new poetry-env 164 | 165 | As soon as we run this command we will see that a folder called `poetry-env` will be created and this directory is the folder of the virtual environment we have created using poetry. 166 | 167 | ![](https://i.imgur.com/egQs4bu.png) 168 | 169 | #### Changing Poetry Path and Activating Poetry environment 170 | 171 | Now there are two options by default Poetry will place all the environments in a directory like this: `"C:\\user-name\box_9\AppData\Local\pypoetry\Cache"` 172 | 173 | You can check the default cache path for your system using this command: 174 | 175 | poetry config --list 176 | 177 | This means that all your environments will be stored in a separate directory, distinct from the directory we our project exists. You can either leave it as is or configure Poetry to always move environment files into the root directory of your Python projects. The second approach is preferable. 178 | 179 | Here's how to set poetry to always move environment files into root directory, just run: 180 | 181 | poetry config virtualenvs.in-project true 182 | 183 | If we `cd` into the folder of our environment i.e. poetry-env in this case we will see a structure like this: 184 | 185 | ![](https://i.imgur.com/DUSPK0b.png) 186 | 187 | Make sure your IDE terminal is in the environment folder i.e. 188 | 189 | `poetry-env`. After we are in a path like this: Documents/Fastapi/Connecting FastAPI with Mongodb/poetry-env 190 | 191 | We need to run `poetry install` command to create further environment files so we can later activate the environment. 192 | 193 | Now if we see the structure/directories present in our environment folder we can see something like: 194 | 195 | ![](https://i.imgur.com/w86sd4S.png) 196 | 197 | Here we can see that when we ran `poetry install` a folder called .venv was created, it is very similar to to how a virtualenv works as it also places environment activation files in the environment folder. 198 | 199 | To activate environment we can again go 1 step back using `cd ..` our goal here is to be in the root directory or the python project directory. The path shown in IDE's terminal should be like: 200 | 201 | `/Documents/Fastapi/Connecting FastAPI with Mongodb` 202 | 203 | See that we our outside the environment folder now. To activate from here we can run: 204 | 205 | ./poetry-env/.venv/bin/Scripts/activate 206 | 207 | ![](https://i.imgur.com/5t0h2Fp.png) 208 | 209 | If you are not in root directory you will need to set correct directory. 210 | 211 | ### Linux/Mac OS 212 | 213 | The commands to create a poetry environment are similar Windows and Linux Based Operating Systems such as GNU Linux and Mac OS. The only difference is how we activate a poetry environment i.e. 214 | 215 | source poetry-env/.venv/bin/activate 216 | 217 | For Fish Shell: 218 | 219 | source poetry-env/.venv/bin/activate.fish 220 | 221 | #### Installing Packages onto poetry environment and checking their versions 222 | 223 | To install any package using poetry we can run pip install commands but we should stick poetry's own [documentation](https://python-poetry.org/docs/managing-environments/#powershell) which suggests we use: 224 | 225 | poetry add name-of-package 226 | i.e. poetry add fastapi 227 | 228 | To check if the package and all it's dependencies have successfully installed we can run: 229 | 230 | poetry show we will see an output like this: 231 | 232 | ![](https://i.imgur.com/8Yil9Ag.png) 233 | 234 | ## Running a fastapi server using both virtualenv and poetry (Any Operating System) 235 | 236 | ##### virtualenv 237 | 238 | In case of virtualenv we can use pip to install uvicorn and fastapi i.e. 239 | 240 | ```python3 241 | pip install fastapi 242 | pip install uvicorn 243 | ``` 244 | 245 | ##### poetry 246 | 247 | ```python3 248 | poetry add fastapi 249 | poetry add uvicorn 250 | ``` 251 | 252 | Now to run a fast api server in virtualenv or poetry environment we need to paste this code into any python file in my case the file is called randomcode.py 253 | 254 | ```python3 255 | from fastapi import FastAPI 256 | 257 | # Create an instance of the FastAPI class 258 | app = FastAPI() 259 | 260 | # Define a root route 261 | @app.get("/") 262 | async def read_root(): 263 | return {"message": "hello, world!"} 264 | 265 | if __name__ == "__main__": 266 | import uvicorn 267 | uvicorn.run(app, host="127.0.0.1", port=8000) 268 | ``` 269 | 270 | To simply run this code for fast api we need to run this command in IDE's terminal: 271 | 272 | uvicorn main:app --reload 273 | 274 | As soon as we run this our fastapi server will be up and running at 127.0.0.1 IP which is also known as localhost and the port will be 8000. 275 | For a more detailed approach to understand this code we can check out [KDNuggets](https://www.kdnuggets.com/beginners-guide-to-fastapi) and it is a better approach to follow fastapi's official [documentation](https://fastapi.tiangolo.com/tutorial/first-steps/) as fastapi is well-known for having a good documentation. 276 | -------------------------------------------------------------------------------- /Setting Up Virtual Enviroments and using Poetry/README_original_copy.md: -------------------------------------------------------------------------------- 1 | This is a guide to help you install poetry and virtual environment which is required for poetry to run on any system. For the Windows portion of this guide to work you need to activate Scripts using windows Powershell and use Windows Powershell. You also need to globally install poetry and venv in your system. We will discuss these steps in detail below. 2 | 3 | # What is a virtual environment in Python? 4 | 5 | ### What is a package and what are package managers? 6 | 7 | Before understanding what a virtual environment is, we must first know what a package and a package manager are in the context of Python. In Python, a package is essentially another term for a library or framework. Python packages are collections of modules that bundle together code to provide specific functionality, making it easier to organize and reuse code across different projects. Each package in Python can have specific versions and a package can he have dependencies meaning that package will not run without those packages. 8 | 9 | A package manager is a tool that helps us download packages from Python Package Index (PyPi) which is like a software repository but instead of GitHub the code is available on this website: https://pypi.org/. The default package manager used by Python Developers is called pip, but before using a package manager Python Documentation suggests that we create a virtual environment. 10 | 11 | A virtual environment in Python provides an isolated space where you can install and manage Python packages independently of the global Python installation. This allows you to create a self-contained directory for each specific project, ensuring that the dependencies and libraries utilized in one project do not conflict with those in another. In essence, it helps maintain a clean and organized development setup, promoting seamless collaboration and project management. Also some packages in Python can be really heavy so it's best to install them in a separate virtual environment rather than installing system wide and then after we are done with developing or running that specific project we can delete that environment. 12 | 13 | ### Looking for Packages and their specific versions 14 | 15 | Whenever we search for any package such as Numpy or Fastapi any search engine such as Brave Search Engine or Google will bring in results from the PyPi website which again in Python Package Index. For example if we search something like install fastapi we will be redirected to this page: 16 | 17 | https://pypi.org/project/fastapi/ and we will see something like: 18 | 19 | ![](https://i.imgur.com/YZr4zDO.png) 20 | 21 | Let's say we want to use an older version of fastapi as it can be a project requirement we visit the Release History portion of this page and select the version we require i.e. 22 | 23 | ![](https://i.imgur.com/q4GuV89.png) 24 | 25 | If we select version 0.113 and click on it PyPi will suggest us to run this command: pip install fastapi==0.113.0 26 | # How to create a virtual environment? 27 | 28 | ### Windows Operating System 29 | 30 | #### Activating Scripts on Windows PowerShell 31 | 32 | First we need to ensure that powershell allows us to activate scripts which can be python specific scripts we need to run on our system. First check if Default Execution Policy on your Windows is unrestricted or restricted by running: 33 | 34 | Run PowerShell as administrator and then run: 35 | Get-ExecutionPolicy 36 | 37 | If returns returns Restricted it means that we need to unrestrict the default execution policy but if it returns Unrestricted than your powershell already allows us to run python scripts as we wish. However if it returns AllSigned, Bypass, Default, RemoteSigned, Restricted, Undefined it's best to follow this step: 38 | 39 | If execution policy is restricted we need to run Powershell as administrator and then run this command: 40 | 41 | Set-ExecutionPolicy unrestricted 42 | 43 | When we run this command we will be prompted to enter y, type y and then press enter key. 44 | 45 | ![](https://i.imgur.com/W2gydio.png) 46 | 47 | #### How to create and activate a virtual environment on Windows? 48 | 49 | First we need to open the folder where our Python Code exists, if we don't have a folder we can create that folder and then open it using VS Code or any other IDE such as Pycharm. You can also right-click inside that folder and click on the option Open with Code. 50 | 51 | Now we need to run the terminal of whichever IDE we are using and we will see a path of the root directory. A root directory is the main folder of our python project i.e. 52 | 53 | To open the terminal in Visual Studio Code, click on the **View** tab in the top menu and select **Terminal** from the dropdown options. By default, the integrated terminal in VS Code is configured to use PowerShell as its default shell. This allows you to execute commands and scripts directly within the editor without needing to switch to an external terminal application. 54 | 55 | We will a path like this: 56 | 57 | ![](https://i.imgur.com/g7ZzR2Q.png) 58 | The PS we see at the beginning means PowerShell. 59 | 60 | So our root directory is called **`exp`** and the absolute path of the folder exp is : 61 | 62 | ```C:\Users\box_9\Desktop\exp>``` 63 | 64 | An **absolute path** specifies the full path starting from the root of the file system (in Windows, the root is typically a drive like `C:\`). 65 | 66 | **To create a virtual environment using virtualenv or poetry we need to install these packages globally** 67 | 68 | pip install virtualenv 69 | pip install poetry 70 | 71 | **If any problem comes while installing poetry on windows you can check this gist: https://gist.github.com/Isfhan/b8b104c8095d8475eb377230300de9b0** 72 | 73 | **`virtualenv`** is a Python package used to create and activate isolated virtual environments. Additionally, the **Poetry** package also relies on `virtualenv` to create and manage its virtual environments, ensuring efficient dependency isolation and project management. 74 | 75 | After installing virtualenv globally we need to run this command inside vs code's terminal: 76 | 77 | python -m venv myenv 78 | 79 | Here myenv is the name of the virtual environment but we can also change the name of this environment, let's say i name it fastapi-code 80 | 81 | python -m venv fastapi-code 82 | 83 | When we run any of these commands we will see that a folder will be created in our root directory which will have the name of the environment. and our IDE might ask if we want to change the environment (We need to press Yes) i.e. 84 | 85 | ![](https://i.imgur.com/yGRXnAW.png) 86 | 87 | Now we need to activate the created environment, to activate we need to run: 88 | 89 | fastapi-code\Scripts\activate.ps1 90 | 91 | You can modify this command if your virtual environment has a different name. After running the command, you'll notice that the terminal in your IDE displays the name of the activated environment instead of the default `PS` prompt. For example: 92 | 93 | ![](https://i.imgur.com/mjoUDhK.png) 94 | 95 | ##### Installing and Uninstalling Packages inside `virtualenv` using pip. 96 | 97 | We can run `pip freeze` command to see if the current environment has any packages installed or not, you will not get any output as we have not installed any package onto this newly created environment. Let's say we install numpy inside this virtual environment. 98 | 99 | We just need to type `pip install numpy` and the latest version of this package will be downloaded from PyPi and get installed into the current environment. 100 | 101 | Let's say for some reason we need to uninstall numpy we can run: `pip uninstall numpy` 102 | 103 | This is what we will see in the terminal: 104 | 105 | ![](https://i.imgur.com/nJYcpbd.png) 106 | 107 | ### Mac/Linux Based Operating Systems 108 | 109 | #### How to create and activate a virtual environment on Mac/Linux? 110 | 111 | # How to create a poetry virtual environment? 112 | 113 | ### Windows Operating System 114 | 115 | Since Our instructor suggest that we use Poetry for creating and using virtual environments let's see how to create and activate virtual environments using poetry. Poetry needs virtualenv package as a dependency so make sure to pip install virtualenv before trying to use poetry package. 116 | 117 | #### Create and Activate a poetry environment 118 | 119 | We need to run poetry new name-of-environment 120 | 121 | You can replace **`name-of-environment`** with any name you wish to assign to your Poetry environment. In the context of Poetry, the environment's folder is referred to as a **Poetry project**, while in the context of a virtual environment, it is simply called an **environment**. 122 | 123 | Let's say i run this: 124 | 125 | poetry new poetry-env 126 | 127 | As soon as we run this command we will see that a folder called poetry-env will be created and this directory is the folder of the virtual environment we have created using poetry. 128 | 129 | ![](https://i.imgur.com/egQs4bu.png) 130 | 131 | #### Changing Poetry Path and Activating Poetry environment 132 | 133 | Now there are two options by default Poetry will place all the environments in a directory like this: `"C:\\user-name\box_9\AppData\Local\pypoetry\Cache"` 134 | 135 | You can check the default cache path for your system using this command: 136 | 137 | poetry config --list 138 | 139 | This means that all your environments will be stored in a separate directory, distinct from the root directory we created. You can either leave it as is or configure Poetry to always move environment files into the root directory of your Python projects. The second approach is preferable. 140 | 141 | Here's how to set poetry to always move environment files into root directory, just run: 142 | 143 | poetry config virtualenvs.in-project true 144 | 145 | Now to activate the environment make sure you have already changed directory to the correct one, meaning your IDE terminal must point to the poetry environment folder i.e. poetry-env in our case, if you are however in the root directory for some reason you can change directory using `cd` command. 146 | 147 | To activate command we need to run (assuming you are in root directory): 148 | 149 | .venv/Scripts/activate.ps1 150 | 151 | ![](https://i.imgur.com/5t0h2Fp.png) 152 | 153 | If you are not in root directory you will need to set correct directory. 154 | 155 | #### Installing Packages onto poetry environment and checking their versions 156 | 157 | To install any package using poetry we can run pip install commands but we should stick poetry's own [documentation](https://python-poetry.org/docs/managing-environments/#powershell) which suggests we use: 158 | 159 | poetry add name-of-package 160 | i.e. poetry add fastapi 161 | 162 | To check if the package and all it's dependencies have successfully installed we can run: 163 | 164 | poetry show we will see an output like this: 165 | 166 | ![](https://i.imgur.com/8Yil9Ag.png) 167 | 168 | ## Running a fastapi server using both virtualenv and poetry (Any Operating System) 169 | 170 | ##### virtualenv 171 | 172 | In case of virtualenv we can use pip to install uvicorn and fastapi i.e. 173 | 174 | ```python3 175 | pip install fastapi 176 | pip install uvicorn 177 | ``` 178 | 179 | ##### poetry 180 | 181 | ```python3 182 | poetry add fastapi 183 | poetry add uvicorn 184 | ``` 185 | 186 | Now to run a fast api server in virtualenv or poetry environment we need to paste this code into any python file in my case the file is called randomcode.py 187 | 188 | ```python3 189 | from fastapi import FastAPI 190 | 191 | # Create an instance of the FastAPI class 192 | app = FastAPI() 193 | 194 | # Define a root route 195 | @app.get("/") 196 | async def read_root(): 197 | return {"message": "hello, world!"} 198 | 199 | if __name__ == "__main__": 200 | import uvicorn 201 | uvicorn.run(app, host="127.0.0.1", port=8000) 202 | ``` 203 | 204 | To simply run this code for fast api we need to run this command in IDE's terminal: 205 | 206 | uvicorn main:app --reload 207 | 208 | As soon as we run this our fastapi server will be up and running at 127.0.0.1 IP which is also known as localhost and the port will be 8000. 209 | For a more detailed approach to understand this code we can check out [KDNuggets](https://www.kdnuggets.com/beginners-guide-to-fastapi) and it is a better approach to follow fastapi's official [documentation](https://fastapi.tiangolo.com/tutorial/first-steps/) as fastapi is well-known for having a good documentation. 210 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | AI-and-Data-Science-Python-Saylani-Mass-IT-SMIT 6 | 7 | 8 | 9 | 10 | 11 |

Artifical Intelligence and Data Science Course by Saylani Mass IT Training Institute (SMIT) - Saylani-AI-Batch2 (Faisalabad)

12 | 13 |

This course is being taught by Sir Ahmed Jajja and this is the original repository that my instructor created on 1st of October 2024. This is an Advance Artificial Intelligent and Data Science Course the Saylani Welfare is teaching for absolutely free

14 | 15 |

This is a course aimed at absolute beginners and I say this as a student of Saylani that it's better than even paid courses by institutes in Pakistan. Saylani is offering this absolutely free, the course is worth hundreds of dollars and they are making careers out of students. The instructor who is the first teacher of this course has been a Section Leader at Standford's code in Place and a number of other international hackathons is determined to make us grind in Leetcode, he has also Co-Founded a Software House and also worked as Full Stack Developer.

16 | 17 |

18 | Artificial Intelligence and Data Science using Python 19 |

20 | 21 |

Artificial Intelligence Course Duration

22 | 23 |

This is a one-year program designed for absolute beginners who are passionate about Artificial Intelligence and Data Science. Preparing Pakistan for the new era of computing driven by the rise of AI.

24 |

Visit the Artificial Intelligence and Data Science Repo here: 25 | GitHub Repository 26 |

27 |

How can students benefit from this?

28 | 29 |

If you're eager to learn Python, you can explore the assignments folder and try solving the questions on your own. If you're unable to complete a question, you can refer to the solutions I've provided. This AI program covers skills such as Data Science, Machine Learning, and Deep Learning. You'll always find code examples and solutions available in my repository.

30 | 31 |

AI and Data Science Proposed Course Outline:

32 | 33 |

Git and GitHub

34 | 35 | 39 | 40 |

Python Programming

41 | 42 | 47 | 48 |

Grinding Leetcode

49 | 50 | 54 | 55 |

FastAPI/Flask

56 | 57 | 60 | 61 |

Database Design and Implementation Using PostgreSQL

62 | 63 |

Langchain LLM (GPTs, Gemini)

64 | 65 | 69 | 70 |

Prerequisite Math Basics

71 | 72 | 75 | 76 |

Libraries and Tools:

77 | 78 | 84 | 85 |

Docker

86 | 87 | 91 | 92 |

Cloud Platforms

93 | 94 | 98 | 99 | 100 | 101 | --------------------------------------------------------------------------------