├── A number is a perfect number ├── Access Set Items.py ├── Boolean Values.py ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Check_armstrong.py ├── Count Total Number.py ├── Electricity Bill.py ├── Face Detection ├── face_detect_cam.py ├── haar_face.xml └── readme.md ├── Find Sum of 10 Numbers.py ├── Find the length.py ├── First Digit.py ├── GCD of Two.py ├── Inorder.py ├── Iterators.py ├── LICENSE ├── Lambda.py ├── Leap year Program.py ├── Logic Operator.py ├── Make a Simple Calculator.py ├── Nunmber_Guessing_Game_Python.py ├── ODE_NN.py ├── Postorder.py ├── Preorder.py ├── Prime or not.py ├── Profit or Loss.py ├── Python Calendar.py ├── Pythonmatrixtwo.py ├── README.md ├── Random.py ├── RegEx.py ├── Remove Punctuation ├── Replace Characters.py ├── Right Triangle Alphabets.py ├── STRINGCONCT.PY ├── Seconded.py ├── Solve Quadratic Equation ├── Swap the first and last elements.py ├── Tic_Tac_Toe.py ├── Transpose a Matrix.py ├── Waterjug.py ├── Web_Scraping_with_BeatifulSoup.py ├── __pycache__ └── numpy.cpython-39.pyc ├── a Module.py ├── accesselement.py ├── all Prime numbers in an Interval.py ├── appenditem.py ├── bfs.py ├── cal.py ├── casting.py ├── castinginpython.py ├── checkifitemexist.py ├── classandobject.py ├── cmath.acos ├── custom_exceptions.py ├── dfs.py ├── dictionaries.py ├── dublicate.py ├── elseif.py ├── exception.py ├── fisrspy.py ├── from 1 to N ├── guess-the-number.py ├── heatmap ├── heatmap.py ├── hellobunny.py ├── inheritance.py ├── insertitem.py ├── johsn.py ├── lambda.py ├── largest.py ├── leapyear_or_not.py ├── line_intersection.py ├── list.py ├── listdataype.py ├── listlength.py ├── literla.py ├── loop.py ├── matplotlib.py ├── matrix.py ├── modules.py ├── n-th Fibonacci number.py ├── nqueens.py ├── numpy1.py ├── nympy.py ├── palindrumreverse.py ├── power of funct.py ├── prog1.py ├── pty.py ├── pygame ├── alien.png ├── background.wav ├── bg.png ├── bullet.png ├── explosion.wav ├── laser.wav ├── main.py ├── requirements.txt ├── si.png └── space.png ├── pymid-python pyramid ├── python.py ├── pythonlambda.py ├── pythonuserinput.py ├── rangeindex.py ├── rangeofneg.py ├── readfile.py ├── repaclingst.py ├── scope.py ├── set.py ├── simplecal.py ├── simplecalulatorinpython.py ├── simplepyexample.py ├── slacingstring.py ├── stack.py ├── string_slicing.py ├── stringformation.py ├── table-of-a-number ├── thistuple.py ├── toh.py ├── try.py ├── tryexception.py ├── tuples.py ├── variable.py └── water_reminder.py /A number is a perfect number: -------------------------------------------------------------------------------- 1 | # Python3 code to check if a given 2 | # number is perfect or not 3 | 4 | # Returns true if n is perfect 5 | def isPerfect( n ): 6 | 7 | # To store sum of divisors 8 | sum = 1 9 | 10 | # Find all divisors and add them 11 | i = 2 12 | while i * i <= n: 13 | if n % i == 0: 14 | sum = sum + i + n/i 15 | i += 1 16 | 17 | # If sum of divisors is equal to 18 | # n, then n is a perfect number 19 | 20 | return (True if sum == n and n!=1 else False) 21 | 22 | # Driver program 23 | print("Below are all perfect numbers till 10000") 24 | n = 2 25 | for n in range (10000): 26 | if isPerfect (n): 27 | print(n , " is a perfect number") 28 | 29 | # This code is contributed by "Sharad_Bhardwaj". 30 | -------------------------------------------------------------------------------- /Access Set Items.py: -------------------------------------------------------------------------------- 1 | thisset = {"apple", "banana", "cherry"} 2 | 3 | for x in thisset: 4 | print(x) 5 | -------------------------------------------------------------------------------- /Boolean Values.py: -------------------------------------------------------------------------------- 1 | x = "Hello" 2 | y = 15 3 | 4 | print(bool(x)) 5 | print(bool(y)) 6 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | https://github.com/suman-shah/. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | welcome to open source project for absolute begineer 2 | 3 | Please go through following step by step process to contribute in this project 4 | 5 | This is c++ programming examples projects here we need to follow these steps 6 | 7 | step1: give a star to this project(optional) 8 | 9 | step2: click on fork button on top right wait few second for completing forking of this project 10 | 11 | step3: click on add new file button and select create new file or upload file option 12 | 13 | step4: give a suitable name of your file and write a complete example 14 | 15 | step5: commit yours file 16 | 17 | step6: click contribute button and click on create pull request option and click on create pull request and finally click on commit 18 | 19 | Congratulation ! 20 | 21 | Note: please do not submit same example which are all ready available use diffrent name of your file too 22 | 23 | Link: https://github.com/suman-shah/python-example- 24 | -------------------------------------------------------------------------------- /Check_armstrong.py: -------------------------------------------------------------------------------- 1 | '''def evenSumPrefix(file): 2 | f=open(file,'r') 3 | r=f.readlines() 4 | s=0 5 | a=[int(i) for i in r] 6 | for j in a: 7 | s=s+j 8 | if s%2==0: 9 | return True 10 | else: 11 | return False 12 | 13 | print(evenSumPrefix("t1.txt")) 14 | ''' 15 | def armstrong(n): 16 | z=len(str(n)) 17 | d=0 18 | e=n 19 | while n!=0: 20 | d+=(n%10)**z 21 | n=n//10 22 | if d==e: 23 | return True 24 | else: 25 | return False 26 | import sys 27 | 28 | m=sys.argv[1:] 29 | print(m) 30 | for i in m: 31 | if armstrong(int(i)): 32 | print('True') 33 | break 34 | else: 35 | print('False') 36 | -------------------------------------------------------------------------------- /Count Total Number.py: -------------------------------------------------------------------------------- 1 | # Python program to Count Total Number of Words in a String 2 | 3 | str1 = input("Please Enter your Own String : ") 4 | total = 1 5 | 6 | for i in range(len(str1)): 7 | if(str1[i] == ' ' or str1 == '\n' or str1 == '\t'): 8 | total = total + 1 9 | 10 | print("Total Number of Words in this String = ", total) 11 | -------------------------------------------------------------------------------- /Electricity Bill.py: -------------------------------------------------------------------------------- 1 | # Python Program to Calculate Electricity Bill 2 | 3 | units = int(input(" Please enter Number of Units you Consumed : ")) 4 | 5 | if(units < 50): 6 | amount = units * 2.60 7 | surcharge = 25 8 | elif(units <= 100): 9 | amount = 130 + ((units - 50) * 3.25) 10 | surcharge = 35 11 | elif(units <= 200): 12 | amount = 130 + 162.50 + ((units - 100) * 5.26) 13 | surcharge = 45 14 | else: 15 | amount = 130 + 162.50 + 526 + ((units - 200) * 8.45) 16 | surcharge = 75 17 | 18 | total = amount + surcharge 19 | print("\nElectricity Bill = %.2f" %total) 20 | -------------------------------------------------------------------------------- /Face Detection/face_detect_cam.py: -------------------------------------------------------------------------------- 1 | import cv2 as cv 2 | import pyautogui as win 3 | 4 | img = cv.VideoCapture(0) 5 | 6 | while True: 7 | isTrue, frame = img.read() 8 | gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) 9 | haar_cascade = cv.CascadeClassifier('haar_face.xml') 10 | faces_rect = haar_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=4) 11 | print(f'{len(faces_rect)} face(s) detected') 12 | faces = f'{len(faces_rect)} face(s)' 13 | 14 | cv.putText(frame, faces, (0,25), cv.FONT_HERSHEY_TRIPLEX, 1.0, (0,0,255), thickness=2) 15 | for (x,y,w,h) in faces_rect: 16 | cv.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), thickness=2) 17 | 18 | cv.imshow('Video',frame) 19 | if cv.waitKey(20) & 0xFF==ord('d') : 20 | break 21 | 22 | img.release() 23 | cv.destroyAllWindows() 24 | -------------------------------------------------------------------------------- /Face Detection/readme.md: -------------------------------------------------------------------------------- 1 | 1. This is face detection project using opencv python. 2 | 2. Make sure that, you have entered the correct cam number in the script (according to your cam setup). 3 | 3. Just run the script. -------------------------------------------------------------------------------- /Find Sum of 10 Numbers.py: -------------------------------------------------------------------------------- 1 | Sum = 0 2 | 3 | print("Please Enter 10 Numbers\n") 4 | for i in range(1, 11): 5 | num = int(input("Number %d = " %i)) 6 | 7 | if num < 0: 8 | break 9 | 10 | Sum = Sum + num 11 | 12 | print("The Sum of Positive Numbers = ", Sum) 13 | -------------------------------------------------------------------------------- /Find the length.py: -------------------------------------------------------------------------------- 1 | # Python3 program to swap first 2 | # and last element of a list 3 | 4 | # Swap function 5 | def swapList(newList): 6 | size = len(newList) 7 | 8 | # Swapping 9 | temp = newList[0] 10 | newList[0] = newList[size - 1] 11 | newList[size - 1] = temp 12 | 13 | return newList 14 | 15 | # Driver code 16 | newList = [12, 35, 9, 56, 24] 17 | 18 | print(swapList(newList)) 19 | -------------------------------------------------------------------------------- /First Digit.py: -------------------------------------------------------------------------------- 1 | # Python Program to find First Digit of a Number 2 | 3 | number = int(input("Please Enter any Number: ")) 4 | 5 | first_digit = number 6 | 7 | while (first_digit >= 10): 8 | first_digit = first_digit // 10 9 | 10 | print("The First Digit from a Given Number {0} = {1}".format(number, first_digit)) 11 | -------------------------------------------------------------------------------- /GCD of Two.py: -------------------------------------------------------------------------------- 1 | a = float(input(" Please Enter the First Value a: ")) 2 | b = float(input(" Please Enter the Second Value b: ")) 3 | 4 | i = 1 5 | while(i <= a and i <= b): 6 | if(a % i == 0 and b % i == 0): 7 | val = i 8 | i = i + 1 9 | 10 | print("\n HCF of {0} and {1} = {2}".format(a, b, val)) 11 | -------------------------------------------------------------------------------- /Inorder.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | 3 | def __init__(self, data): 4 | 5 | self.left = None 6 | self.right = None 7 | self.data = data 8 | # Insert Node 9 | def insert(self, data): 10 | 11 | if self.data: 12 | if data < self.data: 13 | if self.left is None: 14 | self.left = Node(data) 15 | else: 16 | self.left.insert(data) 17 | elif data > self.data: 18 | if self.right is None: 19 | self.right = Node(data) 20 | else: 21 | self.right.insert(data) 22 | else: 23 | self.data = data 24 | 25 | # Print the Tree 26 | def PrintTree(self): 27 | if self.left: 28 | self.left.PrintTree() 29 | print( self.data), 30 | if self.right: 31 | self.right.PrintTree() 32 | 33 | # Inorder traversal 34 | # Left -> Root -> Right 35 | def inorderTraversal(self, root): 36 | res = [] 37 | if root: 38 | res = self.inorderTraversal(root.left) 39 | res.append(root.data) 40 | res = res + self.inorderTraversal(root.right) 41 | return res 42 | 43 | root = Node(27) 44 | root.insert(14) 45 | root.insert(35) 46 | root.insert(10) 47 | root.insert(19) 48 | root.insert(31) 49 | root.insert(42) 50 | print(root.inorderTraversal(root)) 51 | -------------------------------------------------------------------------------- /Iterators.py: -------------------------------------------------------------------------------- 1 | mytuple = ("apple", "banana", "cherry") 2 | myit = iter(mytuple) 3 | 4 | print(next(myit)) 5 | print(next(myit)) 6 | print(next(myit)) 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 suman-shah 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Lambda.py: -------------------------------------------------------------------------------- 1 | x = lambda a, b : a * b 2 | print(x(5, 6)) 3 | -------------------------------------------------------------------------------- /Leap year Program.py: -------------------------------------------------------------------------------- 1 | yr = int(input("Please Enter the Number you wish: ")) 2 | 3 | if (( yr%400 == 0)or (( yr%4 == 0 ) and ( yr%100 != 0))): 4 | print("%d is a Leap year" %yr) 5 | else: 6 | print("%d is Not" %yr) 7 | -------------------------------------------------------------------------------- /Logic Operator.py: -------------------------------------------------------------------------------- 1 | # not, and, or, xor 2 | ''' 3 | Not 4 | ''' 5 | print('===== Not =====\n') 6 | a = True 7 | print('Data a =', not a) 8 | b = False 9 | print('Data b =', not b) 10 | 11 | ''' 12 | And (output will be false if one is false) 13 | ''' 14 | print('\n===== And =====\n') 15 | a = True 16 | b = True 17 | print('Hasil True and True =', a and b) 18 | 19 | a = True 20 | b = False 21 | print('Hasil True and False =', a and b) 22 | 23 | a = False 24 | b = True 25 | print('Hasil False and True =', a and b) 26 | 27 | a = False 28 | b = False 29 | print('Hasil False and False =', a and b) 30 | 31 | ''' 32 | Or (output will be true if one is true) 33 | ''' 34 | print('\n===== Or =====\n') 35 | a = True 36 | b = True 37 | print(a, 'or', b, '=', a or b) 38 | 39 | a = True 40 | b = False 41 | print(a, 'or', b, '=', a or b) 42 | 43 | a = False 44 | b = True 45 | print(a, 'or', b, '=', a or b) 46 | 47 | a = False 48 | b = False 49 | print(a, 'or', b, '=', a or b) 50 | 51 | ''' 52 | Xor (cannot be the same to output true) 53 | ''' 54 | print('\n===== Xor =====\n') 55 | 56 | a = True 57 | b = True 58 | c = a ^ b 59 | print(a, 'xor', b, '=', c) 60 | 61 | a = True 62 | b = False 63 | c = a ^ b 64 | print(a, 'xor', b, '=', c) 65 | 66 | a = False 67 | b = True 68 | c = a ^ b 69 | print(a, 'xor', b, '=', c) 70 | 71 | a = False 72 | b = False 73 | c = a ^ b 74 | print(a, 'xor', b, '=', c) 75 | 76 | -------------------------------------------------------------------------------- /Make a Simple Calculator.py: -------------------------------------------------------------------------------- 1 | 2 | def extract_from_text(text): 3 | 4 | l=[] 5 | 6 | for t in text.split(' '): 7 | 8 | try: 9 | 10 | l.append(float(t)) 11 | 12 | except ValueError: 13 | 14 | pass 15 | 16 | return l 17 | 18 | # calculating LCM 19 | 20 | def lcm(x,y): 21 | 22 | L=x if x>y else y 23 | 24 | while L<=x*y: 25 | 26 | if L%x==0 and L%y==0: 27 | 28 | return L 29 | 30 | L+=1 31 | 32 | # calculating HCF 33 | 34 | def hcf(x,y): 35 | 36 | H=x if x=1: 37 | 38 | if x%H==0 and y%H==0: 39 | 40 | return H 41 | 42 | H-=1 43 | 44 | 45 | 46 | # Addition 47 | 48 | def add(x,y): 49 | 50 | return x+y 51 | 52 | 53 | 54 | # Subtraction 55 | 56 | def sub(x,y): 57 | 58 | return x-y 59 | 60 | 61 | 62 | # Multiplication 63 | 64 | def mul(x,y): 65 | 66 | return x*y 67 | 68 | 69 | 70 | # Division 71 | 72 | def div(x,y): 73 | 74 | return x/y 75 | 76 | 77 | 78 | # Remainder 79 | 80 | def mod(x,y): 81 | 82 | return x%y 83 | 84 | 85 | 86 | # Response to command 87 | 88 | # printing - "Thanks for enjoy with me" on exit 89 | 90 | def end(): 91 | 92 | print(response[2]) 93 | 94 | input('press enter key to exit') 95 | 96 | exit() 97 | 98 | 99 | 100 | def myname(): 101 | 102 | print(response[1]) 103 | 104 | def sorry(): 105 | 106 | print(response[3]) 107 | 108 | 109 | 110 | # Operations - performed on the basis of text tokens 111 | 112 | operations={'ADD':add,'PLUS':add,'SUM':add,'ADDITION':add, 113 | 114 | 'SUB':sub,'SUBTRACT':sub, 'MINUS':sub, 115 | 116 | 'DIFFERENCE':sub,'LCM':lcm,'HCF':hcf, 117 | 118 | 'PRODUCT':mul, 'MULTIPLY':mul,'MULTIPLICATION':mul, 119 | 120 | 'DIVISION':div,'MOD':mod,'REMANDER' 121 | 122 | :mod,'MODULAS':mod} 123 | 124 | 125 | 126 | # commands 127 | 128 | commands={'NAME':myname,'EXIT':end,'END':end,'CLOSE':end} 129 | 130 | 131 | 132 | print('--------------'+response[0]+'------------') 133 | 134 | print('--------------'+response[1]+'--------------------') 135 | 136 | 137 | 138 | while True: 139 | 140 | print() 141 | 142 | text=input('enter your queries: ') 143 | 144 | for word in text.split(' '): 145 | 146 | if word.upper() in operations.keys(): 147 | 148 | try: 149 | 150 | l = extract_from_text(text) 151 | 152 | r = operations[word.upper()] (l[0],l[1]) 153 | 154 | print(r) 155 | 156 | except: 157 | 158 | print('something went wrong going plz enter again !!') 159 | 160 | finally: 161 | 162 | break 163 | 164 | elif word.upper() in commands.keys(): 165 | 166 | commands[word.upper()]() 167 | 168 | break 169 | 170 | else: 171 | 172 | sorry() 173 | 174 | 175 | 176 | Output: 177 | 178 | enter your queries: tell me the LCM of 18,8 179 | 180 | 72 181 | -------------------------------------------------------------------------------- /Nunmber_Guessing_Game_Python.py: -------------------------------------------------------------------------------- 1 | #Make a program in which the computer randomly 2 | #chooses a number between 1 to 10, 1 to 100, or any range. 3 | #Then give users a hint to guess the number. Every time the user guesses wrong, he gets another clue, and his score gets reduced. 4 | #The clue can be multiples, divisible, greater or smaller, or a combination of all. 5 | 6 | import random as r 7 | import math 8 | print(" ********** NUMBER GUESSING GAME ************ ") 9 | print(""" ******** HI WLECOME TO PYTHONVERSE!!! ************ 10 | ******** This is a number guessing game. *********** """) 11 | 12 | print("************ You have 7 chances to guess the number **************") 13 | print("************ If you cannot guess the number in 7 guesses then you will lose the game ***********") 14 | print("************ Maximum score is 7 ***********") 15 | print("********** Please enter your bound for the game to start ********* ") 16 | print("***************************************************************************") 17 | 18 | a=int(input("Enter lower bound of the range in which you want to play the game : ")) 19 | b=int(input("Enter upper bound of the range in which you want to play the game : ")) 20 | random_number = r.randint(a,b) 21 | guess=int(input("Enter the guessed number between " + str(a) +" and "+str(b)+": ")) 22 | score=7 23 | if(guess==random_number): 24 | print("********* CONGRATULATIONS YOU HAVE WON ***************") 25 | print("********* It is a correct guess ******************") 26 | print("********* Your final score is "+str(score)+" *******") 27 | print("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+") 28 | else: 29 | q= (a+b)//2 30 | if(random_numberq): 38 | if(math.isclose(random_number,guess,abs_tol=3)): 39 | print("You are very very very close to the number") 40 | print("The number is greater than "+str(q)) 41 | print("Your score becomes "+str(score-1)) 42 | print("You have "+str(score-1)+" guesses left now ") 43 | print("**********************************************************") 44 | score=score-1 45 | guess=int(input("Enter new guess: ")) 46 | if(guess==random_number): 47 | print("********* CONGRATULATIONS YOU HAVE WON ***************") 48 | print("********* It is a correct guess ******************") 49 | print("********* Your final score is "+str(score)+" *******") 50 | print("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+") 51 | else: 52 | if(math.isclose(random_number,guess,abs_tol=3)): 53 | print("You are very very very close to the number") 54 | print("Your score becomes "+str(score-1)) 55 | print("You have "+str(score-1)+" guesses left now ") 56 | print("**********************************************************") 57 | else: 58 | print("You are not even close to the number ") 59 | print("Your score becomes "+str(score-1)) 60 | print("You have "+str(score-1)+" guesses left now ") 61 | print("**********************************************************") 62 | 63 | score=score-1 64 | guess=int(input("Enter new guess: ")) 65 | if(guess==random_number): 66 | print("********* CONGRATULATIONS YOU HAVE WON ***************") 67 | print("********* It is a correct guess ******************") 68 | print("********* Your final score is "+str(score)+" *******") 69 | print("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+") 70 | else: 71 | if(random_number%2==0): 72 | print("It is an even number") 73 | else: 74 | print("It is an odd number") 75 | if(math.isclose(random_number,guess,abs_tol=3)): 76 | print("You are very very very close to the number") 77 | print("Your score becomes "+str(score-1)) 78 | print("You have "+str(score-1)+" guesses left now ") 79 | print("**********************************************************") 80 | score=score-1 81 | guess=int(input("Enter new guess")) 82 | if(guess==random_number): 83 | print("********* CONGRATULATIONS YOU HAVE WON ***************") 84 | print("********* It is a correct guess ******************") 85 | print("********* Your final score is "+str(score)+" *******") 86 | print("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+") 87 | else: 88 | for i in range(2,random_number+1): 89 | if random_number%i==0: 90 | div=i 91 | break 92 | if(math.isclose(random_number,guess,abs_tol=3)): 93 | print("You are very very very close to the number") 94 | print("The number is divisible by "+str(div)) 95 | 96 | print("Your score becomes "+str(score-1)) 97 | print("You have "+str(score-1)+" guesses left now ") 98 | print("**********************************************************") 99 | score=score-1 100 | guess=int(input("Enter new guess: ")) 101 | if(guess==random_number): 102 | print("********* CONGRATULATIONS YOU HAVE WON ***************") 103 | print("********* It is a correct guess ******************") 104 | print("********* Your final score is "+str(score)+" *******") 105 | print("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+") 106 | else: 107 | count=0 108 | for j in range(2,random_number): 109 | if random_number%j==0: 110 | count+=1 111 | if count>=1: 112 | print("It is a Composite Number") 113 | else: 114 | print("It is a Prime Number") 115 | 116 | if(math.isclose(random_number,guess,abs_tol=3)): 117 | print("You are very very very close to the number") 118 | 119 | print("Your score becomes "+str(score-1)) 120 | print("You have "+str(score-1)+" guesses left now ") 121 | print("**********************************************************") 122 | score=score-1 123 | 124 | guess=int(input("Enter new guess : ")) 125 | if(guess==random_number): 126 | print("********* CONGRATULATIONS YOU HAVE WON ***************") 127 | print("********* It is a correct guess ******************") 128 | print("********* Your final score is "+str(score)+" *******") 129 | print("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+") 130 | else: 131 | for k in range(2,random_number+1): 132 | if(random_number%k==0): 133 | print("The number is a multiple of "+str(k)) 134 | break 135 | if(math.isclose(random_number,guess,abs_tol=3)): 136 | print("You are very very very close to the number") 137 | print("Your score becomes "+str(score-1)) 138 | print("You have "+str(score-1)+" guesses left now ") 139 | print("**********************************************************") 140 | score=score-1 141 | print("It is your last chance to guess the number otherwise you will lose the game") 142 | guess=int(input("Enter new guess: ")) 143 | if(guess==random_number): 144 | print("********* CONGRATULATIONS YOU HAVE WON ***************") 145 | print("********* It is a correct guess ******************") 146 | print("********* Your final score is "+str(score)+" *******") 147 | print("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+") 148 | else: 149 | print("*********** SORRY YOU LOST THE GAME ***********************") 150 | score=score-1 151 | print("*********** The number was : "+str(random_number)+"**********") 152 | print("*********** Your final score is "+str(score)+"***********") 153 | print("**********************************************************") -------------------------------------------------------------------------------- /ODE_NN.py: -------------------------------------------------------------------------------- 1 | import tensorflow.compat.v1 as tf 2 | tf.disable_v2_behavior() 3 | import numpy as np 4 | import math, random 5 | import matplotlib.pyplot as plt 6 | from scipy import special 7 | 8 | # Define the number of outputs and the learning rate 9 | n_input = 1 10 | n_nodes_hl1 = 400 11 | n_nodes_hl2 = 400 12 | n_nodes_hl3 = 500 13 | n_output = 1 14 | learn_rate = 0.00003 15 | 16 | # Boundary Conditions 17 | A = 1 18 | 19 | # training data 20 | N = 1000 21 | a = 0 22 | b = 1 23 | x = np.arange(a, b, (b-a)/N).reshape((N,1)) 24 | y = np.zeros(N) 25 | 26 | # Placeholders 27 | x_ph = tf.placeholder('float', [None, 1],name='input') 28 | y_ph = tf.placeholder('float') 29 | 30 | # number of epochs 31 | n_epochs = 800 32 | 33 | # batchsize per epoch 34 | batch_size= 200 35 | 36 | #validation-data size 37 | n_valid= 400 38 | 39 | # Define standard deviation for initialising weights and biases from normal distribution. 40 | hl_sigma = 0.02 41 | 42 | def neural_network_model(data): 43 | data = tf.cast(data, tf.float32) 44 | hidden_1_layer = {'weights': tf.Variable(tf.random.normal([n_input, n_nodes_hl1],stddev=hl_sigma)), 45 | 'biases': tf.Variable(tf.random.normal([n_nodes_hl1], stddev=hl_sigma))} 46 | hidden_2_layer = {'weights': tf.Variable(tf.random.normal([n_nodes_hl1, n_nodes_hl2], stddev=hl_sigma)), 47 | 'biases': tf.Variable(tf.random.normal([n_nodes_hl2], stddev=hl_sigma))} 48 | output_layer = {'weights': tf.Variable(tf.random.normal([n_nodes_hl2, n_output], stddev=hl_sigma)), 49 | 'biases': tf.Variable(tf.random.normal([n_output], stddev=hl_sigma))} 50 | 51 | 52 | l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases']) 53 | l1 = tf.nn.tanh(l1) 54 | l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases']) 55 | l2 = tf.nn.relu(l2) 56 | output = tf.add(tf.matmul(l2, output_layer['weights']), output_layer['biases'], name='output') 57 | return output 58 | 59 | 60 | def train_neural_network_batch(): 61 | prediction = neural_network_model(x_ph) 62 | pred_dx = tf.gradients(prediction, x_ph) 63 | 64 | u = A + (1-x_ph)*prediction 65 | dudx = -prediction + (1-x_ph)*pred_dx 66 | 67 | cost = tf.reduce_mean(tf.square(dudx + 2*x_ph)) 68 | optimizer = tf.train.AdamOptimizer(learn_rate).minimize(cost) 69 | 70 | with tf.Session() as sess: 71 | sess.run(tf.global_variables_initializer()) 72 | 73 | for epoch in range(n_epochs): 74 | _, l = sess.run([optimizer,cost], feed_dict={x_ph:x, y_ph:y}) 75 | 76 | if(epoch % 100 == 0): 77 | print('loss:-',l,', epoch:-',epoch) 78 | 79 | # Validation 80 | return sess.run(tf.squeeze(prediction),{x_ph:x}), x 81 | 82 | 83 | y_pred,x_pred = train_neural_network_batch() 84 | y_pred = y_pred.reshape(N,1) 85 | u = A+(1-x)*y_pred 86 | plt.plot(x_pred, u,label ='NN') 87 | plt.plot(x_pred, -x_pred*x_pred+2,label ='Analytical') 88 | plt.legend() 89 | plt.show() 90 | -------------------------------------------------------------------------------- /Postorder.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | 3 | def __init__(self, data): 4 | 5 | self.left = None 6 | self.right = None 7 | self.data = data 8 | # Insert Node 9 | def insert(self, data): 10 | 11 | if self.data: 12 | if data < self.data: 13 | if self.left is None: 14 | self.left = Node(data) 15 | else: 16 | self.left.insert(data) 17 | elif data > self.data: 18 | if self.right is None: 19 | self.right = Node(data) 20 | else: 21 | self.right.insert(data) 22 | else: 23 | self.data = data 24 | 25 | # Print the Tree 26 | def PrintTree(self): 27 | if self.left: 28 | self.left.PrintTree() 29 | print( self.data), 30 | if self.right: 31 | self.right.PrintTree() 32 | 33 | # Postorder traversal 34 | # Left ->Right -> Root 35 | def PostorderTraversal(self, root): 36 | res = [] 37 | if root: 38 | res = self.PostorderTraversal(root.left) 39 | res = res + self.PostorderTraversal(root.right) 40 | res.append(root.data) 41 | return res 42 | 43 | root = Node(27) 44 | root.insert(14) 45 | root.insert(35) 46 | root.insert(10) 47 | root.insert(19) 48 | root.insert(31) 49 | root.insert(42) 50 | print(root.PostorderTraversal(root)) 51 | -------------------------------------------------------------------------------- /Preorder.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | 3 | def __init__(self, data): 4 | 5 | self.left = None 6 | self.right = None 7 | self.data = data 8 | # Insert Node 9 | def insert(self, data): 10 | 11 | if self.data: 12 | if data < self.data: 13 | if self.left is None: 14 | self.left = Node(data) 15 | else: 16 | self.left.insert(data) 17 | elif data > self.data: 18 | if self.right is None: 19 | self.right = Node(data) 20 | else: 21 | self.right.insert(data) 22 | else: 23 | self.data = data 24 | 25 | # Print the Tree 26 | def PrintTree(self): 27 | if self.left: 28 | self.left.PrintTree() 29 | print( self.data), 30 | if self.right: 31 | self.right.PrintTree() 32 | 33 | # Preorder traversal 34 | # Root -> Left ->Right 35 | def PreorderTraversal(self, root): 36 | res = [] 37 | if root: 38 | res.append(root.data) 39 | res = res + self.PreorderTraversal(root.left) 40 | res = res + self.PreorderTraversal(root.right) 41 | return res 42 | 43 | root = Node(27) 44 | root.insert(14) 45 | root.insert(35) 46 | root.insert(10) 47 | root.insert(19) 48 | root.insert(31) 49 | root.insert(42) 50 | print(root.PreorderTraversal(root)) 51 | -------------------------------------------------------------------------------- /Prime or not.py: -------------------------------------------------------------------------------- 1 | num = 11 2 | # If given number is greater than 1 3 | if num > 1: 4 | # Iterate from 2 to n / 2 5 | for i in range(2, int(num/2)+1): 6 | # If num is divisible by any number between 7 | # 2 and n / 2, it is not prime 8 | if (num % i) == 0: 9 | print(num, "is not a prime number") 10 | break 11 | else: 12 | print(num, "is a prime number") 13 | else: 14 | print(num, "is not a prime number") 15 | -------------------------------------------------------------------------------- /Profit or Loss.py: -------------------------------------------------------------------------------- 1 | # Python Program to Calculate Profit or Loss 2 | 3 | actual_cost = float(input(" Please Enter the Actual Product Price: ")) 4 | sale_amount = float(input(" Please Enter the Sales Amount: ")) 5 | 6 | if(actual_cost > sale_amount): 7 | amount = actual_cost - sale_amount 8 | print("Total Loss Amount = {0}".format(amount)) 9 | elif(sale_amount > actual_cost): 10 | amount = sale_amount - actual_cost 11 | print("Total Profit = {0}".format(amount)) 12 | else: 13 | print("No Profit No Loss!!!") 14 | -------------------------------------------------------------------------------- /Python Calendar.py: -------------------------------------------------------------------------------- 1 | import calendar 2 | 3 | # ask of month and year 4 | year = int(input("Please Enter the year Number: ")) 5 | month = int(input("Please Enter the month Number: ")) 6 | 7 | print(calendar.month(year, month)) 8 | -------------------------------------------------------------------------------- /Pythonmatrixtwo.py: -------------------------------------------------------------------------------- 1 | # Program to multiply two matrices using nested loops 2 | 3 | # 3x3 matrix 4 | X = [[12,7,3], 5 | [4 ,5,6], 6 | [7 ,8,9]] 7 | # 3x4 matrix 8 | Y = [[5,8,1,2], 9 | [6,7,3,0], 10 | [4,5,9,1]] 11 | # result is 3x4 12 | result = [[0,0,0,0], 13 | [0,0,0,0], 14 | [0,0,0,0]] 15 | 16 | # iterate through rows of X 17 | for i in range(len(X)): 18 | # iterate through columns of Y 19 | for j in range(len(Y[0])): 20 | # iterate through rows of Y 21 | for k in range(len(Y)): 22 | result[i][j] += X[i][k] * Y[k][j] 23 | 24 | for r in result: 25 | print(r) 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python-example- 2 | Python is commonly used for developing websites and software, task automation, data analysis, and data visualization. Since it's relatively easy to learn, Python has been adopted by many non-programmers such as accountants and scientists, for a variety of everyday tasks, like organizing finances. write a python program and create a file 3 | -------------------------------------------------------------------------------- /Random.py: -------------------------------------------------------------------------------- 1 | 2 | import random 3 | random.seed(5) 4 | 5 | print(random.random()) 6 | print(random.random()) 7 | print(random.random()) 8 | -------------------------------------------------------------------------------- /RegEx.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | #Check if the string starts with "The" and ends with "Spain": 4 | 5 | txt = "The rain in Spain" 6 | x = re.search("^The.*Spain$", txt) 7 | 8 | if x: 9 | print("YES! We have a match!") 10 | else: 11 | print("No match") 12 | -------------------------------------------------------------------------------- /Remove Punctuation: -------------------------------------------------------------------------------- 1 | 2 | punc = ‘’’ ! () – [] {} : ; ‘ “ \ , <> . / ? @ # $ % ^ & *_ ‘’’ 3 | 4 | str_1 = input (“Enter the string: “) 5 | 6 | no_punc = “ “ 7 | 8 | for char in str_1: 9 | 10 | if char not in punc: 11 | 12 | no_punc = no_punc + clear 13 | 14 | print (no_punc) 15 | -------------------------------------------------------------------------------- /Replace Characters.py: -------------------------------------------------------------------------------- 1 | # Python program to Replace Characters in a String 2 | 3 | str1 = input("Please Enter your Own String : ") 4 | ch = input("Please Enter your Own Character : ") 5 | newch = input("Please Enter the New Character : ") 6 | 7 | str2 = str1.replace(ch, newch) 8 | 9 | print("\nOriginal String : ", str1) 10 | print("Modified String : ", str2) 11 | -------------------------------------------------------------------------------- /Right Triangle Alphabets.py: -------------------------------------------------------------------------------- 1 | rows = int(input("Enter Right Triangle Alphabets Pattern Rows = ")) 2 | 3 | print("====Right Angled Triangle Alphabets Pattern ====") 4 | 5 | alphabet = 65 6 | 7 | for i in range(0, rows): 8 | for j in range(0, i + 1): 9 | print('%c' %(alphabet + j), end = ' ') 10 | print() 11 | -------------------------------------------------------------------------------- /STRINGCONCT.PY: -------------------------------------------------------------------------------- 1 | a = "Hello" 2 | b = "World" 3 | c = a + " " + b 4 | print(c) 5 | -------------------------------------------------------------------------------- /Seconded.py: -------------------------------------------------------------------------------- 1 | python example 2 | -------------------------------------------------------------------------------- /Solve Quadratic Equation: -------------------------------------------------------------------------------- 1 | 2 | #The following program is used to find out the roots of the quadratic equation 3 | 4 | import math 5 | 6 | def equationroots( x, y, z): 7 | 8 | discri = y * y - 4 * x * z 9 | 10 | sqrtval = math.sqrt(abs(discri)) 11 | 12 | 13 | 14 | # checking condition for discriminant 15 | 16 | if discri > 0: 17 | 18 | print(" real and different roots ") 19 | 20 | print((-y + sqrtval)/(2 * x)) 21 | 22 | print((-y - sqrtval)/(2 * x)) 23 | 24 | 25 | 26 | elif discri == 0: 27 | 28 | print(" real and same roots") 29 | 30 | print(-y / (2 * x)) 31 | 32 | 33 | 34 | # when discriminant is less than 0 35 | 36 | else: 37 | 38 | print("Complex Roots") 39 | 40 | print(- y / (2 * x), " + i", sqrt_val) 41 | 42 | print(- y / (2 * x), " - i", sqrt_val) 43 | 44 | 45 | 46 | # Driver Program 47 | 48 | x = 1 49 | 50 | y = 10 51 | 52 | z = -24 53 | 54 | 55 | 56 | if x == 0: 57 | 58 | print("Input correct quadratic equation") 59 | 60 | 61 | 62 | else: 63 | 64 | equationroots(x, y, z) 65 | 66 | 67 | Output: 68 | 69 | real and different roots 70 | 71 | 2.0 72 | 73 | -12.0 74 | -------------------------------------------------------------------------------- /Swap the first and last elements.py: -------------------------------------------------------------------------------- 1 | # Python3 program to swap first 2 | # and last element of a list 3 | 4 | # Swap function 5 | def swapList(list): 6 | 7 | first = list.pop(0) 8 | last = list.pop(-1) 9 | 10 | list.insert(0, last) 11 | list.append(first) 12 | 13 | return list 14 | 15 | # Driver code 16 | newList = [12, 35, 9, 56, 24] 17 | 18 | print(swapList(newList)) 19 | -------------------------------------------------------------------------------- /Tic_Tac_Toe.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from tkinter import * 4 | import numpy as np 5 | 6 | size_of_board = 600 7 | symbol_size = (size_of_board / 3 - size_of_board / 8) / 2 8 | symbol_thickness = 50 9 | symbol_X_color = '#EE4035' 10 | symbol_O_color = '#0492CF' 11 | Green_color = '#7BC043' 12 | 13 | 14 | class Tic_Tac_Toe(): 15 | # ------------------------------------------------------------------ 16 | # Initialization Functions: 17 | # ------------------------------------------------------------------ 18 | def __init__(self): 19 | self.window = Tk() 20 | self.window.title('Tic-Tac-Toe') 21 | self.canvas = Canvas(self.window, width=size_of_board, height=size_of_board) 22 | self.canvas.pack() 23 | # Input from user in form of clicks 24 | self.window.bind('', self.click) 25 | 26 | self.initialize_board() 27 | self.player_X_turns = True 28 | self.board_status = np.zeros(shape=(3, 3)) 29 | 30 | self.player_X_starts = True 31 | self.reset_board = False 32 | self.gameover = False 33 | self.tie = False 34 | self.X_wins = False 35 | self.O_wins = False 36 | 37 | self.X_score = 0 38 | self.O_score = 0 39 | self.tie_score = 0 40 | 41 | def mainloop(self): 42 | self.window.mainloop() 43 | 44 | def initialize_board(self): 45 | for i in range(2): 46 | self.canvas.create_line((i + 1) * size_of_board / 3, 0, (i + 1) * size_of_board / 3, size_of_board) 47 | 48 | for i in range(2): 49 | self.canvas.create_line(0, (i + 1) * size_of_board / 3, size_of_board, (i + 1) * size_of_board / 3) 50 | 51 | def play_again(self): 52 | self.initialize_board() 53 | self.player_X_starts = not self.player_X_starts 54 | self.player_X_turns = self.player_X_starts 55 | self.board_status = np.zeros(shape=(3, 3)) 56 | 57 | # ------------------------------------------------------------------ 58 | # Drawing Functions: 59 | # The modules required to draw required game based object on canvas 60 | # ------------------------------------------------------------------ 61 | 62 | def draw_O(self, logical_position): 63 | logical_position = np.array(logical_position) 64 | # logical_position = grid value on the board 65 | # grid_position = actual pixel values of the center of the grid 66 | grid_position = self.convert_logical_to_grid_position(logical_position) 67 | self.canvas.create_oval(grid_position[0] - symbol_size, grid_position[1] - symbol_size, 68 | grid_position[0] + symbol_size, grid_position[1] + symbol_size, width=symbol_thickness, 69 | outline=symbol_O_color) 70 | 71 | def draw_X(self, logical_position): 72 | grid_position = self.convert_logical_to_grid_position(logical_position) 73 | self.canvas.create_line(grid_position[0] - symbol_size, grid_position[1] - symbol_size, 74 | grid_position[0] + symbol_size, grid_position[1] + symbol_size, width=symbol_thickness, 75 | fill=symbol_X_color) 76 | self.canvas.create_line(grid_position[0] - symbol_size, grid_position[1] + symbol_size, 77 | grid_position[0] + symbol_size, grid_position[1] - symbol_size, width=symbol_thickness, 78 | fill=symbol_X_color) 79 | 80 | def display_gameover(self): 81 | 82 | if self.X_wins: 83 | self.X_score += 1 84 | text = 'Winner: Player 1 (X)' 85 | color = symbol_X_color 86 | elif self.O_wins: 87 | self.O_score += 1 88 | text = 'Winner: Player 2 (O)' 89 | color = symbol_O_color 90 | else: 91 | self.tie_score += 1 92 | text = 'Its a tie' 93 | color = 'gray' 94 | 95 | self.canvas.delete("all") 96 | self.canvas.create_text(size_of_board / 2, size_of_board / 3, font="cmr 60 bold", fill=color, text=text) 97 | 98 | score_text = 'Scores \n' 99 | self.canvas.create_text(size_of_board / 2, 5 * size_of_board / 8, font="cmr 40 bold", fill=Green_color, 100 | text=score_text) 101 | 102 | score_text = 'Player 1 (X) : ' + str(self.X_score) + '\n' 103 | score_text += 'Player 2 (O): ' + str(self.O_score) + '\n' 104 | score_text += 'Tie : ' + str(self.tie_score) 105 | self.canvas.create_text(size_of_board / 2, 3 * size_of_board / 4, font="cmr 30 bold", fill=Green_color, 106 | text=score_text) 107 | self.reset_board = True 108 | 109 | score_text = 'Click to play again \n' 110 | self.canvas.create_text(size_of_board / 2, 15 * size_of_board / 16, font="cmr 20 bold", fill="gray", 111 | text=score_text) 112 | 113 | # ------------------------------------------------------------------ 114 | # Logical Functions: 115 | # The modules required to carry out game logic 116 | # ------------------------------------------------------------------ 117 | 118 | def convert_logical_to_grid_position(self, logical_position): 119 | logical_position = np.array(logical_position, dtype=int) 120 | return (size_of_board / 3) * logical_position + size_of_board / 6 121 | 122 | def convert_grid_to_logical_position(self, grid_position): 123 | grid_position = np.array(grid_position) 124 | return np.array(grid_position // (size_of_board / 3), dtype=int) 125 | 126 | def is_grid_occupied(self, logical_position): 127 | if self.board_status[logical_position[0]][logical_position[1]] == 0: 128 | return False 129 | else: 130 | return True 131 | 132 | def is_winner(self, player): 133 | 134 | player = -1 if player == 'X' else 1 135 | 136 | # Three in a row 137 | for i in range(3): 138 | if self.board_status[i][0] == self.board_status[i][1] == self.board_status[i][2] == player: 139 | return True 140 | if self.board_status[0][i] == self.board_status[1][i] == self.board_status[2][i] == player: 141 | return True 142 | 143 | # Diagonals 144 | if self.board_status[0][0] == self.board_status[1][1] == self.board_status[2][2] == player: 145 | return True 146 | 147 | if self.board_status[0][2] == self.board_status[1][1] == self.board_status[2][0] == player: 148 | return True 149 | 150 | return False 151 | 152 | def is_tie(self): 153 | 154 | r, c = np.where(self.board_status == 0) 155 | tie = False 156 | if len(r) == 0: 157 | tie = True 158 | 159 | return tie 160 | 161 | def is_gameover(self): 162 | # Either someone wins or all grid occupied 163 | self.X_wins = self.is_winner('X') 164 | if not self.X_wins: 165 | self.O_wins = self.is_winner('O') 166 | 167 | if not self.O_wins: 168 | self.tie = self.is_tie() 169 | 170 | gameover = self.X_wins or self.O_wins or self.tie 171 | 172 | if self.X_wins: 173 | print('X wins') 174 | if self.O_wins: 175 | print('O wins') 176 | if self.tie: 177 | print('Its a tie') 178 | 179 | return gameover 180 | 181 | 182 | 183 | 184 | 185 | def click(self, event): 186 | grid_position = [event.x, event.y] 187 | logical_position = self.convert_grid_to_logical_position(grid_position) 188 | 189 | if not self.reset_board: 190 | if self.player_X_turns: 191 | if not self.is_grid_occupied(logical_position): 192 | self.draw_X(logical_position) 193 | self.board_status[logical_position[0]][logical_position[1]] = -1 194 | self.player_X_turns = not self.player_X_turns 195 | else: 196 | if not self.is_grid_occupied(logical_position): 197 | self.draw_O(logical_position) 198 | self.board_status[logical_position[0]][logical_position[1]] = 1 199 | self.player_X_turns = not self.player_X_turns 200 | 201 | # Check if game is concluded 202 | if self.is_gameover(): 203 | self.display_gameover() 204 | # print('Done') 205 | else: # Play Again 206 | self.canvas.delete("all") 207 | self.play_again() 208 | self.reset_board = False 209 | 210 | 211 | game_instance = Tic_Tac_Toe() 212 | game_instance.mainloop() -------------------------------------------------------------------------------- /Transpose a Matrix.py: -------------------------------------------------------------------------------- 1 | 2 | X = [[1, 3], [4,5], [7, 9]] 3 | 4 | result = [0, 0, 0], [0, 0, 0]] 5 | 6 | for i in range (len (X)): 7 | 8 | for j in range (len (X[0])): 9 | 10 | result [j][i] = X [i][j] 11 | 12 | for r in result: 13 | 14 | print (r) 15 | -------------------------------------------------------------------------------- /Waterjug.py: -------------------------------------------------------------------------------- 1 | # This function is used to initialize the 2 | # dictionary elements with a default value. 3 | from collections import defaultdict 4 | 5 | # jug1 and jug2 contain the value 6 | # for max capacity in respective jugs 7 | # and aim is the amount of water to be measured. 8 | jug1, jug2, aim = 4, 3, 2 9 | 10 | # Initialize dictionary with 11 | # default value as false. 12 | visited = defaultdict(lambda: False) 13 | 14 | # Recursive function which prints the 15 | # intermediate steps to reach the final 16 | # solution and return boolean value 17 | # (True if solution is possible, otherwise False). 18 | # amt1 and amt2 are the amount of water present 19 | # in both jugs at a certain point of time. 20 | def waterJugSolver(amt1, amt2): 21 | 22 | # Checks for our goal and 23 | # returns true if achieved. 24 | if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0): 25 | print(amt1, amt2) 26 | return True 27 | 28 | # Checks if we have already visited the 29 | # combination or not. If not, then it proceeds further. 30 | if visited[(amt1, amt2)] == False: 31 | print(amt1, amt2) 32 | 33 | # Changes the boolean value of 34 | # the combination as it is visited. 35 | visited[(amt1, amt2)] = True 36 | 37 | # Check for all the 6 possibilities and 38 | # see if a solution is found in any one of them. 39 | return (waterJugSolver(0, amt2) or 40 | waterJugSolver(amt1, 0) or 41 | waterJugSolver(jug1, amt2) or 42 | waterJugSolver(amt1, jug2) or 43 | waterJugSolver(amt1 + min(amt2, (jug1-amt1)), 44 | amt2 - min(amt2, (jug1-amt1))) or 45 | waterJugSolver(amt1 - min(amt1, (jug2-amt2)), 46 | amt2 + min(amt1, (jug2-amt2)))) 47 | 48 | # Return False if the combination is 49 | # already visited to avoid repetition otherwise 50 | # recursion will enter an infinite loop. 51 | else: 52 | return False 53 | 54 | print("Steps: ") 55 | 56 | # Call the function and pass the 57 | # initial amount of water present in both jugs. 58 | waterJugSolver(0, 0) 59 | -------------------------------------------------------------------------------- /Web_Scraping_with_BeatifulSoup.py: -------------------------------------------------------------------------------- 1 | # import required modules 2 | import json 3 | import requests 4 | from datetime import datetime 5 | from urllib.parse import urlparse 6 | from bs4 import BeautifulSoup 7 | from beautifultable import BeautifulTable 8 | 9 | 10 | 11 | def load_json(database_json_file="scraped_data.json"): 12 | """ 13 | This function will load json data from scraped_data.json file if it exist else crean an empty array 14 | """ 15 | try: 16 | with open(database_json_file, "r") as read_it: 17 | all_data_base = json.loads(read_it.read()) 18 | return all_data_base 19 | except: 20 | all_data_base = dict() 21 | return all_data_base 22 | 23 | 24 | def save_scraped_data_in_json(data, database_json_file="scraped_data.json"): 25 | """ 26 | This function Save the scraped data in json format. scraped_data.json file if it exist else create it. 27 | if file already exist you can view previous scraped data 28 | """ 29 | file_obj = open(database_json_file, "w") 30 | file_obj.write(json.dumps(data)) 31 | file_obj.close() 32 | 33 | 34 | def existing_scraped_data_init(json_db): 35 | """ 36 | This function init data from json file if it exist have data else create an empty one 37 | """ 38 | scraped_data = json_db.get("scraped_data") 39 | if scraped_data is None: 40 | json_db['scraped_data'] = dict() 41 | 42 | return None 43 | 44 | 45 | def scraped_time_is(): 46 | """ 47 | This function create time stamp for keep our book issue record trackable 48 | """ 49 | now = datetime.now() 50 | dt_string = now.strftime("%d/%m/%Y %H:%M:%S") 51 | return dt_string 52 | 53 | def process_url_request(website_url): 54 | """ 55 | This function process provided URL get its data using requets module 56 | and contrunct soup data using BeautifulSoup for scarping 57 | """ 58 | requets_data = requests.get(website_url) 59 | if requets_data.status_code == 200: 60 | soup = BeautifulSoup(requets_data.text,'html') 61 | return soup 62 | return None 63 | 64 | def proccess_beautiful_soup_data(soup): 65 | return { 66 | 'title': soup.find('title').text, 67 | 'all_anchor_href': [i['href'] for i in soup.find_all('a', href=True)], 68 | 'all_anchors': [str(i) for i in soup.find_all('a')], 69 | 'all_images_data': [ str(i) for i in soup.find_all('img')], 70 | 'all_images_source_data': [ i['src'] for i in soup.find_all('img')], 71 | 'all_h1_data': [i.text for i in soup.find_all('h1')], 72 | 'all_h2_data': [i.text for i in soup.find_all('h2')], 73 | 'all_h3_data': [i.text for i in soup.find_all('h3')], 74 | 'all_p_data': [i.text for i in soup.find_all('p')] 75 | } 76 | 77 | 78 | 79 | # Here I used infinite loop because i don't want to run it again and again. 80 | while True: 81 | 82 | print(""" ================ Welcome to this scraping program ============= 83 | ==>> press 1 for checking existing scraped websites 84 | ==>> press 2 for scrap a single website 85 | ==>> press 3 for exit 86 | """) 87 | 88 | choice = int(input("==>> Please enter your choice :")) 89 | 90 | # Load json function called for fetching/creating data from json file. 91 | local_json_db = load_json() 92 | existing_scraped_data_init(local_json_db) 93 | 94 | if choice == 1: 95 | # I used Beautiful table for presenting scraped data in a good way !! 96 | # you guys can read more about from this link https://beautifultable.readthedocs.io/en/latest/index.html 97 | scraped_websites_table = BeautifulTable() 98 | scraped_websites_table.columns.header = ["Sr no.", "Allias name ", "Website domain", "title", "Scraped at", "Status"] 99 | scraped_websites_table.set_style(BeautifulTable.STYLE_BOX_DOUBLED) 100 | 101 | 102 | local_json_db = load_json() 103 | for count, data in enumerate(local_json_db['scraped_data']): 104 | scraped_websites_table.rows.append([count + 1, 105 | local_json_db['scraped_data'][data]['alias'], 106 | local_json_db['scraped_data'][data]['domain'], 107 | local_json_db['scraped_data'][data]['title'], 108 | local_json_db['scraped_data'][data]['scraped_at'], 109 | local_json_db['scraped_data'][data]['status']]) 110 | # all_scraped_websites = [websites['name'] for websites in local_json_db['scraped_data']] 111 | if not local_json_db['scraped_data']: 112 | print('===> No existing data found !!!') 113 | print(scraped_websites_table) 114 | 115 | elif choice == 2: 116 | print() 117 | url_for_scrap = input("===> Please enter url you want to scrap:") 118 | is_accessable = process_url_request(url_for_scrap) 119 | if is_accessable: 120 | scraped_data_packet = proccess_beautiful_soup_data(is_accessable) 121 | print() 122 | print(' =====> Data scraped successfully !!!') 123 | key_for_storing_data = input("enter alias name for saving scraped data :") 124 | scraped_data_packet['url'] = url_for_scrap 125 | scraped_data_packet['name'] = key_for_storing_data 126 | scraped_data_packet['scraped_at'] = scraped_time_is() 127 | if key_for_storing_data in local_json_db['scraped_data']: 128 | key_for_storing_data = key_for_storing_data + str(scraped_time_is()) 129 | print("Provided key is already exist so data stored as : {}".format(key_for_storing_data)) 130 | scraped_data_packet['alias'] = key_for_storing_data 131 | scraped_data_packet['status'] = True 132 | scraped_data_packet['domain'] = urlparse(url_for_scrap).netloc 133 | 134 | local_json_db['scraped_data'][key_for_storing_data] = scraped_data_packet 135 | print( 136 | 'scraped data is:', local_json_db['scraped_data'][key_for_storing_data] 137 | ) 138 | save_scraped_data_in_json(local_json_db) 139 | # load data 140 | local_json_db = load_json() 141 | print(' =====> Data saved successfully !!!') 142 | print() 143 | elif choice == 3: 144 | print('Thank you for using !!!') 145 | break 146 | 147 | elif choice == 4: 148 | print('Thank you for using !!!') 149 | break 150 | 151 | else: 152 | print("enter a valid choice ") -------------------------------------------------------------------------------- /__pycache__/numpy.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suman-shah/python-example-/4f28cd03d23d0479d5e7b7494b36a546b40de31a/__pycache__/numpy.cpython-39.pyc -------------------------------------------------------------------------------- /a Module.py: -------------------------------------------------------------------------------- 1 | def greeting(name): 2 | print("Hello, " + name) 3 | -------------------------------------------------------------------------------- /accesselement.py: -------------------------------------------------------------------------------- 1 | thislist = ["apple", "banana", "cherry"] 2 | print(thislist[-1]) -------------------------------------------------------------------------------- /all Prime numbers in an Interval.py: -------------------------------------------------------------------------------- 1 | # Python program to print all 2 | # prime number in an interval 3 | 4 | def prime(x, y): 5 | prime_list = [] 6 | for i in range(x, y): 7 | if i == 0 or i == 1: 8 | continue 9 | else: 10 | for j in range(2, int(i/2)+1): 11 | if i % j == 0: 12 | break 13 | else: 14 | prime_list.append(i) 15 | return prime_list 16 | 17 | # Driver program 18 | starting_range = 2 19 | ending_range = 7 20 | lst = prime(starting_range, ending_range) 21 | if len(lst) == 0: 22 | print("There are no prime numbers in this range") 23 | else: 24 | print("The prime numbers in this range are: ", lst) 25 | -------------------------------------------------------------------------------- /appenditem.py: -------------------------------------------------------------------------------- 1 | thislist = ["apple", "banana", "cherry"] 2 | thislist.append("orange") 3 | print(thislist) -------------------------------------------------------------------------------- /bfs.py: -------------------------------------------------------------------------------- 1 | graph = { 2 | '5' : ['3','7'], 3 | '3' : ['2', '4'], 4 | '7' : ['8'], 5 | '2' : [], 6 | '4' : ['8'], 7 | '8' : [] 8 | } 9 | 10 | visited = [] # List for visited nodes. 11 | queue = [] #Initialize a queue 12 | 13 | def bfs(visited, graph, node): #function for BFS 14 | visited.append(node) 15 | queue.append(node) 16 | 17 | while queue: # Creating loop to visit each node 18 | m = queue.pop(0) 19 | print (m, end = " ") 20 | 21 | for neighbour in graph[m]: 22 | if neighbour not in visited: 23 | visited.append(neighbour) 24 | queue.append(neighbour) 25 | 26 | # Driver Code 27 | print("Following is the Breadth-First Search") 28 | bfs(visited, graph, '5') # function calling 29 | -------------------------------------------------------------------------------- /cal.py: -------------------------------------------------------------------------------- 1 | # Program make a simple calculator 2 | 3 | # This function adds two numbers 4 | def add(x, y): 5 | return x + y 6 | 7 | # This function subtracts two numbers 8 | def subtract(x, y): 9 | return x - y 10 | 11 | # This function multiplies two numbers 12 | def multiply(x, y): 13 | return x * y 14 | 15 | # This function divides two numbers 16 | def divide(x, y): 17 | return x / y 18 | 19 | 20 | print("Select operation.") 21 | print("1.Add") 22 | print("2.Subtract") 23 | print("3.Multiply") 24 | print("4.Divide") 25 | 26 | while True: 27 | # take input from the user 28 | choice = input("Enter choice(1/2/3/4): ") 29 | 30 | # check if choice is one of the four options 31 | if choice in ('1', '2', '3', '4'): 32 | num1 = float(input("Enter first number: ")) 33 | num2 = float(input("Enter second number: ")) 34 | 35 | if choice == '1': 36 | print(num1, "+", num2, "=", add(num1, num2)) 37 | 38 | elif choice == '2': 39 | print(num1, "-", num2, "=", subtract(num1, num2)) 40 | 41 | elif choice == '3': 42 | print(num1, "*", num2, "=", multiply(num1, num2)) 43 | 44 | elif choice == '4': 45 | print(num1, "/", num2, "=", divide(num1, num2)) 46 | 47 | # check if user wants another calculation 48 | # break the while loop if answer is no 49 | next_calculation = input("Let's do next calculation? (yes/no): ") 50 | if next_calculation == "no": 51 | break 52 | 53 | else: 54 | print("Invalid Input") 55 | -------------------------------------------------------------------------------- /casting.py: -------------------------------------------------------------------------------- 1 | x = int(1) # x will be 1 2 | y = int(2.8) # y will be 2 3 | z = int("3") # z will be 3 4 | -------------------------------------------------------------------------------- /castinginpython.py: -------------------------------------------------------------------------------- 1 | x = int(1) 2 | y = int(2.8) 3 | z = int("3") 4 | print(x) 5 | print(y) 6 | print(z) 7 | -------------------------------------------------------------------------------- /checkifitemexist.py: -------------------------------------------------------------------------------- 1 | thislist = ["apple", "banana", "cherry"] 2 | if "apple" in thislist: 3 | print("Yes, 'apple' is in the fruits list") -------------------------------------------------------------------------------- /classandobject.py: -------------------------------------------------------------------------------- 1 | class Person: 2 | def __init__(self, name, age): 3 | self.name = name 4 | self.age = age 5 | 6 | p1 = Person("John", 36) 7 | 8 | print(p1.name) 9 | print(p1.age) 10 | -------------------------------------------------------------------------------- /cmath.acos: -------------------------------------------------------------------------------- 1 | #import cmath for complex number operations 2 | import cmath 3 | 4 | #find the arc cosine of a complex number 5 | print (cmath.acos(2+3j)) 6 | -------------------------------------------------------------------------------- /custom_exceptions.py: -------------------------------------------------------------------------------- 1 | class InvalidInputError(Exception): 2 | def __init__(self, input_value): 3 | """ 4 | Custom invalid input error inheriting from the base Exception class. 5 | """ 6 | self.input_value = input_value 7 | self.message = f"Invalid input: {input_value}. Valid inputs are: 1, 2, 3." 8 | 9 | super().__init__(self.message) 10 | 11 | 12 | class CustomNameError(Exception): 13 | """ 14 | Custom name error inheriting from the base Exception class. 15 | """ 16 | 17 | def __int__(self): 18 | self.message = "The application has raised a custom name error." 19 | super().__init__(self.message) 20 | 21 | 22 | class CustomTypeError(Exception): 23 | """ 24 | Custom type error inheriting from the base Exception class. 25 | """ 26 | 27 | def __int__(self): 28 | self.message = "The application has raised a custom type error." 29 | super().__init__(self.message) 30 | 31 | 32 | class CustomValueError(Exception): 33 | """ 34 | Custom value error inheriting from the base Exception class. 35 | """ 36 | 37 | def __int__(self): 38 | self.message = "The application has raised a custom value error." 39 | super().__init__(self.message) 40 | 41 | 42 | def get_user_input(): 43 | print("\nHello. This application is a demonstration of custom Python exceptions.") 44 | print("There are four custom exceptions available, all inheriting from the base Exception class:\n") 45 | print("1 - A custom name error.") 46 | print("2 - A custom type error.") 47 | print("3 - A custom value error.") 48 | print("4 - A custom input error.") 49 | print("\nPlease enter a name from 1 to 3 to raise one of the corresponding errors and see their output.") 50 | print("Entering any other input will raise the custom input error instead.") 51 | 52 | user_input = input("\nYour input: ") 53 | 54 | if user_input == "1": 55 | raise CustomNameError() 56 | elif user_input == "2": 57 | raise CustomTypeError 58 | elif user_input == "3": 59 | raise CustomValueError 60 | else: 61 | raise InvalidInputError(user_input) 62 | 63 | 64 | get_user_input() 65 | 66 | 67 | quit() 68 | -------------------------------------------------------------------------------- /dfs.py: -------------------------------------------------------------------------------- 1 | 2 | graph = { 3 | '5' : ['3','7'], 4 | '3' : ['2', '4'], 5 | '7' : ['8'], 6 | '2' : [], 7 | '4' : ['8'], 8 | '8' : [] 9 | } 10 | visited = set() 11 | 12 | def dfs(visited, graph, node): 13 | if node not in visited: 14 | print (node) 15 | visited.add(node) 16 | for neighbour in graph[node]: 17 | dfs(visited, graph, neighbour) 18 | print("Following is the Depth-First Search") 19 | dfs(visited, graph, '5') 20 | -------------------------------------------------------------------------------- /dictionaries.py: -------------------------------------------------------------------------------- 1 | thisdict = { 2 | "brand": "Ford", 3 | "model": "Mustang", 4 | "year": 1964 5 | } 6 | print(thisdict) 7 | -------------------------------------------------------------------------------- /dublicate.py: -------------------------------------------------------------------------------- 1 | thislist = ["apple", "banana", "cherry", "apple", "cherry"] 2 | print(thislist) -------------------------------------------------------------------------------- /elseif.py: -------------------------------------------------------------------------------- 1 | a = 33 2 | b = 200 3 | 4 | if b > a: 5 | print("b is greater than a") 6 | -------------------------------------------------------------------------------- /exception.py: -------------------------------------------------------------------------------- 1 | #The try block will generate an error, because x is not defined: 2 | 3 | try: 4 | print(x) 5 | except: 6 | print("An exception occurred") 7 | -------------------------------------------------------------------------------- /fisrspy.py: -------------------------------------------------------------------------------- 1 | a = """Hello my name is jay """ 2 | print(a) 3 | -------------------------------------------------------------------------------- /from 1 to N: -------------------------------------------------------------------------------- 1 | # Python3 program to display Prime numbers till N 2 | 3 | #function to check if a given number is prime 4 | def isPrime(n): 5 | #since 0 and 1 is not prime return false. 6 | if(n==1 or n==0): 7 | return False 8 | 9 | #Run a loop from 2 to n-1 10 | for i in range(2,n): 11 | #if the number is divisible by i, then n is not a prime number. 12 | if(n%i==0): 13 | return False 14 | 15 | #otherwise, n is prime number. 16 | return True 17 | 18 | 19 | 20 | # Driver code 21 | N = 100; 22 | #check for every number from 1 to N 23 | for i in range(1,N+1): 24 | #check if current number is prime 25 | if(isPrime(i)): 26 | print(i,end=" ") 27 | -------------------------------------------------------------------------------- /guess-the-number.py: -------------------------------------------------------------------------------- 1 | import random 2 | system = random.randint(0, 10) 3 | score = 100 4 | while True: 5 | try: 6 | player = int(input("guess a no between 1 to 10 \n")) 7 | if player == system: 8 | print("Damn you are genius") 9 | break 10 | 11 | elif player > 10: 12 | print("Bro I said 1 to 10") 13 | score -= 10 14 | 15 | elif player > system: 16 | print(f"Nope the number is lesser than {player}") 17 | score -= 10 18 | 19 | 20 | elif player < system: 21 | print(f"Nope the number is greater than {player}") 22 | score -= 10 23 | except: 24 | print("Atleast type a correct spelling") 25 | 26 | print(f" So your score is {score}") 27 | -------------------------------------------------------------------------------- /heatmap: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | data = np.random.random(( 12 , 12 )) 5 | plt.imshow( data , cmap = 'autumn' , interpolation = 'nearest' ) 6 | 7 | plt.title( "2-D Heat Map" ) 8 | plt.show() -------------------------------------------------------------------------------- /heatmap.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | data = np.random.random(( 12 , 12 )) 5 | plt.imshow( data , cmap = 'autumn' , interpolation = 'nearest' ) 6 | 7 | plt.title( "2-D Heat Map" ) 8 | plt.show() -------------------------------------------------------------------------------- /hellobunny.py: -------------------------------------------------------------------------------- 1 | # 1 - Import library 2 | import pygame 3 | from pygame.locals import * 4 | 5 | # 2 - Initialize the game 6 | pygame.init() 7 | width, height = 640, 480 8 | screen=pygame.display.set_mode((width, height)) 9 | 10 | # 3 - Load images 11 | player = pygame.image.load("resources/images/dude.png") 12 | 13 | # 4 - keep looping through 14 | while 1: 15 | # 5 - clear the screen before drawing it again 16 | screen.fill(0) 17 | # 6 - draw the screen elements 18 | screen.blit(player, (100,100)) 19 | # 7 - update the screen 20 | pygame.display.flip() 21 | # 8 - loop through the events 22 | for event in pygame.event.get(): 23 | # check if the event is the X button 24 | if event.type==pygame.QUIT: 25 | # if it is quit the game 26 | pygame.quit() 27 | exit(0) 28 | -------------------------------------------------------------------------------- /inheritance.py: -------------------------------------------------------------------------------- 1 | class Person: 2 | def __init__(self, fname, lname): 3 | self.firstname = fname 4 | self.lastname = lname 5 | 6 | def printname(self): 7 | print(self.firstname, self.lastname) 8 | 9 | #Use the Person class to create an object, and then execute the printname method: 10 | 11 | x = Person("John", "Doe") 12 | x.printname() 13 | -------------------------------------------------------------------------------- /insertitem.py: -------------------------------------------------------------------------------- 1 | thislist = ["apple", "banana", "cherry"] 2 | thislist.insert(1, "orange") 3 | print(thislist) 4 | -------------------------------------------------------------------------------- /johsn.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | # some JSON: 4 | x = '{ "name":"John", "age":30, "city":"New York"}' 5 | 6 | # parse x: 7 | y = json.loads(x) 8 | 9 | # the result is a Python dictionary: 10 | print(y["age"]) 11 | -------------------------------------------------------------------------------- /lambda.py: -------------------------------------------------------------------------------- 1 | x = lambda a, b : a * b 2 | print(x(5, 6)) 3 | -------------------------------------------------------------------------------- /largest.py: -------------------------------------------------------------------------------- 1 | # Python program to find the largest number among the three input numbers 2 | 3 | # change the values of num1, num2 and num3 4 | # for a different result 5 | num1 = 10 6 | num2 = 14 7 | num3 = 12 8 | 9 | # uncomment following lines to take three numbers from user 10 | #num1 = float(input("Enter first number: ")) 11 | #num2 = float(input("Enter second number: ")) 12 | #num3 = float(input("Enter third number: ")) 13 | 14 | if (num1 >= num2) and (num1 >= num3): 15 | largest = num1 16 | elif (num2 >= num1) and (num2 >= num3): 17 | largest = num2 18 | else: 19 | largest = num3 20 | 21 | print("The largest number is", largest) 22 | -------------------------------------------------------------------------------- /leapyear_or_not.py: -------------------------------------------------------------------------------- 1 | a=int(input("enter year :")) 2 | 3 | if a%4==0: 4 | if a%100==0: 5 | if a%400==0: 6 | print(" Leap") 7 | else: 8 | print("Not Leap") 9 | else: 10 | print(" Leap") 11 | 12 | else: 13 | print("Not Leap") 14 | -------------------------------------------------------------------------------- /line_intersection.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | from shapely.geometry import LineString 4 | 5 | x1 = [] 6 | x2 = [] 7 | y1 = [] 8 | y2 = [] 9 | 10 | N = 1000 11 | x1 = np.arange(0, 1, (1-0)/N).reshape((N,1)) 12 | x2 = np.arange(0, 1, (1-0)/N).reshape((N,1)) 13 | y1 = np.arange(0, 1, (1-0)/N).reshape((N,1)) 14 | y2 = np.arange(1, 0, (0-1)/N).reshape((N,1)) 15 | 16 | line_1 = LineString(np.column_stack((x1, y1))) 17 | line_2 = LineString(np.column_stack((x2, y2))) 18 | intersect = line_1.intersection(line_2) 19 | p = np.array(intersect) 20 | print(p) 21 | 22 | plt.plot(x1,y1) 23 | plt.plot(x2,y2) 24 | -------------------------------------------------------------------------------- /list.py: -------------------------------------------------------------------------------- 1 | thislist = ["apple", "banana", "cherry"] 2 | print(thislist) -------------------------------------------------------------------------------- /listdataype.py: -------------------------------------------------------------------------------- 1 | list1 = ["apple", "banana", "cherry"] 2 | list2 = [1, 5, 7, 9, 3] 3 | list3 = [True, False, False] -------------------------------------------------------------------------------- /listlength.py: -------------------------------------------------------------------------------- 1 | thislist = ["apple", "banana", "cherry"] 2 | print(len(thislist)) -------------------------------------------------------------------------------- /literla.py: -------------------------------------------------------------------------------- 1 | mytuple = ("apple", "banana", "cherry") 2 | myit = iter(mytuple) 3 | 4 | print(next(myit)) 5 | print(next(myit)) 6 | print(next(myit)) 7 | -------------------------------------------------------------------------------- /loop.py: -------------------------------------------------------------------------------- 1 | fruits = ["apple", "banana", "cherry"] 2 | for x in fruits: 3 | print(x) 4 | -------------------------------------------------------------------------------- /matplotlib.py: -------------------------------------------------------------------------------- 1 | #Three lines to make our compiler able to draw: 2 | import sys 3 | import matplotlib 4 | matplotlib.use('Agg') 5 | 6 | import matplotlib.pyplot as plt 7 | import numpy as np 8 | 9 | x = np.array(["A", "B", "C", "D"]) 10 | y = np.array([3, 8, 1, 10]) 11 | 12 | plt.bar(x,y) 13 | plt.show() 14 | 15 | #Two lines to make our compiler able to draw: 16 | plt.savefig(sys.stdout.buffer) 17 | sys.stdout.flush() 18 | -------------------------------------------------------------------------------- /matrix.py: -------------------------------------------------------------------------------- 1 | n=int(input("Enter a number: ")) 2 | for i in range(0,n): 3 | for j in range(0,n): 4 | if(i==j): 5 | print("1",sep=" ",end=" ") 6 | else: 7 | print("0",sep=" ",end=" ") 8 | print() 9 | -------------------------------------------------------------------------------- /modules.py: -------------------------------------------------------------------------------- 1 | def greeting(name): 2 | print("Hello, " + name) 3 | -------------------------------------------------------------------------------- /n-th Fibonacci number.py: -------------------------------------------------------------------------------- 1 | # Function for nth Fibonacci number 2 | 3 | def Fibonacci(n): 4 | if n<= 0: 5 | print("Incorrect input") 6 | # First Fibonacci number is 0 7 | elif n == 1: 8 | return 0 9 | # Second Fibonacci number is 1 10 | elif n == 2: 11 | return 1 12 | else: 13 | return Fibonacci(n-1)+Fibonacci(n-2) 14 | 15 | # Driver Program 16 | 17 | print(Fibonacci(10)) 18 | 19 | # This code is contributed by Saket Modi 20 | -------------------------------------------------------------------------------- /nqueens.py: -------------------------------------------------------------------------------- 1 | global N 2 | N = 4 3 | 4 | def printSolution(board): 5 | for i in range(N): 6 | for j in range(N): 7 | print(board[i][j], end = " ") 8 | print() 9 | 10 | 11 | def isSafe(board, row, col): 12 | 13 | 14 | for i in range(col): 15 | if board[row][i] == 1: 16 | return False 17 | 18 | for i, j in zip(range(row, -1, -1), 19 | range(col, -1, -1)): 20 | if board[i][j] == 1: 21 | return False 22 | 23 | for i, j in zip(range(row, N, 1), 24 | range(col, -1, -1)): 25 | if board[i][j] == 1: 26 | return False 27 | 28 | return True 29 | 30 | def solveNQUtil(board, col): 31 | 32 | 33 | if col >= N: 34 | return True 35 | 36 | for i in range(N): 37 | 38 | if isSafe(board, i, col): 39 | 40 | 41 | board[i][col] = 1 42 | 43 | 44 | if solveNQUtil(board, col + 1) == True: 45 | return True 46 | 47 | 48 | board[i][col] = 0 49 | 50 | 51 | return False 52 | 53 | def solveNQ(): 54 | board = [ [0, 0, 0, 0], 55 | [0, 0, 0, 0], 56 | [0, 0, 0, 0], 57 | [0, 0, 0, 0] ] 58 | 59 | if solveNQUtil(board, 0) == False: 60 | print ("Solution does not exist") 61 | return False 62 | 63 | printSolution(board) 64 | return True 65 | 66 | solveNQ() 67 | -------------------------------------------------------------------------------- /numpy1.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | arr = np.array([1, 2, 3, 4, 5]) 4 | 5 | print(arr) 6 | 7 | print(type(arr)) 8 | 9 | print(arr.ndim) #gives the dimension of array -------------------------------------------------------------------------------- /nympy.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | arr = np.array([1, 2, 3, 4, 5]) 4 | 5 | print(arr) 6 | 7 | print(type(arr)) 8 | -------------------------------------------------------------------------------- /palindrumreverse.py: -------------------------------------------------------------------------------- 1 | n=int(input("Enter number:")) 2 | temp=n 3 | rev=0 4 | while(n>0): 5 | dig=n%10 6 | rev=rev*10+dig 7 | n=n//10 8 | if(temp==rev): 9 | print("The number is a palindrome!") 10 | else: 11 | print("The number isn't a palindrome!") 12 | -------------------------------------------------------------------------------- /power of funct.py: -------------------------------------------------------------------------------- 1 | number = int(input(" Please Enter any Positive Integer : ")) 2 | exponent = int(input(" Please Enter Exponent Value : ")) 3 | power = 1 4 | 5 | for i in range(1, exponent + 1): 6 | power = power * number 7 | 8 | print("The Result of {0} Power {1} = {2}".format(number, exponent, power)) 9 | -------------------------------------------------------------------------------- /prog1.py: -------------------------------------------------------------------------------- 1 | # Python Program to calculate the square root 2 | 3 | # Note: change this value for a different result 4 | num = 8 5 | 6 | # To take the input from the user 7 | #num = float(input('Enter a number: ')) 8 | 9 | num_sqrt = num ** 0.5 10 | print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) 11 | -------------------------------------------------------------------------------- /pty.py: -------------------------------------------------------------------------------- 1 | x = int(1) 2 | y = int(2.8) 3 | z = int("3") 4 | print(x) 5 | print(y) 6 | print(z) 7 | -------------------------------------------------------------------------------- /pygame/alien.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suman-shah/python-example-/4f28cd03d23d0479d5e7b7494b36a546b40de31a/pygame/alien.png -------------------------------------------------------------------------------- /pygame/background.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suman-shah/python-example-/4f28cd03d23d0479d5e7b7494b36a546b40de31a/pygame/background.wav -------------------------------------------------------------------------------- /pygame/bg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suman-shah/python-example-/4f28cd03d23d0479d5e7b7494b36a546b40de31a/pygame/bg.png -------------------------------------------------------------------------------- /pygame/bullet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suman-shah/python-example-/4f28cd03d23d0479d5e7b7494b36a546b40de31a/pygame/bullet.png -------------------------------------------------------------------------------- /pygame/explosion.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suman-shah/python-example-/4f28cd03d23d0479d5e7b7494b36a546b40de31a/pygame/explosion.wav -------------------------------------------------------------------------------- /pygame/laser.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suman-shah/python-example-/4f28cd03d23d0479d5e7b7494b36a546b40de31a/pygame/laser.wav -------------------------------------------------------------------------------- /pygame/main.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import random 3 | from pygame import mixer 4 | 5 | pygame.init() 6 | screen = pygame.display.set_mode((800, 600)) 7 | bg = pygame.image.load('bg.png') 8 | 9 | pygame.display.set_caption("Space Invaders") 10 | icon = pygame.image.load('space.png') 11 | pygame.display.set_icon(icon) 12 | 13 | score = 0 14 | font = pygame.font.Font('freesansbold.ttf', 32) 15 | scoreX = 15 16 | scoreY = 15 17 | 18 | overfont = pygame.font.Font('freesansbold.ttf', 100) 19 | 20 | mixer.music.load("background.wav") 21 | mixer.music.play(-1) 22 | # mixer.music.load("explosion.wav") 23 | 24 | playimg = pygame.image.load('si.png') 25 | playerX = 368 26 | playerY = 500 27 | c = 0 28 | d = 0 29 | 30 | enemyimg = [] 31 | enemyX = [] 32 | enemyY = [] 33 | e = [] 34 | numofenemy = 8 35 | for i in range(numofenemy): 36 | enemyimg.append(pygame.image.load('alien.png')) 37 | enemyX.append(random.randint(0, 736)) 38 | enemyY.append(random.randint(0, 250)) 39 | e.append(1.2) 40 | 41 | bulletimg = pygame.image.load('bullet.png') 42 | bulletX = 0 43 | bulletY = 480 44 | f = 15 45 | bulstate = "ready" 46 | 47 | 48 | def showscore(): 49 | scoreobj = font.render("Score: " + str(score), True, (255, 255, 255)) 50 | screen.blit(scoreobj, (scoreX, scoreY)) 51 | 52 | 53 | def player(): 54 | screen.blit(playimg, (playerX, playerY)) 55 | 56 | 57 | def enemy(): 58 | for b in range(numofenemy): 59 | screen.blit(enemyimg[b], (enemyX[b], enemyY[b])) 60 | 61 | 62 | def bulletfire(): 63 | global bulstate 64 | bulstate = "fire" 65 | screen.blit(bulletimg, (bulletX + 16, bulletY + 10)) 66 | 67 | 68 | def gameover(): 69 | overobj = overfont.render("GAME OVER", True, (255, 255, 255)) 70 | screen.blit(overobj, (90, 250)) 71 | restartobj = font.render("Press Enter to Restart", True, (255, 255, 255)) 72 | screen.blit(restartobj, (230, 400)) 73 | 74 | 75 | rn = True 76 | while rn: 77 | screen.fill((0, 0, 0)) 78 | screen.blit(bg, (0, 0)) 79 | for ev in pygame.event.get(): 80 | if ev.type == pygame.QUIT: 81 | rn = False 82 | if ev.type == pygame.KEYDOWN: 83 | if ev.key == pygame.K_LEFT: 84 | c = -3 85 | if ev.key == pygame.K_RIGHT: 86 | c = 3 87 | if ev.key == pygame.K_UP: 88 | d = -3 89 | if ev.key == pygame.K_DOWN: 90 | d = 3 91 | if ev.key == pygame.K_SPACE and bulstate == "ready": 92 | bulletsound = mixer.Sound('laser.wav') 93 | bulletsound.play() 94 | bulletX = playerX 95 | bulletY = playerY 96 | bulletfire() 97 | if ev.key == pygame.K_RETURN and enemyY[0] == 2000: 98 | score = 0 99 | enemyY = [] 100 | for i in range(numofenemy): 101 | enemyY.append(random.randint(0, 250)) 102 | 103 | if ev.type == pygame.KEYUP: 104 | if ev.key == pygame.K_LEFT or ev.key == pygame.K_RIGHT: 105 | c = 0 106 | if ev.key == pygame.K_UP or ev.key == pygame.K_DOWN: 107 | d = 0 108 | playerX += c 109 | if playerX > 736: 110 | playerX = 736 111 | elif playerX < 0: 112 | playerX = 0 113 | playerY += d 114 | if playerY > 536: 115 | playerY = 536 116 | elif playerY < 0: 117 | playerY = 0 118 | player() 119 | enemy() 120 | 121 | for i in range(numofenemy): 122 | enemyX[i] += e[i] 123 | if enemyX[i] > 736 or enemyX[i] < 0: 124 | e[i] = -e[i] 125 | enemyY[i] += 40 126 | if enemyY[i] > 420 or (abs(enemyX[i] - playerX) < 22 and abs(enemyY[i] - playerY) < 22): 127 | for j in range(numofenemy): 128 | enemyY[j] = 2000 129 | gameover() 130 | break 131 | 132 | if bulstate == "fire": 133 | bulletY -= f 134 | bulletfire() 135 | 136 | if bulletY < 0: 137 | bulstate = "ready" 138 | 139 | for i in range(numofenemy): 140 | if abs(enemyX[i] - bulletX) < 20 and abs(enemyY[i] - bulletY) < 20: 141 | scoresound = mixer.Sound('explosion.wav') 142 | scoresound.play() 143 | bulstate = "ready" 144 | score += 1 145 | enemyX[i] = random.randint(0, 736) 146 | enemyY[i] = random.randint(0, 350) 147 | showscore() 148 | pygame.display.update() 149 | -------------------------------------------------------------------------------- /pygame/requirements.txt: -------------------------------------------------------------------------------- 1 | pygame==2.1.2 2 | -------------------------------------------------------------------------------- /pygame/si.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suman-shah/python-example-/4f28cd03d23d0479d5e7b7494b36a546b40de31a/pygame/si.png -------------------------------------------------------------------------------- /pygame/space.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suman-shah/python-example-/4f28cd03d23d0479d5e7b7494b36a546b40de31a/pygame/space.png -------------------------------------------------------------------------------- /pymid-python pyramid: -------------------------------------------------------------------------------- 1 | # Contributed by endrasww 2 | 3 | while True: 4 | try: 5 | high = int(input(" Please enter the expected high for the python pyramid! ")) + 1 6 | except ValueError: 7 | print("Invalid input, expecting integer value!") 8 | else: 9 | break 10 | 11 | block = input(" Please choose your pyramid block! Select between X, *, —, and +. The default is X. ") + " " 12 | if block not in ['X ', '* ', '- ', '+ ']: 13 | print("Invalid input for pyramid block, continue with default block (X).") 14 | block = 'X ' 15 | 16 | for i in range(1, high): 17 | if i % 2: 18 | print("{:^150}".format(block*i)) 19 | else: 20 | print("{:^150}".format(block*i)) 21 | -------------------------------------------------------------------------------- /python.py: -------------------------------------------------------------------------------- 1 | x = int(1) # x will be 1 2 | y = int(2.8) # y will be 2 3 | z = int("3") # z will be 3 4 | -------------------------------------------------------------------------------- /pythonlambda.py: -------------------------------------------------------------------------------- 1 | x = lambda a, b : a * b 2 | print(x(5, 6)) 3 | -------------------------------------------------------------------------------- /pythonuserinput.py: -------------------------------------------------------------------------------- 1 | username = input("Enter username:") 2 | print("Username is: " + username) 3 | -------------------------------------------------------------------------------- /rangeindex.py: -------------------------------------------------------------------------------- 1 | thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] 2 | print(thislist[2:5]) -------------------------------------------------------------------------------- /rangeofneg.py: -------------------------------------------------------------------------------- 1 | thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] 2 | print(thislist[-4:-1]) -------------------------------------------------------------------------------- /readfile.py: -------------------------------------------------------------------------------- 1 | f = open("demofile.txt", "r") 2 | print(f.read()) 3 | -------------------------------------------------------------------------------- /repaclingst.py: -------------------------------------------------------------------------------- 1 | a = "Hello, World!" 2 | print(a.replace("H", "J")) 3 | -------------------------------------------------------------------------------- /scope.py: -------------------------------------------------------------------------------- 1 | def myfunc(): 2 | x = 300 3 | print(x) 4 | 5 | myfunc() 6 | -------------------------------------------------------------------------------- /set.py: -------------------------------------------------------------------------------- 1 | thisset = {"apple", "banana", "cherry"} 2 | print(thisset) 3 | -------------------------------------------------------------------------------- /simplecal.py: -------------------------------------------------------------------------------- 1 | 2 | # Program make a simple calculator 3 | 4 | # This function adds two numbers 5 | def add(x, y): 6 | return x + y 7 | 8 | # This function subtracts two numbers 9 | def subtract(x, y): 10 | return x - y 11 | 12 | # This function multiplies two numbers 13 | def multiply(x, y): 14 | return x * y 15 | 16 | # This function divides two numbers 17 | def divide(x, y): 18 | return x / y 19 | 20 | 21 | print("Select operation.") 22 | print("1.Add") 23 | print("2.Subtract") 24 | print("3.Multiply") 25 | print("4.Divide") 26 | 27 | while True: 28 | # take input from the user 29 | choice = input("Enter choice(1/2/3/4): ") 30 | 31 | # check if choice is one of the four options 32 | if choice in ('1', '2', '3', '4'): 33 | num1 = float(input("Enter first number: ")) 34 | num2 = float(input("Enter second number: ")) 35 | 36 | if choice == '1': 37 | print(num1, "+", num2, "=", add(num1, num2)) 38 | 39 | elif choice == '2': 40 | print(num1, "-", num2, "=", subtract(num1, num2)) 41 | 42 | elif choice == '3': 43 | print(num1, "*", num2, "=", multiply(num1, num2)) 44 | 45 | elif choice == '4': 46 | print(num1, "/", num2, "=", divide(num1, num2)) 47 | 48 | # check if user wants another calculation 49 | # break the while loop if answer is no 50 | next_calculation = input("Let's do next calculation? (yes/no): ") 51 | if next_calculation == "no": 52 | break 53 | 54 | else: 55 | print("Invalid Input") 56 | -------------------------------------------------------------------------------- /simplecalulatorinpython.py: -------------------------------------------------------------------------------- 1 | def add(P, Q): 2 | # This function is used for adding two numbers 3 | return P + Q 4 | def subtract(P, Q): 5 | # This function is used for subtracting two numbers 6 | return P - Q 7 | def multiply(P, Q): 8 | # This function is used for multiplying two numbers 9 | return P * Q 10 | def divide(P, Q): 11 | # This function is used for dividing two numbers 12 | return P / Q 13 | # Now we will take inputs from the user 14 | print ("Please select the operation.") 15 | print ("a. Add") 16 | print ("b. Subtract") 17 | print ("c. Multiply") 18 | print ("d. Divide") 19 | 20 | choice = input("Please enter choice (a/ b/ c/ d): ") 21 | 22 | num_1 = int (input ("Please enter the first number: ")) 23 | num_2 = int (input ("Please enter the second number: ")) 24 | 25 | if choice == 'a': 26 | print (num_1, " + ", num_2, " = ", add(num_1, num_2)) 27 | 28 | elif choice == 'b': 29 | print (num_1, " - ", num_2, " = ", subtract(num_1, num_2)) 30 | 31 | elif choice == 'c': 32 | print (num1, " * ", num2, " = ", multiply(num1, num2)) 33 | elif choice == 'd': 34 | print (num_1, " / ", num_2, " = ", divide(num_1, num_2)) 35 | else: 36 | print ("This is an invalid input") 37 | -------------------------------------------------------------------------------- /simplepyexample.py: -------------------------------------------------------------------------------- 1 | print("Hello, World!") 2 | -------------------------------------------------------------------------------- /slacingstring.py: -------------------------------------------------------------------------------- 1 | b = "Hello, World!" 2 | print(b[2:5]) 3 | -------------------------------------------------------------------------------- /stack.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, value): 3 | self.value = value 4 | self.next = None 5 | 6 | 7 | class Stack: 8 | def __init__(self): 9 | self.head = Node("head") 10 | self.size = 0 11 | 12 | def __str__(self): 13 | cur = self.head.next 14 | out = "" 15 | while cur: 16 | out += str(cur.value) + "->" 17 | cur = cur.next 18 | return out[:-3] 19 | 20 | # Get the current size of the stack 21 | def getSize(self): 22 | return self.size 23 | 24 | # Check if the stack is empty 25 | def isEmpty(self): 26 | return self.size == 0 27 | 28 | # Get the top item of the stack 29 | def peek(self): 30 | 31 | # Sanitary check to see if we 32 | # are peeking an empty stack. 33 | if self.isEmpty(): 34 | raise Exception("Peeking from an empty stack") 35 | return self.head.next.value 36 | 37 | # Push a value into the stack. 38 | def push(self, value): 39 | node = Node(value) 40 | node.next = self.head.next 41 | self.head.next = node 42 | self.size += 1 43 | 44 | # Remove a value from the stack and return. 45 | def pop(self): 46 | if self.isEmpty(): 47 | raise Exception("Popping from an empty stack") 48 | remove = self.head.next 49 | self.head.next = self.head.next.next 50 | self.size -= 1 51 | return remove.value 52 | 53 | 54 | # Driver Code 55 | if __name__ == "__main__": 56 | stack = Stack() 57 | for i in range(1, 11): 58 | stack.push(i) 59 | print(f"Stack: {stack}") 60 | 61 | for _ in range(1, 6): 62 | remove = stack.pop() 63 | print(f"Pop: {remove}") 64 | print(f"Stack: {stack}") 65 | -------------------------------------------------------------------------------- /string_slicing.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suman-shah/python-example-/4f28cd03d23d0479d5e7b7494b36a546b40de31a/string_slicing.py -------------------------------------------------------------------------------- /stringformation.py: -------------------------------------------------------------------------------- 1 | price = 49 2 | txt = "The price is {} dollars" 3 | print(txt.format(price)) 4 | -------------------------------------------------------------------------------- /table-of-a-number: -------------------------------------------------------------------------------- 1 | #Program to print the table of a given number 2 | num= int(input("Enter number: ")) 3 | 4 | for i in range(1,11): 5 | print(num, "x", i, "=", (num*i)) 6 | -------------------------------------------------------------------------------- /thistuple.py: -------------------------------------------------------------------------------- 1 | thistuple = ("apple", "banana", "cherry") 2 | if "apple" in thistuple: 3 | print("Yes, 'apple' is in the fruits tuple") 4 | -------------------------------------------------------------------------------- /toh.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def TowerOfHanoi(n , source, destination, auxiliary): 4 | if n==1: 5 | print ("Move disk 1 from source",source,"to destination",destination) 6 | return 7 | TowerOfHanoi(n-1, source, auxiliary, destination) 8 | print ("Move disk",n,"from source",source,"to destination",destination) 9 | TowerOfHanoi(n-1, auxiliary, destination, source) 10 | 11 | n = 4 12 | TowerOfHanoi(n,'A','B','C') 13 | -------------------------------------------------------------------------------- /try.py: -------------------------------------------------------------------------------- 1 | try: 2 | print(x) 3 | except: 4 | print("An exception occurred") 5 | -------------------------------------------------------------------------------- /tryexception.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | try: 4 | print(x) 5 | except: 6 | print("An exception occurred") 7 | -------------------------------------------------------------------------------- /tuples.py: -------------------------------------------------------------------------------- 1 | thistuple = ("apple", "banana", "cherry") 2 | print(thistuple) 3 | -------------------------------------------------------------------------------- /variable.py: -------------------------------------------------------------------------------- 1 | x = 5 2 | y = "John" 3 | print(x) 4 | print(y) 5 | -------------------------------------------------------------------------------- /water_reminder.py: -------------------------------------------------------------------------------- 1 | import time 2 | from plyer import notification 3 | if __name__ == '__main__': 4 | while True: 5 | notification.notify( 6 | title = "**Drink Water Now!!", 7 | message ="Drinking Water Helps to Maintain the Balance of Body Fluids.", 8 | timeout= 10 9 | ) 10 | time.sleep(60*60) --------------------------------------------------------------------------------