├── .DS_Store ├── .gitignore ├── .vscode ├── extensions.json ├── launch.json └── settings.json ├── ArgsKwArgs ├── KwArgs.py └── args.py ├── Classes ├── composition.py ├── decorators.py ├── globalVariables.py ├── inheritance.py ├── session-on-class.py ├── special_class_methods.py └── state.py ├── Cryptography ├── __pycache__ │ └── rsa.cpython-37.pyc ├── rsa.py └── test.py ├── DataCollectionTypes ├── Dictionary │ ├── Task1.py │ ├── Task2.py │ ├── Tutorials_1.py │ └── to_delete_in_future_sample.py ├── List │ ├── 1. ListBasics.py │ ├── 2. ListLearning.py │ ├── 3. ListComprehension.py │ ├── 4. ListTutorial.py │ ├── 5. NestedList.py │ ├── 6. CombiningAllInnerListIntoOneList.py │ ├── 7. OrderedList.py │ ├── 8. MostRepeatedElementsInList.py │ ├── FindCommonElements.py │ └── MoveAllZerosToEnd.py ├── Sets │ ├── 1. Sets_Tutorial.py │ ├── 2. SymettricDifference.py │ └── Excercise │ │ ├── difference.py │ │ └── unionOperation.py └── Tuples │ └── Tuples.py ├── DataStructures ├── Array │ └── What.py ├── FB │ ├── EditApart.py │ └── Spiral.py ├── LinkedList │ ├── LinkedList.png │ ├── LinkedList_EasyUnderstanding.py │ └── LinkedList_Implementation.py ├── Stack │ └── Stack_Implementation.py └── test │ └── test.cs ├── Decorators ├── WhatIsDecorators.py └── __init__.py ├── DynamicProgramming ├── BitMask.py ├── __init__.py ├── abbrevation.py ├── factorial.py ├── rapdiFibonacci.py └── wordBreak.py ├── ExceptionalHandling ├── EHFinally.py ├── ForGoodUnderstanding.py ├── __pycache__ │ ├── three.cpython-37.pyc │ └── two.cpython-37.pyc ├── one.py ├── test.py ├── three.py └── two.py ├── Excersise ├── 24HourTimeFormat.py ├── CheckingInternetIsWorking.py ├── CheckingStringPalindromeOrNot.py ├── CompareTriplets.py ├── ConverFloatPointNumberToDecimal.py ├── ConverFloatToDecimal.py ├── ConvertDecimalToBinary.py ├── DiagonalSum.py ├── DiscoverMonk.py ├── DynamicProgramming.py ├── EvenNumEvenIndex_42.py ├── EvenOrOddWithoutUsingModDiv.py ├── EvenTree.py ├── Factorial.py ├── FindDigits.py ├── FindNextGreaterElement.py ├── FindingNumbers.py ├── FindingTraceInBreadthFirstSearch.py ├── FolderSizeOfDirectory.py ├── Fraction.py ├── GoldRate │ ├── GoldRate.py │ └── Todo.txt ├── Hashing.py ├── HelloWorld.py ├── Himanshu.py ├── LargestPrimeNumber.py ├── LibraryFineCollections.py ├── ListAddition.py ├── Min-MaxSum.py ├── MostCommon.py ├── NaviBeer.py ├── OrderedDictionary.py ├── PalindromeChecker.py ├── PlusMinus.py ├── PrimNumFromList.py ├── RemoveDuplicateStrings.py ├── SecondHighestNumber.py ├── SherlockSquares.py ├── StairCase.py ├── TrailingZero.py ├── TrendingLaptopBrands.py ├── UniqueMaximumNumber.py ├── WordOrder.py ├── checkPalindrome.py ├── fibonacci.py ├── first-M-MultiplesOfN ├── namedtuple.py ├── python_encryption.py ├── toSwathi.py ├── usingNumpy.py └── youtubeDownload.py ├── Filter ├── WhatIsFilter.py └── __init__.py ├── FruitStore ├── Bill.py ├── FStore.py ├── UserHandler.py ├── __init__.py ├── __pycache__ │ ├── Bill.cpython-37.pyc │ ├── FStore.cpython-37.pyc │ ├── UserHandler.cpython-37.pyc │ └── log.cpython-37.pyc ├── log.py ├── main.py ├── scoring.py ├── stock.json └── userMenu.txt ├── GLOBAL_LOG.log ├── Generators ├── DiffBtwnGenratorsAndIterator.py ├── LotteryExample.py ├── __init__.py └── basicGenerators.py ├── HashTable ├── 1. Implementation_Tutorial.py └── __init__.py ├── Iterator └── What.py ├── Lambda ├── WhatIsLambda.py └── timecomplexity.py ├── Map ├── WhatIsMap.py └── __init__.py ├── MathOperationAndLoops ├── ArithmeticOperators.py ├── BaiscForLoop.py ├── IntegerAllSizes.py ├── Mod Divmod.py ├── Mod Power.py ├── Number Swaping.py ├── PerformingDivision.py ├── PrintSpeciality.py └── getInputFromUser.py ├── MultiTasking ├── Asynchronous.py ├── MultiProcessing.py └── Synchronous.py ├── OOP ├── AbstractExample │ └── BaseAbstractClass │ │ ├── ABC.py │ │ └── DerivedClass.py ├── Encapsulation │ ├── Data Abstraction.py │ └── DataHiding.py ├── Inheritance │ ├── HierarchicalInheritance.py │ ├── HybridInheritance.py │ ├── MultilevelInheritance.py │ ├── MultipleInheritance.py │ ├── MultipleInheritanceBestExample.py │ └── SingleInheritance.py ├── Others │ ├── AnonymousFunction │ │ ├── MapFilterReduceLamba.py │ │ └── __init__.py │ ├── Decorators │ │ ├── DecoratorsExample.py │ │ └── decorators.py │ ├── ExceptionalHandling │ │ ├── CustomException.py │ │ ├── TryExcept.py │ │ └── __init__.py │ ├── FileHandling │ │ ├── FileReadingWriting.py │ │ ├── input.txt │ │ ├── input1.txt │ │ ├── ram.txt │ │ └── readLog.py │ └── MapFilterReduceLamba.py ├── Polymorphism │ ├── MethodOverloading.py │ ├── MethodOverloading_Achievable.py │ ├── MethodOverloading_NotEfficient.py │ ├── MethodOverriding.py │ └── SuperMethod.py └── __init__.py ├── Paramiko ├── __init__.py └── paramiko.py ├── QDataStructure ├── Deque_Implementation.py ├── RenamingAFile.py └── __init__.py ├── QR ├── HelloWorldQR.png ├── HelloWorldQR.py └── QR_Encode.py ├── RE ├── BeginerLevel.py └── trail.py ├── README.md ├── Recursion ├── RecursionTechniq.py └── TowersOfHanoi.py ├── Search Technique ├── BinarySearch.py └── SequentialSearch.py ├── Sets ├── Intro.py ├── NoIdea.py ├── Set.add().py ├── Sets.discard(),.remove(),.pop().py ├── checkStrictSubset.py ├── checkSubset.py ├── intersection.py ├── itertools.py ├── permutations.py ├── symettricDifference.py └── tutorial.py ├── Sort ├── BubbleSort.py ├── InsertionSort.py ├── MergeSort.py └── QuickSort.py ├── Strings ├── Capitalize.py ├── CompareTwoStrings.py ├── DesignerDoorMat.py ├── FindAString.py ├── MinionGame.py ├── Mutations.py ├── StringFormatting.py ├── StringSplitAndJoin.py ├── StringValidators.py ├── SwapCases.py └── TextWrap.py ├── Zip ├── HowToUnzip.py ├── WhatIsZip.py └── __init__.py ├── general.log ├── input1.txt ├── itertools ├── Triplets.py ├── itertools_product.py └── what.py └── test.json /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | .gitignore 3 | .idea/ 4 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "github.copilot" 4 | ] 5 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Python: Current File (Integrated Terminal)", 9 | "type": "python", 10 | "request": "launch", 11 | "program": "${file}", 12 | "console": "integratedTerminal" 13 | }, 14 | { 15 | "name": "Python: Remote Attach", 16 | "type": "python", 17 | "request": "attach", 18 | "port": 5678, 19 | "host": "localhost", 20 | "pathMappings": [ 21 | { 22 | "localRoot": "${workspaceFolder}", 23 | "remoteRoot": "." 24 | } 25 | ] 26 | }, 27 | { 28 | "name": "Python: Module", 29 | "type": "python", 30 | "request": "launch", 31 | "module": "enter-your-module-name-here", 32 | "console": "integratedTerminal" 33 | }, 34 | { 35 | "name": "Python: Django", 36 | "type": "python", 37 | "request": "launch", 38 | "program": "${workspaceFolder}/manage.py", 39 | "console": "integratedTerminal", 40 | "args": [ 41 | "runserver", 42 | "--noreload", 43 | "--nothreading" 44 | ], 45 | "django": true 46 | }, 47 | { 48 | "name": "Python: Flask", 49 | "type": "python", 50 | "request": "launch", 51 | "module": "flask", 52 | "env": { 53 | "FLASK_APP": "app.py" 54 | }, 55 | "args": [ 56 | "run", 57 | "--no-debugger", 58 | "--no-reload" 59 | ], 60 | "jinja": true 61 | }, 62 | { 63 | "name": "Python: Current File (External Terminal)", 64 | "type": "python", 65 | "request": "launch", 66 | "program": "${file}", 67 | "console": "externalTerminal" 68 | } 69 | ] 70 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "C:\\Python37\\python.exe" 3 | } -------------------------------------------------------------------------------- /ArgsKwArgs/KwArgs.py: -------------------------------------------------------------------------------- 1 | # Example 3: Using **kwargs to pass the variable keyword arguments to the function 2 | def intro(**data): 3 | print("\nData type of argument:",type(data)) 4 | 5 | for key, value in data.items(): 6 | print("{} is {}".format(key,value)) 7 | 8 | intro(Firstname="Sita", Lastname="Sharma", Age=22, Phone=1234567890) 9 | intro(Firstname="John", Lastname="Wood", Email="johnwood@nomail.com", Country="Wakanda", Age=25, Phone=9876543210) 10 | # When we run the above program, the output will be 11 | 12 | # Data type of argument: 13 | # Firstname is Sita 14 | # Lastname is Sharma 15 | # Age is 22 16 | # Phone is 1234567890 17 | 18 | # Data type of argument: 19 | # Firstname is John 20 | # Lastname is Wood 21 | # Email is johnwood@nomail.com 22 | # Country is Wakanda 23 | # Age is 25 24 | # Phone is 9876543210 25 | 26 | 27 | # In the above program, we have a function intro() with **data as a parameter. We passed two dictionaries with variable argument length to the intro() function. We have for loop inside intro() function which works on the data of passed dictionary and prints the value of the dictionary. 28 | 29 | ''' 30 | Things to Remember: 31 | 1. *args and *kwargs are special keyword which allows function to take variable length argument. 32 | 2. *args passes variable number of non-keyworded arguments list and on which operation of the list can be performed. 33 | 3. **kwargs passes variable number of keyword arguments dictionary to function on which operation of a dictionary can be performed. 34 | 4. *args and **kwargs make the function flexible. 35 | ''' -------------------------------------------------------------------------------- /Classes/composition.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/Classes/composition.py -------------------------------------------------------------------------------- /Classes/decorators.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/Classes/decorators.py -------------------------------------------------------------------------------- /Classes/globalVariables.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import math 4 | 5 | 6 | 7 | class AreaOfCircle(): 8 | PI_VALUE = 3.14 9 | 10 | def __init__(self, name, gender): 11 | self.name = name 12 | self.gender = gender 13 | 14 | def areaCalculation(self, radius): 15 | return 3.14 * (radius**2) 16 | 17 | 18 | # sampleObj = AreaOfCircle() 19 | 20 | # print(sampleObj) 21 | 22 | # value = sampleObj.areaCalculation(5) 23 | 24 | # print(value) 25 | 26 | # what is the class attributes the? 27 | 28 | # print(AreaOfCircle.PI_VALUE) 29 | 30 | # print(sampleObj.PI_VALUE) 31 | 32 | ############### 33 | 34 | ramObj = AreaOfCircle('Ram', 'Male') 35 | 36 | print(ramObj.name) 37 | print(ramObj.gender) 38 | 39 | 40 | # how about this? 41 | 42 | print(AreaOfCircle.name) -------------------------------------------------------------------------------- /Classes/inheritance.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/Classes/inheritance.py -------------------------------------------------------------------------------- /Classes/session-on-class.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Employee(): 4 | 5 | def __init__(self, name, age): 6 | self.name = name 7 | self.age = age 8 | self.pi = 3.142 9 | 10 | # wrong way for gettting employee name from the object. 11 | # def getEmployeeName(self, inputFromUser): 12 | # print("Employee name is ", inputFromUser) 13 | 14 | def getNewEmployeeName(self): 15 | print("new employee name is ", self.name) 16 | 17 | def getEmployeeAge(self): 18 | print(self.name + "'s age is " + self.age) 19 | 20 | import random 21 | 22 | class Bank(): 23 | def __init__(self, name, age, dob, address): 24 | self.name = name 25 | self.age = age 26 | self.dob = dob 27 | self.address = address 28 | self.accountNumber = random.randint(1,1000) 29 | self.accountBalance = 0 30 | print("Your account got created, " + self.name) 31 | 32 | 33 | def getCustomerAccountInfo(self): 34 | print("Hello " + self.name) 35 | print("Your account got created, here's your account number " , str(self.accountNumber)) 36 | print("Your current balance of your account is ", str(self.accountBalance)) 37 | 38 | def getMyBirthDate(self): 39 | print('Hello ' + self.name + ' you birthday is ' + self.dob) 40 | 41 | 42 | ramIsTheCustomer = Bank('Ram', 26, '1/1/2020', 'London') 43 | 44 | ramIsTheCustomer.getCustomerAccountInfo() 45 | 46 | ramIsTheCustomer.getMyBirthDate() 47 | 48 | 49 | 50 | ram = Employee("Ram") 51 | san = Employee("Sanjay") 52 | 53 | print(ram) 54 | print("--------") 55 | # print(ram.getEmployeeName("Ram")) 56 | 57 | ram.getNewEmployeeName() 58 | 59 | san.getNewEmployeeName() 60 | sanjay.getEmployeeAge() 61 | 62 | 63 | 64 | 65 | class EmployeeV2(): 66 | def __init__(self, name, age, sex): 67 | self.name = name 68 | self.age = age 69 | self.sex = sex 70 | 71 | def getEmployeeName(self): 72 | return("Employee name is " + self.name) 73 | -------------------------------------------------------------------------------- /Classes/special_class_methods.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/Classes/special_class_methods.py -------------------------------------------------------------------------------- /Classes/state.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Have you heard about State in Programming Language? 4 | 5 | # Very frequentlt this terminology is been used in Entity or Object Communication. 6 | 7 | 8 | # Let's say we have to model a bank account with support for deposit and withdraw operations. 9 | # One way to do that is by using global state 10 | 11 | balance = 0 #balance variable is global of the program, if this below snippet is inside the class, we can call as class attribute. 12 | 13 | def deposit(amount): 14 | global balance 15 | balance += amount 16 | return balance 17 | 18 | def withdraw(amount): 19 | global balance 20 | balance -= amount 21 | return balance 22 | 23 | sanjay = deposit(100) 24 | print(sanjay) 25 | 26 | # The above example is good enough only if we want to have just a single account. Did you understand what I said? 27 | 28 | 29 | # ******Things start getting complicated if want to model multiple accounts.****** 30 | 31 | # We can solve the problem by making the state local, probably by using a dictionary to store the state. 32 | 33 | def make_account(): 34 | return {'balance': 0} 35 | 36 | def putDeposit(account, amount): 37 | account['balance'] += amount 38 | return account['balance'] 39 | 40 | def withdrawMoney(account, amount): 41 | account['balance'] -= amount 42 | return account['balance'] 43 | 44 | def checkBalance(account): 45 | return account['balance'] 46 | 47 | 48 | sanjay = make_account() 49 | 50 | ram = make_account() 51 | 52 | # by default, when someone creates an account, balance will show 0. 53 | putDeposit(sanjay, 5000) 54 | 55 | # what is sanjay's balance amount now? 56 | print("Sanjay has " + str(checkBalance(sanjay)) + " in his account!") 57 | 58 | print("Sanjay has withdrawn 2500 rs from the account, therefore the remaining balance is " + str(withdrawMoney(sanjay, 2500))) 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /Cryptography/__pycache__/rsa.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/Cryptography/__pycache__/rsa.cpython-37.pyc -------------------------------------------------------------------------------- /Cryptography/rsa.py: -------------------------------------------------------------------------------- 1 | from Crypto.PublicKey import RSA 2 | from Crypto.Cipher import PKCS1_OAEP 3 | import binascii 4 | 5 | keyPair = RSA.generate(1024) 6 | 7 | pubKey = keyPair.publickey() 8 | # print(f"Public key: (n={hex(pubKey.n)}, e={hex(pubKey.e)})") 9 | 10 | pubKeyPEM = pubKey.exportKey() 11 | print(pubKeyPEM.decode('ascii')) 12 | 13 | 14 | # print(f"Private key: (n={hex(pubKey.n)}, d={hex(keyPair.d)})") 15 | privKeyPEM = keyPair.exportKey() 16 | print(privKeyPEM.decode('ascii')) 17 | 18 | msg = b'D$bd1@k3' 19 | encryptor = PKCS1_OAEP.new(pubKey) 20 | encrypted = encryptor.encrypt(msg) 21 | print("Encrypted:", binascii.hexlify(encrypted)) 22 | 23 | 24 | decryptor = PKCS1_OAEP.new(keyPair) 25 | decrypted = decryptor.decrypt(encrypted) 26 | print('\nDecrypted:', decrypted.decode("utf-8")) 27 | 28 | 29 | -------------------------------------------------------------------------------- /Cryptography/test.py: -------------------------------------------------------------------------------- 1 | # Basic Fernet 2 | 3 | # msg = "I am going to encrypt this sentence using Fernet" 4 | msg = "D$bd1@k3" 5 | 6 | from cryptography import fernet 7 | from cryptography.fernet import Fernet 8 | 9 | # first generate key 10 | eKey = Fernet.generate_key() 11 | print("\nKey is : " + eKey.decode()) 12 | # print("\nType of key is .. " + str(type(eKey))) 13 | print("\nKey is : " + str(len(eKey.decode()))) 14 | 15 | # create a class instance object 16 | f1 = Fernet(eKey) 17 | 18 | eMsg = f1.encrypt(msg.encode()) # f1 instance can encrypt only bytes 19 | print("\nEncrypted message is - " + eMsg.decode()) 20 | print("\nEncrypted message is -" + str(len(eMsg))) 21 | 22 | # decrypt with same instance 23 | dMsg = f1.decrypt(eMsg).decode() 24 | print("\nDecrypted Message - " + dMsg) -------------------------------------------------------------------------------- /DataCollectionTypes/Dictionary/Task2.py: -------------------------------------------------------------------------------- 1 | org = [] 2 | def getOrgNames(fromGivenInput): 3 | for orgInfo in fromGivenInput: 4 | if not orgInfo['orgName'] in org: 5 | org.append(orgInfo['orgName']) 6 | return org 7 | 8 | def employeeInfoBasedOnOrg(orgName, userGivenInput): 9 | output = { orgName : []} 10 | tempOp = {} 11 | 12 | for info in userGivenInput: 13 | if info['orgName'] == orgName: 14 | tempOp[info['empName']] = info['empSal'] 15 | 16 | output[orgName].append(tempOp) 17 | print(output) 18 | 19 | if __name__ == '__main__': 20 | 21 | givenInput = [ 22 | { 23 | "orgName": "techM", 24 | "empName": "name1", 25 | "empSal": "40000" 26 | }, 27 | { 28 | "orgName": "techM", 29 | "empName":"name2", 30 | "empSal": "5000" 31 | }, 32 | { 33 | "orgName": "techM", 34 | "empName": "name3", 35 | "empSal": "50000" 36 | }, 37 | { 38 | "orgName": "Mahindra", 39 | "empName": "name4", 40 | "empSal": "55000" 41 | }, 42 | { 43 | "orgName": "Mahindra", 44 | "empName": "name5", 45 | "empSal": "45000" 46 | }, 47 | { 48 | "orgName": "Mahindra", 49 | "empName": "name6", 50 | "empSal": "35000" 51 | } 52 | ] 53 | 54 | 55 | listOfOrgs = getOrgNames(givenInput) 56 | 57 | for orgName in listOfOrgs: 58 | employeeInfoBasedOnOrg(orgName, givenInput) 59 | 60 | 61 | from collections import Counter 62 | 63 | eop = {} 64 | d1 = {'apple': 'sanjay', 'orange': 'sanjay', 'banana': 'sanjay'} 65 | 66 | # for k,v in d1.items(): 67 | # if type(v) == str: 68 | # eop[k] = len(v) 69 | 70 | # print(Counter(eop)) 71 | 72 | print(Counter({k:len(v) for k,v in d1.items()})) -------------------------------------------------------------------------------- /DataCollectionTypes/Dictionary/Tutorials_1.py: -------------------------------------------------------------------------------- 1 | # Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}. 2 | # Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. 3 | 4 | # How to create a dictionary with some values? 5 | 6 | myDict = {'name': 'AnyName', 'id': 123, 'info': 'value of id not neccessarily need to be string since it has integer as numbers'} 7 | 8 | print(myDict) # Output: {'name': 'AnyName', 'id': 123, 'info': 'value of id not neccessarily need to be string since it has integer as numbers'} 9 | 10 | print(myDict.keys()) #Output: dict_keys(['name', 'id', 'info']) 11 | 12 | 13 | 14 | from collections import Counter -------------------------------------------------------------------------------- /DataCollectionTypes/Dictionary/to_delete_in_future_sample.py: -------------------------------------------------------------------------------- 1 | # import pyodbc 2 | # import json 3 | 4 | # # reads N number of lines of queries 5 | # def readSQL(): 6 | # with open('queries.sql', 'r') as sqlFile: 7 | # line = sqlFile.readlines() 8 | # return line 9 | 10 | # def sqlConnect(): 11 | # conn = pyodbc.connect('Driver={SQL Server};' 12 | # 'Server=DESKTOP-AV96G7N;' 13 | # 'Database=AdventureWorks2019;' 14 | # 'Trusted_Connection=yes;') 15 | # cursor = conn.cursor() 16 | # return cursor 17 | 18 | # def executeSQLQuery(cursorObj, query): 19 | # execResult = cursorObj.execute(query) 20 | # return execResult 21 | 22 | # def getCursorData(cursorObj): 23 | # outputDict = {} 24 | 25 | # outputDict['ID'] = cursorObj[0] 26 | # outputDict['NI_ID'] = cursorObj[1] 27 | # outputDict['JOB_TITLE'] = cursorObj[2] 28 | 29 | # return outputDict 30 | 31 | # if _name_ == "__main__": 32 | # sqlLine = readSQL() 33 | # connectionString = sqlConnect() 34 | 35 | # sanjOp = {} 36 | 37 | # for rowLine in sqlLine: 38 | # execResult = executeSQLQuery(connectionString, rowLine) 39 | # for rows in execResult: 40 | # print(rows) 41 | 42 | # # outputResult = list(sqlConnect()) 43 | # finalListOutput = [getCursorData(row) for row in outputResult] 44 | # outputJson = {} 45 | # outputJson['Result'] = finalListOutput 46 | 47 | # """ Below code is used to create a json file if not available and dumps the output """ 48 | # with open('data.json', 'w') as file: 49 | # json.dump(outputJson, file) 50 | 51 | # """ below code with append the out to already available json file """ 52 | # with open('data.json', 'w') as file: 53 | # json.zzzzzzzz(outputJson, file) 54 | 55 | 56 | # Ram's expectation is to have two lines of json object in a data.json file. 57 | # Here's tee sample, 58 | 59 | # {'result1': [{},{},{}]} 60 | # {'result2': [{},{},{}]} 61 | 62 | 63 | import json 64 | intellipaat = {"course":"python", "topic":"Python JSON"} 65 | intellipaat_json = json.dumps(intellipaat) 66 | 67 | print(type(intellipaat_json)) 68 | 69 | testFile = open('test.json', 'w') 70 | 71 | for i in range(1,5): 72 | testFile.write(intellipaat_json + "\n") 73 | 74 | 75 | test = {} 76 | for i in range(0,10): 77 | test['result'+str(i)] = [] 78 | 79 | print(test) -------------------------------------------------------------------------------- /DataCollectionTypes/List/3. ListComprehension.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # Let's learn about list comprehensions! You are given three integers X,YX,Y and ZZ representing the dimensions of a cuboid. You have to print a list of all possible coordinates on a 3D grid where the sum of XXii ++ YYii ++ ZZii is not equal to NN. If X=2X=2, the possible values of XXii can be 00, 11 and 22. The same applies to YY and ZZ. 3 | # Input Format 4 | 5 | # Four integers X,Y,ZX,Y,Z and NN each on four separate lines, respectively. 6 | 7 | # Output Format 8 | # Print the list in lexicographic increasing order. 9 | 10 | # Sample Input 11 | 12 | # 1 13 | # 1 14 | # 1 15 | # 2 16 | # Sample Output 17 | 18 | # [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]] 19 | 20 | x, y, z, n = int(input()), int(input()), int(input()), int(input()) 21 | print([[a, b, c] for a in range(0, x+1) for b in range(0, y+1) for c in range(0, z+1) if a + b + c != n]) 22 | -------------------------------------------------------------------------------- /DataCollectionTypes/List/4. ListTutorial.py: -------------------------------------------------------------------------------- 1 | # ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', 2 | # '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', 3 | # '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', 4 | # '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', ' 5 | # __subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 6 | # 'sort'] 7 | 8 | animals = ['Tiger', 'Lion', 'Dog', 'Zebra'] 9 | 10 | # create an empty List 11 | 12 | # __add__(self, element) - to concatinate two list and make a single list 13 | sampleNumbers = [13,4356,65,4776] 14 | print(sampleNumbers.__add__(animals)) #print(sampleList) => [13, 4356, 65, 4776, 'Tiger', 'Lion', 'Dog', 'Zebra'] 15 | 16 | 17 | # __contains__ - check whether the element is available in list or not. 18 | print(animals.__contains__('Mouse')) #False 19 | print(animals.__contains__('Lion')) #True 20 | 21 | 22 | # __delattr__ - delete element in the list, by supplying its index value 23 | # sampleNumbers.__delattr__(13) 24 | # print(sampleNumbers) 25 | 26 | #__delitem__ - delete item from the list, by supplying its index value 27 | sampleNumbers.append(4) 28 | print(sampleNumbers) 29 | sampleNumbers.__delitem__(1) # 4356 will be removed, whose index value is 1 30 | print(sampleNumbers) 31 | 32 | 33 | # __setitem__ - inserting value (10) in it's (1) index place. 34 | sampleNumbers.__setitem__(1,10) 35 | print(sampleNumbers) 36 | 37 | # __eq__ - to compare two list and returns bool value (True or false) 38 | print(sampleNumbers.__eq__(animals)) # false 39 | 40 | # __format__ - 41 | print(sampleNumbers.__format__('')) # '[13, 65, 4776, 4]' 42 | print(type(sampleNumbers.__format__(''))) # 43 | 44 | # Count 45 | sampleNumbers.extend([1,1,1,1,1,1,11,1,1,1,1,1,1]) 46 | print("Totally there are ", sampleNumbers.count(1), " times 1 repeated inside the list") 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /DataCollectionTypes/List/5. NestedList.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # Input Format 4 | 5 | # The first line contains an integer, NN, the number of students. 6 | # The 2N2N subsequent lines describe each student over 22 lines; the first line contains a student's name, and the second line contains their grade. 7 | 8 | # Constraints 9 | # 10 | # 2?N?52?N?5 11 | # There will always be one or more students having the second lowest grade. 12 | # Output Format 13 | 14 | # Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line. 15 | 16 | # Sample Input 17 | 18 | # 5 19 | # Harry 20 | # 37.21 21 | # Berry 22 | # 37.21 23 | # Tina 24 | # 37.2 25 | # Akriti 26 | # 41 27 | # Harsh 28 | # 39 29 | # Sample Output 30 | 31 | # Berry 32 | # Harry 33 | # Explanation 34 | 35 | # There are 55 students in this class whose names and grades are assembled to build the following list: 36 | 37 | # students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]] 38 | # The lowest grade of 37.237.2 belongs to Tina. The second lowest grade of 37.2137.21 belongs to both Harry and Berry, 39 | # so we order their names alphabetically and print each name on a new line. 40 | 41 | n = int(input()) 42 | marks = [[input(), float(input())] for i in range(n)] 43 | scores = sorted({s[1] for s in marks}) 44 | result = sorted(s[0] for s in marks if s[1] == scores[1]) 45 | print ('\n'.join(result)) 46 | 47 | #ends -------------------------------------------------------------------------------- /DataCollectionTypes/List/6. CombiningAllInnerListIntoOneList.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | class singleList: 4 | def appendingAllElementsInAList(self, alist): 5 | finalOutput = [] 6 | for i in alist: 7 | if type(i) == list: 8 | for z in i: 9 | finalOutput.append(z) 10 | else: 11 | finalOutput.append(i) 12 | 13 | print("finally the output is..") 14 | print(finalOutput) 15 | 16 | 17 | def genericSolutionUsingRecursive(inputList): 18 | pass 19 | 20 | def genericSolutionWithoutUsingRecursive(inputList): 21 | outputArray = [] 22 | for num in inputList: 23 | if type(num) == list: 24 | inputList.extend(num) 25 | else: 26 | outputArray.append(num) 27 | return outputArray 28 | 29 | 30 | if __name__ == '__main__': 31 | 32 | firstInputList = ['a', 'b', 'c', 'd'] 33 | 34 | firstInputList.append(list(range(1, 4))) # [1,2,3] 35 | print(firstInputList) # ['a', 'b', 'c', 'd', [1, 2, 3]] 36 | 37 | ob = singleList() 38 | ob.appendingAllElementsInAList(firstInputList) 39 | 40 | # Take this example, here elements inside the below lists are again list. 41 | sampleList = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] 42 | flatList = [] 43 | for listItem in sampleList: 44 | for item in listItem: 45 | flatList.append(item) 46 | 47 | # print(flatList) 48 | 49 | # hey the above code works only when all the elements inside the list, is also a type as list. 50 | # it wont work - sampleList = [[1, 2, 3], [4, 5, 6], [7], [8, 9], 10] 51 | # here's the solution. 52 | 53 | sampleListUC2 = [[1, 2, 3], [4, 5, 6], [7], [8, 9], 10] 54 | ob.appendingAllElementsInAList(sampleListUC2) 55 | 56 | ############## OTHER Best Solutions ############## 57 | 58 | # so from the above inputs, we understood, a list can have n number of arbitary items/list inside it. 59 | # what if the input is like [[1,2,3], [4,5,6], [[7,8,9], [10,[11,12, [13, 14, 15,]]]]] 60 | # we must have a generic function. 61 | 62 | sampleListUC3 = [[1,2,3], [4,5,6], [[7,8,9], [10,[11,12, [13, 14, 15,]]]]] 63 | answer = genericSolutionWithoutUsingRecursive(sampleListUC3) 64 | print(answer) # output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] 65 | 66 | # here's the most fun code but only works when input is like [[1,2], [3,4], [5], [6]] 67 | # print(sum(sampleListUC2, [])) 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /DataCollectionTypes/List/7. OrderedList.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # We will now consider a type of list known as an ordered list. 4 | # For example, if the list of integers shown above were an ordered list (ascending order), 5 | # then it could be written as 17, 26, 31, 54, 77, and 93. Since 17 is the smallest item, it occupies the first position in the list. 6 | # Likewise, since 93 is the largest, it occupies the last position. 7 | 8 | # OrderedList() creates a new ordered list that is empty. It needs no parameters and returns an empty list. 9 | # add(item) adds a new item to the list making sure that the order is preserved. It needs the item and returns nothing. Assume the item is not already in the list. 10 | # remove(item) removes the item from the list. It needs the item and modifies the list. Assume the item is present in the list. 11 | # search(item) searches for the item in the list. It needs the item and returns a boolean value. 12 | # isEmpty() tests to see whether the list is empty. It needs no parameters and returns a boolean value. 13 | # size() returns the number of items in the list. It needs no parameters and returns an integer. 14 | # index(item) returns the position of item in the list. It needs the item and returns the index. Assume the item is in the list. 15 | # pop() removes and returns the last item in the list. It needs nothing and returns an item. Assume the list has at least one item. 16 | # pop(pos) removes and returns the item at position pos. It needs the position and returns the item. Assume the item is in the list. -------------------------------------------------------------------------------- /DataCollectionTypes/List/8. MostRepeatedElementsInList.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | from collections import Counter 3 | import operator 4 | 5 | # TODO: Below commented code must be cleaned or refactored, after understanding the usage of this logic. 6 | # def mostTrendingBrand(numOfResponse, listOfBrands): 7 | # if numOfResponse>1: 8 | # brandCount = Counter(listOfBrands) 9 | # onlyCount = [] 10 | # for ke,va in brandCount.iteritems(): 11 | # onlyCount.append(va) 12 | # trendingCount = max(onlyCount) 13 | # trendingBrandOutput = [] 14 | # for ke,va in brandCount.iteritems(): 15 | # if trendingCount == va: 16 | # trendingBrandOutput.append(ke) 17 | # for i in trendingBrandOutput: 18 | # print("Most repeated item is",i) 19 | 20 | 21 | # currently this function takes input as a list, to find maximum repeated elements in the list. 22 | def mostTrendingBrancAlternateSolution(userInputs): 23 | finalOp = {} 24 | for element in userInputs: 25 | finalOp[element] = userInputs.count(element) 26 | print(finalOp) 27 | for key, value in finalOp.items(): 28 | if value == max(list(finalOp.values())): 29 | print("Maximum repeated brand is ", key) 30 | 31 | if __name__ == "__main__": 32 | x = int(input()) 33 | userInputList = [] 34 | for i in range(0, x): 35 | temp = input() 36 | userInputList.append(temp) 37 | # mostTrendingBrand(x, userInputList) 38 | mostTrendingBrancAlternateSolution(userInputList) 39 | 40 | 41 | # Sample output 42 | # 5 43 | # 'a' 44 | # 'b' 45 | # 'a' 46 | # 'a' 47 | # 'b' 48 | 49 | # Most repeated item is 'a' 50 | -------------------------------------------------------------------------------- /DataCollectionTypes/List/FindCommonElements.py: -------------------------------------------------------------------------------- 1 | 2 | def __onlyCommonEle(p): 3 | if len(p) == 0: 4 | return 5 | print(set(p[0]).intersection(*p)) 6 | 7 | def findCommonElements(*args): 8 | if len(args) == 0: 9 | return 10 | __onlyCommonEle([i for i in args if type(i) == list]) 11 | 12 | 13 | findCommonElements([1,2,3], 'a', 'c', ['a','b',1,2,4]) -------------------------------------------------------------------------------- /DataCollectionTypes/List/MoveAllZerosToEnd.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | def moveZerosToEnd(inputList): 4 | if type(inputList) is not list: 5 | return 6 | 7 | if 0 in inputList : 8 | ex = dict(Counter(inputList)) 9 | if (0 in ex.keys()): 10 | op = [i for i in inputList if i != 0] 11 | for i in range(ex[0]): 12 | op.append(0) 13 | else: 14 | return "No Zeros exist" 15 | 16 | 17 | print(op) 18 | 19 | 20 | # OMKAR solution - isn't working. 21 | # def move(arr): 22 | # count = 0 23 | # for a in arr: 24 | # if not a == 0: 25 | # arr[count] = a 26 | # count += 1 27 | # while count < len(nums): 28 | # arr[count] = 0 29 | # count += 1 30 | 31 | 32 | 33 | moveZerosToEnd([1,2,3,4,0,0,0,0,3,4,43,43,435453,545455,7676]) 34 | print(moveZerosToEnd([1,2,3,4,4])) 35 | 36 | -------------------------------------------------------------------------------- /DataCollectionTypes/Sets/2. SymettricDifference.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # Task 4 | # Given 22 sets of integers, MM and NN, print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either MM or NN but do not exist in both. 5 | # 6 | # Input Format 7 | # 8 | # The first line of input contains an integer, MM. 9 | # The second line contains MM space-separated integers. 10 | # The third line contains an integer, NN. 11 | # The fourth line contains NN space-separated integers. 12 | # 13 | # Output Format 14 | # 15 | # Output the symmetric difference integers in ascending order, one per line. 16 | # 17 | # Sample Input 18 | # 19 | # 4 20 | # 2 4 5 9 21 | # 4 22 | # 2 4 11 12 23 | # Sample Output 24 | # 25 | # 5 26 | # 9 27 | # 11 28 | # 12raw_input 29 | 30 | input() 31 | a=set(map(int,().split())) 32 | input() 33 | b=set(map(int,input().split())) 34 | c=a.symmetric_difference(b) 35 | for n in sorted(list(c)): 36 | print (n) -------------------------------------------------------------------------------- /DataCollectionTypes/Sets/Excercise/difference.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # 3 | # 4 | # Task 5 | # 6 | # 7 | # Students of District College have a subscription to English and French newspapers. Some students have subscribed to only the English newspaper, some have subscribed to only the French newspaper, and some have subscribed to both newspapers. 8 | # 9 | # You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to only English newspapers. 10 | # 11 | # 12 | # Input Format 13 | # 14 | # 15 | # The first line contains the number of students who have subscribed to the English newspaper. 16 | # The second line contains the space separated list of student roll numbers who have subscribed to the English newspaper. 17 | # The third line contains the number of students who have subscribed to the French newspaper. 18 | # The fourth line contains the space separated list of student roll numbers who have subscribed to the French newspaper. 19 | # 20 | # Constraints 21 | # 22 | # 0 len(s2): 4 | for i in s1: 5 | print(i[0]) 6 | elif len(s1) < len(s2): 7 | pass 8 | else: 9 | pass 10 | 11 | def OneEditApart(s1, s2): 12 | if type(s1) != str and type(s2) != str: 13 | return False 14 | 15 | if len(s1) == 0 or len(s2) == 0: 16 | return False 17 | 18 | eS1 = enumerate(s1) 19 | eS2 = enumerate(s2) 20 | 21 | print(list(eS1)) 22 | print(list(eS2)) 23 | 24 | 25 | OneEditApart("Geeks", "Geek") 26 | print("s") -------------------------------------------------------------------------------- /DataStructures/FB/Spiral.py: -------------------------------------------------------------------------------- 1 | def spiralOrder(matrix): 2 | ans = [] 3 | 4 | if (len(matrix) == 0): 5 | return ans 6 | 7 | R = len(matrix) 8 | C = len(matrix[0]) 9 | seen = [[0 for i in range(C)] for j in range(R)] 10 | dr = [0, 1, 0, -1] 11 | dc = [1, 0, -1, 0] 12 | r = 0 13 | c = 0 14 | di = 0 15 | 16 | # Iterate from 0 to R * C - 1 17 | for i in range(R * C): 18 | ans.append(matrix[r]) 19 | seen[r] = True 20 | cr = r + dr[di] 21 | cc = c + dc[di] 22 | 23 | # if (0 <= cr and cr < R and 0 <= cc and cc < C and not(seen[cr][cc])): 24 | # r = cr 25 | # c = cc 26 | # else: 27 | # di = (di + 1) % 4 28 | # r += dr[di] 29 | # c += dc[di] 30 | return ans 31 | 32 | 33 | # Driver code 34 | a = [[1, 2, 3, 4], 35 | [5, 6, 7, 8], 36 | [9, 10, 11, 12], 37 | [13, 14, 15, 16]] 38 | 39 | for x in spiralOrder(a): 40 | print(x, end=" ") 41 | print() -------------------------------------------------------------------------------- /DataStructures/LinkedList/LinkedList.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/DataStructures/LinkedList/LinkedList.png -------------------------------------------------------------------------------- /DataStructures/LinkedList/LinkedList_Implementation.py: -------------------------------------------------------------------------------- 1 | # LinkedListData Structure Implementation 2 | 3 | 4 | #Description : A linked list is a linear data structure, in which the elements are not stored at contiguous 5 | # memory locations. The elements in a linked list are linked using pointers. 6 | 7 | # In simple words, a linked list consists of nodes where each node contains a data field 8 | # and a reference(link) to the next node in the list. 9 | 10 | class node: 11 | def __init__(self, data=None, next=None): 12 | self.data = data 13 | self.next = next 14 | 15 | 16 | class linked_list: 17 | def __init__(self): 18 | self.head = None 19 | 20 | # function to add a node at front 21 | def add_at_front(self, data): 22 | self.head = node(data=data, next=self.head) 23 | 24 | # function to check whether the list is empty 25 | def is_empty(self): 26 | return self.head == None 27 | 28 | # function to add node at the end 29 | def add_at_end(self, data): 30 | if not self.head: 31 | self.head = node(data=data) 32 | return 33 | curr = self.head 34 | while curr.next: 35 | curr = curr.next 36 | curr.next = node(data=data) 37 | 38 | # function to delete any node 39 | def delete_node(self, key): 40 | curr = self.head 41 | prev = None 42 | while curr and curr.data != key: 43 | prev = curr 44 | curr = curr.next 45 | if prev is None: 46 | self.head = curr.next 47 | elif curr: 48 | prev.next = curr.next 49 | curr.next = None 50 | 51 | # function to get the last node 52 | def get_last_node(self): 53 | temp = self.head 54 | while (temp.next is not None): 55 | temp = temp.next 56 | return temp.data 57 | 58 | # function to print the list nodes 59 | def print_list(self): 60 | node = self.head 61 | while node != None: 62 | print(node.data, end=" => ") 63 | node = node.next 64 | 65 | 66 | s = linked_list() 67 | s.add_at_front(5) 68 | s.add_at_end(8) 69 | s.add_at_front(9) 70 | s.print_list() -------------------------------------------------------------------------------- /DataStructures/Stack/Stack_Implementation.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # 4 | # Stack() creates a new stack that is empty. It needs no parameters and returns an empty stack. 5 | 6 | # push(item) adds a new item to the top of the stack. It needs the item and returns nothing. 7 | 8 | # pop() removes the top item from the stack. It needs no parameters and returns the item. The stack is modified. 9 | 10 | # peek() returns the top item from the stack but does not remove it. It needs no parameters. The stack is not modified. 11 | 12 | # isEmpty() tests to see whether the stack is empty. It needs no parameters and returns a boolean value. 13 | 14 | # size() returns the number of items on the stack. It needs no parameters and returns an integer. 15 | 16 | 17 | #The above information gives you clear understanding on Stacks Predefined functions. 18 | class Stack(object): 19 | 20 | """ A stack is an abstract data type that serves as a collection of 21 | elements with two principal operations: push() and pop(). push() adds an 22 | element to the top of the stack, and pop() removes an element from the top 23 | of a stack. The order in which elements come off of a stack are 24 | Last In, First Out (LIFO). 25 | https://en.wikipedia.org/wiki/Stack_(abstract_data_type) 26 | """ 27 | def __init__(self, defaultLimit = 10): 28 | self.items = [] 29 | self.limit = defaultLimit 30 | 31 | def push(self, newItem): 32 | if len(self.items) >= self.limit: 33 | raise StackOverflowError 34 | self.items.append(newItem) 35 | 36 | def pop(self): 37 | if self.items: 38 | return self.items.pop() 39 | else: 40 | raise IndexError("pop from an empty stack") 41 | 42 | def isEmpty(self): 43 | return self.items == [] 44 | 45 | def size(self): 46 | return len(self.items) 47 | 48 | def show(self): 49 | print(self.items) 50 | return self.items 51 | 52 | def peek(self): 53 | return self.items[0] 54 | 55 | def size(self): 56 | return len(self.items) 57 | 58 | class StackOverflowError(BaseException): 59 | pass 60 | 61 | 62 | if __name__ == '__main__': 63 | obj = Stack() 64 | obj.push(13) 65 | obj.show() 66 | obj.push('sanjay') 67 | obj.push('surya') 68 | obj.push(45) 69 | obj.show() 70 | obj.pop() 71 | obj.show() 72 | obj.size() 73 | obj.isEmpty() 74 | obj.show() 75 | -------------------------------------------------------------------------------- /DataStructures/test/test.cs: -------------------------------------------------------------------------------- 1 | // write a hello world program 2 | 3 | // console.log("Hello") 4 | console.writeLine("hhhh") -------------------------------------------------------------------------------- /Decorators/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/Decorators/__init__.py -------------------------------------------------------------------------------- /DynamicProgramming/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dynamic programming is a method for solving complex problems by breaking them down into simpler subproblems. It is applicable when the problem can be divided into overlapping subproblems that can be solved independently. The main idea is to store the results of subproblems to avoid redundant computations, which can significantly improve the efficiency of the algorithm. 3 | 4 | Dynamic programming is particularly useful in optimization problems where the goal is to find the best solution among many possible ones. It is commonly used in various fields such as operations research, economics, and computer science. 5 | 6 | Example: 7 | A classic example of dynamic programming is the Fibonacci sequence, where each number is the sum of the two preceding ones. Using dynamic programming, we can store the results of previously computed Fibonacci numbers to avoid redundant calculations. 8 | 9 | Here is a simple implementation of the Fibonacci sequence using dynamic programming in Python: 10 | 11 | def fibonacci(n): 12 | # Create an array to store Fibonacci numbers 13 | fib = [0] * (n + 1) 14 | # Base cases 15 | fib[0] = 0 16 | fib[1] = 1 17 | # Compute the Fibonacci numbers in a bottom-up manner 18 | for i in range(2, n + 1): 19 | fib[i] = fib[i - 1] + fib[i - 2] 20 | return fib[n] 21 | 22 | print(fibonacci(10)) # Output: 55 23 | 24 | In this example, the function `fibonacci` computes the nth Fibonacci number by storing the results of previous computations in an array, thus avoiding redundant calculations and improving efficiency. 25 | """ -------------------------------------------------------------------------------- /DynamicProgramming/abbrevation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Link : https://www.hackerrank.com/challenges/abbr/problem 3 | You can perform the following operation on some string, : 4 | 5 | 1. Capitalize zero or more of 's lowercase letters at some index i 6 | (i.e., make them uppercase). 7 | 2. Delete all of the remaining lowercase letters in . 8 | 9 | Example: 10 | a=daBcd and b="ABC" 11 | daBcd -> capitalize a and c(dABCd) -> remove d (ABC) 12 | """ 13 | 14 | def need_transform(first_input: str, second_input: str) -> bool: 15 | """ 16 | Determines if string first_input can be transformed into string second_input by capitalizing 17 | zero or more lowercase letters and deleting all other lowercase letters. 18 | 19 | Args: 20 | first_input (str): The original string. 21 | second_input (str): The target string. 22 | 23 | Returns: 24 | bool: True if first_input can be transformed into second_input, False otherwise. 25 | """ 26 | 27 | dp = [[False] * (len(first_input) + 1) for _ in range(len(second_input) + 1)] 28 | dp[0][0] = True 29 | 30 | for i in range(len(second_input)): 31 | for j in range(len(first_input) + 1): 32 | if dp[i][j]: 33 | if j < len(first_input) and first_input[i].upper() == second_input[j]: 34 | dp[i + 1][j + 1] = True 35 | if first_input[i].islower(): 36 | dp[i + 1][j] = True 37 | 38 | return dp[len(second_input)][len(first_input)] 39 | 40 | print(need_transform("daBcd", "ABC")) -------------------------------------------------------------------------------- /DynamicProgramming/factorial.py: -------------------------------------------------------------------------------- 1 | 2 | # The @lru_cache is a decorator provided by the functools module in Python. 3 | # It stands for "Least Recently Used cache". This decorator is used to cache 4 | # the results of function calls, so that if the function is called again with 5 | # the same arguments, the cached result is returned instead of recomputing 6 | # the result. This can significantly improve the performance of functions that 7 | # are called frequently with the same arguments, especially recursive 8 | # functions like your factorial function. 9 | 10 | # Here's a brief explanation of how it works in your code: 11 | 12 | # Caching: When factorial is called with a particular argument, 13 | # the result is stored in a cache. 14 | 15 | # Reuse: If factorial is called again with the same argument, 16 | # the cached result is returned immediately, avoiding the need for 17 | # recalculating the factorial. 18 | 19 | # Efficiency: This reduces the number of recursive calls and improves the 20 | # performance of the function. 21 | 22 | # To use @lru_cache, you need to import it from the functools module. 23 | # Here is your updated code with the necessary import statement: 24 | 25 | # Factorial of a number using memoization 26 | 27 | from functools import lru_cache 28 | 29 | 30 | @lru_cache 31 | def factorial(num: int) -> int: 32 | if num < 0: 33 | raise ValueError("Number should not be negative.") 34 | 35 | return 1 if num in (0, 1) else num * factorial(num - 1) 36 | 37 | 38 | if __name__ == "__main__": 39 | sample_input = 10 40 | print(factorial(sample_input)) -------------------------------------------------------------------------------- /DynamicProgramming/rapdiFibonacci.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | import sys 3 | 4 | 5 | def fibonacci(n: int) -> int: 6 | """ 7 | return F(n) 8 | >>> [fibonacci(i) for i in range(13)] 9 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] 10 | """ 11 | if n < 0: 12 | raise ValueError("Negative arguments are not supported") 13 | return _privateFibonacci(n)[0] 14 | 15 | 16 | # returns (F(n), F(n-1)) 17 | def _privateFibonacci(userGivenNumber: int) -> tuple[int, int]: 18 | if userGivenNumber == 0: # (F(0), F(1)) 19 | return (0, 1) 20 | 21 | # F(2n) = F(n)[2F(n+1) - F(n)] 22 | # F(2n+1) = F(n+1)^2+F(n)^2 23 | a, b = _privateFibonacci(userGivenNumber // 2) 24 | 25 | c = a * (b * 2 - a) 26 | d = a * a + b * b 27 | 28 | if n%2: 29 | return (d, c+d) 30 | else: 31 | return (c, d) 32 | 33 | 34 | if __name__ == "__main__": 35 | n = 5 36 | print(f"fibonacci({n}) is {fibonacci(n)}") -------------------------------------------------------------------------------- /ExceptionalHandling/EHFinally.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Important point to be noted. 4 | 5 | # finally block is always executed after leaving the try statement. 6 | # In case if some exception was not handled by except block, it is re-raised after execution of finally block. 7 | # finally block is used to deallocate the system resources. 8 | # One can use finally just after try without using except block, but no exception is handled in that case. 9 | 10 | # here's the sample exercise for understanding `finally` keyword in python 11 | 12 | try: 13 | inFromUser = int(input("Hello user, give me a integer input: ")) 14 | k = 5//inFromUser # raises divide by zero exception. 15 | print(k) 16 | 17 | # handles zerodivision exception 18 | except ZeroDivisionError: 19 | print("Can't divide by zero") 20 | except TypeError: 21 | print("Given in put is not in a right datatype") 22 | 23 | finally: 24 | # this block is always executed 25 | # regardless of exception generation. 26 | print('This is always executed') 27 | for num in list(range(0,10)): 28 | if num%2 ==0: 29 | continue 30 | print(num) 31 | 32 | # have you heard about break/continue 33 | 34 | # by default continue will not support inside finally 35 | # from 3.8.3, continue is supported inside finally 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /ExceptionalHandling/__pycache__/three.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/ExceptionalHandling/__pycache__/three.cpython-37.pyc -------------------------------------------------------------------------------- /ExceptionalHandling/__pycache__/two.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/ExceptionalHandling/__pycache__/two.cpython-37.pyc -------------------------------------------------------------------------------- /ExceptionalHandling/one.py: -------------------------------------------------------------------------------- 1 | 2 | import two 3 | 4 | 5 | def main(): 6 | try: 7 | # a = two.add(19, "a") 8 | # if (a): 9 | # print("success") 10 | # return a 11 | # else: 12 | # print(a) 13 | print("a"/22) 14 | 15 | except Exception as e: 16 | print(e) 17 | else: 18 | print("sinside main functio") 19 | finally: 20 | print("done") 21 | 22 | main() -------------------------------------------------------------------------------- /ExceptionalHandling/test.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | # list1 = [1,2,2,2,4,4,4,4,4,4,4,4,'xyz', ['list1', 'list2'], {1:3, 2:4}] 4 | 5 | def convertDict1(list1): #Method 1 6 | try: 7 | print("Hello") 8 | myDict = {i:list1.count(i) for i in list1} 9 | return myDict 10 | except TypeError: 11 | print("Something went wrong!") 12 | 13 | def convertDict2(list1): #Method 2 14 | myDict2 = dict(Counter(list1)) 15 | return myDict2 16 | 17 | def cleaningList1(list1): 18 | dummyList = [] 19 | for i in list1: 20 | if type(i) == str or type(i) == int or isinstance(i, list): 21 | dummyList.append(i) 22 | else: 23 | pass 24 | return dummyList 25 | 26 | if __name__ == "__main__": 27 | 28 | #list1 = list(input("Enter something here:")) 29 | list1 = [1,'xyz', ['list1', 'list2'], {1:3, 2:4}] 30 | 31 | firstLevel = cleaningList1(list1) 32 | print(convertDict1(firstLevel)) 33 | 34 | # print(convertDict2(list1)) 35 | # print(cleaningList1(list1)) -------------------------------------------------------------------------------- /ExceptionalHandling/three.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def realAddition(a,b,c): 4 | try: 5 | print("inside real Addition") 6 | return a+b+c 7 | except Exception as e: 8 | print(e) 9 | return False -------------------------------------------------------------------------------- /ExceptionalHandling/two.py: -------------------------------------------------------------------------------- 1 | 2 | import three 3 | 4 | def add(a,b): 5 | try: 6 | print("inside two") 7 | return three.realAddition(a,b, 100) 8 | except Exception as e: 9 | print(e) 10 | return False -------------------------------------------------------------------------------- /Excersise/24HourTimeFormat.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/time-conversion 2 | 3 | givenTime = input() 4 | timeListFormat = list(givenTime) 5 | hour = [] 6 | finalOutput = '' 7 | 8 | if "AM" in givenTime: 9 | # if list(timeListFormat[0:2]) == [1,2]: 10 | if int(timeListFormat[0]) == 1 and int(timeListFormat[1]) == 2: 11 | timeListFormat[0] = str(0) 12 | timeListFormat[1] = str(0) 13 | for i in timeListFormat[0:8]: 14 | finalOutput += i 15 | print(finalOutput) 16 | elif "PM" in givenTime: 17 | for i in timeListFormat[0:2]: 18 | hour.append(int(i)) 19 | 20 | if int(timeListFormat[0]) == 1 and int(timeListFormat[1]) == 2: 21 | for i in timeListFormat[0: len(timeListFormat) - 2]: 22 | finalOutput += i 23 | else: 24 | x = '' 25 | for i in hour: 26 | x += str(i) 27 | finalOutput += str(int(x) + 12) 28 | for i in timeListFormat[2: len(timeListFormat)-2]: 29 | finalOutput += i 30 | 31 | print (finalOutput) -------------------------------------------------------------------------------- /Excersise/CheckingInternetIsWorking.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | import urllib.request 3 | 4 | def testInternet(): 5 | try: 6 | urllib.request.urlopen("http://google.com", timeout=2) 7 | print ("Internet is Working!") 8 | except urllib.URLError: 9 | print ("No Internet Connection! Please contact your administrator!") 10 | 11 | if __name__ == '__main__': 12 | testInternet() -------------------------------------------------------------------------------- /Excersise/CheckingStringPalindromeOrNot.py: -------------------------------------------------------------------------------- 1 | 2 | # Not checking for Special characters. 3 | def checkPalindrome(): 4 | userInput = input("Enter a string or integer") 5 | try: 6 | if type(userInput) is str or type(userInput) is int: 7 | if userInput == userInput[::-1]: 8 | print ('its a palindrome') 9 | else: 10 | raise Exception("It's not a palindrom, better luck next time") 11 | else: 12 | print ("is it something else?Please check.") 13 | except Exception as e: 14 | print (e) 15 | 16 | 17 | if __name__ == '__main__': 18 | checkPalindrome() 19 | -------------------------------------------------------------------------------- /Excersise/CompareTriplets.py: -------------------------------------------------------------------------------- 1 | # Please check the question here - https://www.hackerrank.com/challenges/compare-the-triplets 2 | 3 | 4 | aliceTriplets = input().split() 5 | bobTriplets = input().split() 6 | alice, bob = 0,0 7 | 8 | for i in range(len(aliceTriplets)): 9 | if (int(aliceTriplets[int(i)]) > int(bobTriplets[int(i)])): 10 | print (aliceTriplets[i], bobTriplets[i]) 11 | alice = alice + 1 12 | elif (int(aliceTriplets[int(i)]) < int(bobTriplets[int(i)])): 13 | bob +=1 14 | else: 15 | print ("inside else") 16 | 17 | print (alice, bob) 18 | 19 | # 5 6 7 20 | # 3 6 10 -------------------------------------------------------------------------------- /Excersise/ConverFloatPointNumberToDecimal.py: -------------------------------------------------------------------------------- 1 | # Python program to convert float 2 | # decimal to binary number 3 | 4 | # Function returns octal representation 5 | def float_bin(number, places = 3): 6 | 7 | # split() seperates whole number and decimal 8 | # part and stores it in two seperate variables 9 | whole, dec = str(number).split(".") 10 | 11 | # Convert both whole number and decimal 12 | # part from string type to integer type 13 | whole = int(whole) 14 | dec = int (dec) 15 | 16 | # Convert the whole number part to it's 17 | # respective binary form and remove the 18 | # "0b" from it. 19 | res = bin(whole).lstrip("0b") + "." 20 | 21 | # Iterate the number of times, we want 22 | # the number of decimal places to be 23 | for x in range(places): 24 | 25 | # Multiply the decimal value by 2 26 | # and seperate the whole number part 27 | # and decimal part 28 | whole, dec = str((decimal_converter(dec)) * 2).split(".") 29 | 30 | # Convert the decimal part 31 | # to integer again 32 | dec = int(dec) 33 | 34 | # Keep adding the integer parts 35 | # receive to the result variable 36 | res += whole 37 | 38 | return res 39 | 40 | # Function converts the value passed as 41 | # parameter to it's decimal representation 42 | def decimal_converter(num): 43 | while num > 1: 44 | num /= 10 45 | return num 46 | 47 | # Driver Code 48 | 49 | # Take the user input for 50 | # the floating point number 51 | n = input("Enter your floating point value : \n") 52 | 53 | # Take user input for the number of 54 | # decimal places user want result as 55 | p = int(input("Enter the number of decimal places of the result : \n")) 56 | 57 | print(float_bin(n, places = p)) -------------------------------------------------------------------------------- /Excersise/ConverFloatToDecimal.py: -------------------------------------------------------------------------------- 1 | # Python program to convert float 2 | # decimal to binary number 3 | 4 | # Function returns octal representation 5 | def float_bin(number, places = 3): 6 | 7 | # split() seperates whole number and decimal 8 | # part and stores it in two seperate variables 9 | whole, dec = str(number).split(".") 10 | 11 | # Convert both whole number and decimal 12 | # part from string type to integer type 13 | whole = int(whole) 14 | dec = int (dec) 15 | 16 | # Convert the whole number part to it's 17 | # respective binary form and remove the 18 | # "0b" from it. 19 | res = bin(whole).lstrip("0b") + "." 20 | 21 | # Iterate the number of times, we want 22 | # the number of decimal places to be 23 | for x in range(places): 24 | 25 | # Multiply the decimal value by 2 26 | # and seperate the whole number part 27 | # and decimal part 28 | whole, dec = str((decimal_converter(dec)) * 2).split(".") 29 | 30 | # Convert the decimal part 31 | # to integer again 32 | dec = int(dec) 33 | 34 | # Keep adding the integer parts 35 | # receive to the result variable 36 | res += whole 37 | 38 | return res 39 | 40 | # Function converts the value passed as 41 | # parameter to it's decimal representation 42 | def decimal_converter(num): 43 | while num > 1: 44 | num /= 10 45 | return num 46 | 47 | # Driver Code 48 | 49 | # Take the user input for 50 | # the floating point number 51 | n = input("Enter your floating point value : \n") 52 | 53 | # Take user input for the number of 54 | # decimal places user want result as 55 | p = int(input("Enter the number of decimal places of the result : \n")) 56 | 57 | print(float_bin(n, places = p)) -------------------------------------------------------------------------------- /Excersise/ConvertDecimalToBinary.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | 4 | #Testing for 25 with octal (8) 5 | 6 | class Stack: 7 | def __init__(self): 8 | self.items = [] 9 | 10 | def push(self, newItem): 11 | self.items.append(newItem) 12 | 13 | def pop(self): 14 | self.items.pop() 15 | 16 | def isEmpty(self): 17 | return self.items == [] 18 | 19 | def size(self): 20 | return len(self.items) 21 | 22 | def show(self): 23 | print (self.items) 24 | return self.items 25 | 26 | def peek(self): 27 | return self.items[0] 28 | 29 | def size(self): 30 | return len(self.items) 31 | 32 | 33 | def baseConverter(decNumber,base): #(25,8) 34 | digits = "0123456789ABCDEF" 35 | 36 | remstack = Stack() 37 | 38 | while decNumber > 0: #True, 3 39 | rem = decNumber % base # 25%8 = 1, 3 %8 = 3 40 | remstack.push(rem) # pushing inside the empty stack, [1,3] 41 | decNumber = decNumber # 25//8 = 3 ,3//8 = 0 42 | 43 | newString = "" 44 | while not remstack.isEmpty(): 45 | newString = newString + digits[remstack.pop()] 46 | 47 | return newString 48 | 49 | print(baseConverter(25,2)) 50 | print(baseConverter(25,16)) -------------------------------------------------------------------------------- /Excersise/DiagonalSum.py: -------------------------------------------------------------------------------- 1 | # Given a square matrix of size , calculate the absolute difference between the sums of its diagonals. 2 | # 3 | # Input Format 4 | # 5 | # The first line contains a single integer, . The next lines denote the matrix's rows, with each line containing space-separated integers describing the columns. 6 | # 7 | # Output Format 8 | # 9 | # Print the absolute difference between the two sums of the matrix's diagonals as a single integer. 10 | # 11 | # Sample Input 12 | 13 | # 3 14 | # 11 2 4 15 | # 4 5 6 16 | # 10 8 -12 17 | # Sample Output 18 | 19 | # 15 20 | # Explanation 21 | 22 | # The primary diagonal is: 23 | # 11 24 | # 5 25 | # -12 26 | # 27 | # Sum across the primary diagonal: 11 + 5 - 12 = 4 28 | # 29 | # The secondary diagonal is: 30 | # 4 31 | # 5 32 | # 10 33 | # Sum across the secondary diagonal: 4 + 5 + 10 = 19 34 | # Difference: |4 - 19| = 15 35 | 36 | 37 | n = int(input().strip()) 38 | givenInputArray = [] 39 | for a_i in range(n): 40 | a_temp = map(int, input().strip().split(' ')) 41 | givenInputArray.append(a_temp) 42 | primaryDiagonal = [] 43 | 44 | for primaryDiagonalElements in range(len(givenInputArray)): 45 | primaryDiagonal.append(givenInputArray[primaryDiagonalElements][primaryDiagonalElements]) 46 | 47 | primaryDiagonal = sum(primaryDiagonal) 48 | 49 | secondaryDiagonal = sum(givenInputArray[i][n-i-1] for i in range(n)) 50 | 51 | print (abs(primaryDiagonal -secondaryDiagonal)) 52 | -------------------------------------------------------------------------------- /Excersise/DiscoverMonk.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | def monk(n, args = []): 4 | 5 | someArray = range(0,50,10) 6 | for i in args: 7 | if i in someArray: 8 | print ("YES") 9 | else: 10 | print ("NO") 11 | 12 | if __name__ == '__main__': 13 | someList = range(0,100,10) 14 | monk(len(someList), someList) 15 | 16 | -------------------------------------------------------------------------------- /Excersise/DynamicProgramming.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # Here is the real time scenario for Dynamic Programming. 4 | # A classic example of an optimization problem involves making change using the fewest coins. 5 | # Suppose you are a programmer for a vending machine manufacturer. Your company wants to streamline effort 6 | # by giving out the fewest possible coins in change for each transaction. Suppose a customer puts in a 7 | # dollar bill and purchases an item for 37 cents. What is the smallest number of coins you can use to 8 | # make change? The answer is six coins: two quarters, one dime, and three pennies. How did we arrive at 9 | # the answer of six coins? We start with the largest coin in our arsenal (a quarter) and use as many of 10 | # those as possible, then we go to the next lowest coin value and use as many of those as possible. 11 | 12 | def dpMakeChange(coinValueList,change,minCoins,coinsUsed): 13 | for cents in range(change+1): 14 | coinCount = cents 15 | newCoin = 1 16 | for j in [c for c in coinValueList if c <= cents]: 17 | if minCoins[cents-j] + 1 < coinCount: 18 | coinCount = minCoins[cents-j]+1 19 | newCoin = j 20 | minCoins[cents] = coinCount 21 | coinsUsed[cents] = newCoin 22 | return minCoins[change] 23 | 24 | def printCoins(coinsUsed,change): 25 | coin = change 26 | while coin > 0: 27 | thisCoin = coinsUsed[coin] 28 | print(thisCoin) 29 | coin = coin - thisCoin 30 | 31 | def main(): 32 | amnt = 63 33 | clist = [1,5,10,21,25] 34 | coinsUsed = [0]*(amnt+1) 35 | coinCount = [0]*(amnt+1) 36 | 37 | print("Making change for",amnt,"requires") 38 | print(dpMakeChange(clist,amnt,coinCount,coinsUsed),"coins") 39 | print("They are:") 40 | printCoins(coinsUsed,amnt) 41 | print("The used list is as follows:") 42 | print(coinsUsed) 43 | 44 | if __name__ == '__main__': 45 | main() 46 | 47 | -------------------------------------------------------------------------------- /Excersise/EvenNumEvenIndex_42.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a list of N numbers, use a single list comprehension to produce a new list that only contains those values that are: 3 | (a) even numbers, and 4 | (b) from elements in the original list that had even indices 5 | For example, if list[2] contains a value that is even, that value should be included in the new list, 6 | since it is also at an even index (i.e., 2) in the original list. 7 | However, if list[3] contains an even number, that number should not be included in the new list since 8 | it is at an odd index (i.e., 3) in the original list. 9 | ''' 10 | 11 | def EvenNumEvenIndex(someList): 12 | if type(someList) is not list: 13 | print("Invalid user input") 14 | if len(someList) == 0: 15 | print("No value in the list") 16 | 17 | dummyList = [] 18 | for num in someList: 19 | if someList.index(num) %2 == 0 and num %2 == 0: 20 | dummyList.append(int(num)) 21 | return dummyList 22 | 23 | 24 | def getUserInput(): 25 | listOfIntNum = [] 26 | listOfFloatNum = [] 27 | 28 | inputList = input("Enter list of nunmbers: ") 29 | inputList = inputList.split(" ") 30 | 31 | if inputList: 32 | for value in inputList: 33 | if '.' in value: 34 | # possible that, value can be a floating number or a sentence with full stop. 35 | try: 36 | if isinstance(float(value), float): 37 | listOfFloatNum.append(float(value)) 38 | continue 39 | except ValueError as e: 40 | pass 41 | try: 42 | if isinstance(int(value), int): 43 | listOfIntNum.append(int(value)) 44 | except ValueError as e: 45 | pass 46 | 47 | 48 | return listOfIntNum + listOfFloatNum 49 | 50 | if __name__ == "__main__": 51 | numList = getUserInput() 52 | print(numList) 53 | print(EvenNumEvenIndex(numList)) -------------------------------------------------------------------------------- /Excersise/EvenOrOddWithoutUsingModDiv.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # The below program is to check whether the given number is odd or even 4 | # The logic is acheived by Bit wise operator 5 | # normally people will use Modulo or division operator to find its even or odd. 6 | 7 | numList = range(0, 10, 2) # [0,2,4,6,8] 8 | 9 | def commonLogicPlusMyOwnImplementation(n): 10 | # used bit wise operator logic and also checking whether the last number of the digit 11 | # is there in numList, which is a common declared list at the top 12 | if ((n & 1 == 0) or (n in numList)): 13 | print("It's a Even Number") 14 | else: 15 | print("It's a Odd Number") 16 | if __name__ == '__main__': 17 | try: 18 | getIn = raw_input("Please give a input to check whether the number is even or odd") 19 | if getIn.isdigit(): # checks whether the user given input is valid or not. 20 | if getIn == 1 or getIn >1: 21 | commonLogicPlusMyOwnImplementation(int(getIn)) 22 | else: 23 | raise ArithmeticError("Something is wrong in the given input!Check it.") 24 | except ArithmeticError as e: 25 | print(e.message) 26 | else: 27 | print("Thanks for testing me!") -------------------------------------------------------------------------------- /Excersise/EvenTree.py: -------------------------------------------------------------------------------- 1 | # Ex - 3 2 | 3 | 4 | def find_edges(count): 5 | root = max(count) 6 | 7 | count_even = 0 8 | 9 | for cnt in count: 10 | if cnt % 2 == 0: 11 | count_even += 1 12 | 13 | if root % 2 == 0: 14 | count_even -= 1 15 | 16 | return count_even 17 | 18 | 19 | def count_nodes(edge_list, n, m): 20 | count = [1 for i in range(0, n)] 21 | 22 | for i in range(m - 1, -1, -1): 23 | count[edge_list[i][1] - 1] += count[edge_list[i][0] - 1] 24 | 25 | print (find_edges(count)) 26 | return find_edges(count) 27 | 28 | 29 | if __name__ == '__main__': 30 | # n,m= map(int, raw_input()) 31 | n, m = 10, 9 32 | edge_list = [(2,1),(3, 1),(4,3),(5,2),(6,1),(7,2),(8,6),(9, 8),(10, 8)] 33 | s = count_nodes(edge_list,n,m) 34 | find_edges(s) 35 | 36 | -------------------------------------------------------------------------------- /Excersise/Factorial.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | 4 | def fa(n): 5 | # if n==1: 6 | # return 1 7 | # else: 8 | # return fa(n) * fa(n-1) 9 | f = 1 10 | for i in range(n+1): 11 | if i is not 0: 12 | f = f*i 13 | print (f) 14 | 15 | 16 | def fac(n): 17 | resp = 1 18 | givenInput = list(range(1, n+1)) 19 | for i in givenInput: 20 | resp = resp * i 21 | 22 | return resp 23 | 24 | 25 | if __name__ == '__main__': 26 | print ("Enter a number to find the factorial!") 27 | getInput = int(input()) 28 | fa(getInput) 29 | fac(5) 30 | -------------------------------------------------------------------------------- /Excersise/FindDigits.py: -------------------------------------------------------------------------------- 1 | 2 | # Given an integer, , traverse its digits (1,2,...,n) and determine how many digits evenly divide (i.e.: count the number of times divided by each digit i has a remainder of ). Print the number of evenly divisible digits. 3 | 4 | # Note: Each digit is considered to be unique, so each occurrence of the same evenly divisible digit should be counted (i.e.: for , the answer is ). 5 | 6 | # Input Format 7 | 8 | # The first line is an integer, , indicating the number of test cases. 9 | # The subsequent lines each contain an integer, . 10 | 11 | # Output Format 12 | # For every test case, count and print (on a new line) the number of digits in that are able to evenly divide . 13 | 14 | # Sample Input # Sample Output 15 | 16 | # 2 17 | # 12 2 18 | # 1012 3 19 | 20 | #Explanation: 21 | 22 | # The number is broken into two digits, and . When is divided by either of those digits, the calculation's remainder is ; thus, the number of evenly-divisible digits in is . 23 | 24 | # The number is broken into four digits, , , , and . is evenly divisible by its digits , , and , but it is not divisible by as division by zero is undefined; thus, our count of evenly divisible digits is . 25 | 26 | if __name__ =='__main__': 27 | 28 | t = int(input().strip()) 29 | opToDisplay = [] 30 | for a0 in range(t): 31 | n = int(input().strip()) 32 | singleIterationResult = [] 33 | splitResult = [int(i) for i in str(n)] 34 | for i in splitResult: 35 | if i != 0: 36 | if n % i == 0: 37 | singleIterationResult.append(i) 38 | opToDisplay.append(len(singleIterationResult)) 39 | for i in opToDisplay: 40 | print (i) 41 | -------------------------------------------------------------------------------- /Excersise/FindNextGreaterElement.py: -------------------------------------------------------------------------------- 1 | # Function to print element and NGE pair for all elements of list 2 | def printNGE(arr): 3 | for i in range(0, len(arr), 1): 4 | next = -1 5 | for j in range(i + 1, len(arr), 1): 6 | if arr[i] < arr[j]: 7 | next = arr[j] 8 | break 9 | 10 | print(str(arr[i]) + " -- " + str(next)) 11 | 12 | 13 | # Driver program to test above function 14 | arr = [11, 13, 21, 3] 15 | printNGE(arr) -------------------------------------------------------------------------------- /Excersise/FindingNumbers.py: -------------------------------------------------------------------------------- 1 | # Alice has just learnt multiplying two integers. He wants to multiply two integers X and Y to form a number Z. To make the problem interesting he will choose X in the range [1,M] and Y in the range [1,N]. Help him to find the number of ways in which he can do this. 2 | # 3 | # Input 4 | # First line of the input is the number of test cases T. It is followed by T lines. Each line has three space separated integers, the numbers Z, M and N. 5 | # 6 | # Output 7 | # For each test case output a single integer, the number of ways. 8 | # 9 | # Constraints 10 | # 1 <= T <= 50 11 | # 1 <= Z <= 10^12 12 | # 1 <= M <= 10^12 13 | # 1 <= N <= 10^12 14 | 15 | # SAMPLE INPUT SAMPLE OUTPUT 16 | # 4 17 | # 4 7 9 3 18 | # 5 2 10 1 19 | # 5 5 6 2 20 | # 2 8 1 1 21 | 22 | 23 | def findNumbers(totalTest): 24 | for i in range(totalTestCases): 25 | del finalOp[:] 26 | count = 0 27 | resultSum, firstInput, secondInput = map(int,input().split()) 28 | firstList = range(1, firstInput+1) 29 | secondList = range(1, secondInput+1) 30 | if not firstList or not secondList: 31 | finalOp.append(1) 32 | else: 33 | for i in firstList: 34 | for j in secondList: 35 | if i*j == resultSum or j*i == resultSum: 36 | count = count + 1 37 | finalOp.append(1) 38 | else: 39 | pass 40 | # print len(finalOp) 41 | print (count) 42 | 43 | # def secondD+ayTry(totalTestC): 44 | # op = [] 45 | # res = 0 46 | # for i in range(totalTestC): 47 | # resultSum, firstInput, secondInput = map(int, raw_input().split()) 48 | # firstList = range(1, firstInput) 49 | # secondList = range(1, secondInput) 50 | # 51 | # if not firstList or not secondList: 52 | # op.append(1) 53 | # else: 54 | # for m in firstList: 55 | # op.append(res) 56 | # res = 0 57 | # for n in secondList: 58 | # if m*n == resultSum: 59 | # res = res +1 60 | # 61 | # print res 62 | # 63 | # for i in op: 64 | # print "result is",i 65 | 66 | 67 | 68 | if __name__ == '__main__': 69 | totalTestCases = int(input()) 70 | finalOp = [] 71 | findNumbers(totalTestCases) -------------------------------------------------------------------------------- /Excersise/FindingTraceInBreadthFirstSearch.py: -------------------------------------------------------------------------------- 1 | # http://stackoverflow.com/questions/8922060/how-to-trace-the-path-in-a-breadth-first-search 2 | 3 | # graph is in adjacent list representation 4 | graph = { 5 | '1': ['2', '3', '4'], 6 | '2': ['5', '6'], 7 | '5': ['9', '10'], 8 | '4': ['7', '8'], 9 | '7': ['11', '12'] 10 | } 11 | 12 | # below implemented method is independednt, which is not inside any class. 13 | def BreadthFirstSearch(graph, start, end): 14 | # maintain a queue of paths 15 | queue = [] 16 | # push the first path into the queue 17 | queue.append([start]) 18 | 19 | while queue: 20 | 21 | path = queue.pop(0) 22 | 23 | node = path[-1] 24 | # path found 25 | if node == end: 26 | return path 27 | # enumerate all adjacent nodes, construct a new path and push it into the queue 28 | for adjacent in graph.get(node, []): 29 | new_path = list(path) 30 | new_path.append(adjacent) 31 | queue.append(new_path) 32 | 33 | 34 | print BreadthFirstSearch(graph, '1', '19') 35 | -------------------------------------------------------------------------------- /Excersise/FolderSizeOfDirectory.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | import os # Load the library module 4 | directory = '.' # Set the variable directory to be the current directory 5 | dir_size = 0 # Set the size to 0 6 | 7 | fsizedicr = { 8 | 'Bytes': 1, 'Kilobytes': float(1)/1024, 9 | 'Megabytes': float(1)/(1024*1024), 10 | 'Gigabytes': float(1)/(1024*1024*1024) 11 | } 12 | print (os) 13 | print (os.walk(directory)) 14 | 15 | for (path, dirs, files) in os.walk(directory): # Walk through all the directories. For each iteration, os.walk returns the folders, subfolders and files in the dir. 16 | for file in files: # Get all the files 17 | filename = os.path.join(path, file) 18 | dir_size += os.path.getsize(filename) # Add the size of each file in the root dir to get the total size. 19 | 20 | for key in fsizedicr: #iterating through the dictionary 21 | print ("Folder Size: " + str(round(fsizedicr[key]*dir_size, 2)) + " " + key) # round function example: round(4.2384, 2) ==> 4.23 22 | -------------------------------------------------------------------------------- /Excersise/Fraction.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | class Fraction: 4 | 5 | def __init__(self,top,bottom): 6 | 7 | self.num = top 8 | self.den = bottom 9 | 10 | def display(self): 11 | print("here are the input numbers") 12 | print (self.num, "/", self.den) 13 | 14 | def division(self): 15 | c = self.num / self.den 16 | if c is not 0: 17 | print ("the value of c is ",c) 18 | else: 19 | print ("it seems it's zero") 20 | 21 | def __add__(self, other): 22 | newnum = self.num * other.den + self.den * other.num 23 | newden = self.den * other.den 24 | 25 | return Fraction(newnum, newden) 26 | # 27 | # object.__add__(self, other) 28 | # object.__sub__(self, other) 29 | # object.__mul__(self, other) 30 | # object.__floordiv__(self, other) 31 | # object.__mod__(self, other) 32 | # object.__divmod__(self, other) 33 | # object.__pow__(self, other[, modulo]) 34 | # object.__lshift__(self, other) 35 | # object.__rshift__(self, other) 36 | # object.__and__(self, other) 37 | # object.__xor__(self, other) 38 | # object.__or__(self, other) 39 | 40 | 41 | if __name__ == '__main__': 42 | myFrac = Fraction(3,5) 43 | print (myFrac) 44 | myFrac.display() 45 | myFrac.division() 46 | f1 = Fraction(1,4) 47 | f2 = Fraction(1,2) 48 | f3 = f1+f2 49 | print (f3) 50 | 51 | -------------------------------------------------------------------------------- /Excersise/GoldRate/Todo.txt: -------------------------------------------------------------------------------- 1 | 1. Store not only date, but also time needs to be stored - Done 2 | 2. Implementation of graph. 3 | 3. ask user for date, wait for 10 seconds, within 10 seconds if user gives input as dd/mm/yyy then find the gold rate for that date and store that in DB 4 | 4. if user didn't give any input within 10 seconds, proceed finding gold rate for today's date, display it and store in DB 5 | 5. all hard coded values inside .py file should be in a separate config or constant file. 6 | 6. rename the file 7 | 7. during schedule task - always check wether existing date data is available in DB, if available, find it's source info, inform the user saying "record already exist in DB, user can check there if needed" //if record says manually triggered, then proceed finding gold rate and store in DB 8 | 8. if existing date data shows source info as "shceduled", then inform user data is already present in DB, ask yes or no, whether to store one more record in DB 9 | 9. Get Silver Rate as well 10 | 10. Get gold rates for gulf countries as well. 11 | 11. Get gold rates for US as well. 12 | 12. Refactor the Dubai/USA and India Data in a single function, passing URL as parameter. 13 | -------------------------------------------------------------------------------- /Excersise/Hashing.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | class HashTable: 4 | def __init__(self): 5 | self.size = 11 6 | self.slots = [None] * self.size 7 | self.data = [None] * self.size 8 | 9 | def put(self,key,data): 10 | hashvalue = self.hashfunction(key,len(self.slots)) 11 | 12 | if self.slots[hashvalue] == None: 13 | self.slots[hashvalue] = key 14 | self.data[hashvalue] = data 15 | else: 16 | if self.slots[hashvalue] == key: 17 | self.data[hashvalue] = data #replace 18 | else: 19 | nextslot = self.rehash(hashvalue,len(self.slots)) 20 | while self.slots[nextslot] != None and \ 21 | self.slots[nextslot] != key: 22 | nextslot = self.rehash(nextslot,len(self.slots)) 23 | 24 | if self.slots[nextslot] == None: 25 | self.slots[nextslot]=key 26 | self.data[nextslot]=data 27 | else: 28 | self.data[nextslot] = data #replace 29 | 30 | def hashfunction(self,key,size): 31 | return key%size 32 | 33 | def rehash(self,oldhash,size): 34 | return (oldhash+1)%size 35 | 36 | def get(self,key): 37 | startslot = self.hashfunction(key,len(self.slots)) 38 | 39 | data = None 40 | stop = False 41 | found = False 42 | position = startslot 43 | while self.slots[position] != None and \ 44 | not found and not stop: 45 | if self.slots[position] == key: 46 | found = True 47 | data = self.data[position] 48 | else: 49 | position=self.rehash(position,len(self.slots)) 50 | if position == startslot: 51 | stop = True 52 | return data 53 | 54 | def __getitem__(self,key): 55 | return self.get(key) 56 | 57 | def __setitem__(self,key,data): 58 | self.put(key,data) 59 | 60 | if __name__ == '__main__': 61 | H=HashTable() 62 | H[54]="cat" 63 | H[26]="dog" 64 | H[93]="lion" 65 | H[17]="tiger" 66 | H[77]="bird" 67 | H[31]="cow" 68 | H[44]="goat" 69 | H[55]="pig" 70 | H[20]="chicken" 71 | print(H.slots) 72 | -------------------------------------------------------------------------------- /Excersise/HelloWorld.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | 4 | print ('Hello world') 5 | 6 | # for Python Version 3.X and PEP8 suggests to use double quotes 7 | 8 | print ("Hello World") 9 | 10 | -------------------------------------------------------------------------------- /Excersise/LargestPrimeNumber.py: -------------------------------------------------------------------------------- 1 | def is_prime(m): 2 | """Checks if the argument is a prime number.""" 3 | 4 | if m < 2: return False 5 | 6 | for i in range(2, m): 7 | if m % i == 0: 8 | return False 9 | 10 | return True 11 | 12 | def get_largest_prime_factor(k): 13 | """Gets the largest prime factor for the argument.""" 14 | 15 | prime_divide = (p for p in range(1, k)) 16 | for d in prime_divide: 17 | 18 | if k % d == 0 and is_prime(k / d): 19 | return k / d 20 | 21 | print (get_largest_prime_factor(234)) -------------------------------------------------------------------------------- /Excersise/LibraryFineCollections.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # Your local library needs your help! Given the expected and actual return dates for a library book, create a program that calculates the fine (if any). The fee structure is as follows: 3 | # 4 | # If the book is returned on or before the expected return date, no fine will be charged (i.e.: . 5 | # If the book is returned after the expected return day but still within the same calendar month and year as the expected return date, . 6 | # If the book is returned after the expected return month but still within the same calendar year as the expected return date, the . 7 | # If the book is returned after the calendar year in which it was expected, there is a fixed fine of . 8 | # Input Format 9 | # 10 | # The first line contains space-separated integers denoting the respective , , and on which the book was actually returned. 11 | # The second line contains space-separated integers denoting the respective , , and on which the book was expected to be returned (due date). 12 | # 13 | # Constraints 14 | # 15 | # Output Format 16 | # 17 | # Print a single integer denoting the library fine for the book received as input. 18 | # 19 | # Sample Input 20 | # 21 | # 9 6 2015 22 | # 6 6 2015 23 | # Sample Output 24 | # 25 | # 45 26 | # Explanation 27 | # 28 | # Given the following return dates: 29 | # Actual: 30 | # Expected: 31 | # 32 | # Because , we know it is less than a year late. 33 | # Because , we know it's less than a month late. 34 | # Because , we know that it was returned late (but still within the same month and year). 35 | # 36 | # Per the library's fee structure, we know that our fine will be . We then print the result of as our output. 37 | 38 | 39 | 40 | deliveryInfo = map(int, raw_input().split()) 41 | estimatedDeliveryInfo = map(int, raw_input().split()) 42 | 43 | 44 | deliveredDate = deliveryInfo[0] 45 | deliveredMonth = deliveryInfo[1] 46 | deliveredYear = deliveryInfo[2] 47 | 48 | estimatedDeliveryDate = estimatedDeliveryInfo[0] 49 | estimatedDeliveryMonth = estimatedDeliveryInfo[1] 50 | estimatedDeliveryYear = estimatedDeliveryInfo[2] 51 | 52 | if (estimatedDeliveryDate == deliveredDate and estimatedDeliveryMonth != deliveredMonth): 53 | print(500 * abs(deliveredMonth - estimatedDeliveryMonth)) 54 | elif (estimatedDeliveryDate != deliveredDate and estimatedDeliveryMonth == deliveredMonth ): 55 | print(15 * abs(deliveredDate - estimatedDeliveryDate)) 56 | elif (estimatedDeliveryYear != deliveredYear ): 57 | print(10000) 58 | 59 | # 9 6 2015 60 | # 6 6 2015 -------------------------------------------------------------------------------- /Excersise/ListAddition.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # Question 4 | # There are 2 arrays of integers.You have to add the those integers and keep it in 3rd array.there is one condition, if the sum is a 2 digit number, split that number into single digiit and other condition is if any of the array integer is left then print that number 5 | # I/P: 6 | # int[] a = {1,2,3,4,5,6} 7 | # int[] b = {2,3,4,5,6,7,8} 8 | # o/p: 9 | # {3,5,7,9,1,1,1,3,8} 10 | 11 | def ListAdditionOutputWithCommaSeparated(a,b): 12 | try: 13 | s= "" 14 | for i in range(len(a)): 15 | c = a[i] + b[i] 16 | s = s + str(c) 17 | print ([int(i) for i in s]) 18 | except (IndexError, ValueError): 19 | print (ValueError) 20 | 21 | 22 | def genericCheck(a,b): 23 | diff = len(a) - len(b) 24 | for i in range(diff): 25 | b.append(0) 26 | ListAdditionOutputWithCommaSeparated(a,b) 27 | 28 | if __name__ == '__main__': 29 | a = range(10) 30 | b = range(11,21) 31 | if len(a) > len(b): 32 | genericCheck(a,b) 33 | elif(len(b) > len(a)): 34 | genericCheck(a,b) 35 | else: 36 | ListAdditionOutputWithCommaSeparated(a,b) -------------------------------------------------------------------------------- /Excersise/Min-MaxSum.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # https://www.hackerrank.com/challenges/mini-max-sum 4 | 5 | 6 | 7 | 8 | a,b,c,d,e = list(map(int, input().split())) 9 | a,b,c,d,e = [int(a),int(b),int(c),int(d),int(e)] 10 | 11 | lst = sorted([a, b, c, d, e]) 12 | print (lst) 13 | 14 | print(sum(lst[:-1]), sum(lst[1:])) -------------------------------------------------------------------------------- /Excersise/MostCommon.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # Input Format 4 | # 5 | # 6 | # A single line of input containing the string S 7 | # S 8 | # . 9 | # 10 | # Constraints 11 | # 12 | # 3 19 | using namespace std; 20 | 21 | int main() 22 | { 23 | //taking input for number of test cases, T. 24 | cin>>T; 25 | 26 | //For every test case, taking input for N , K and M. 27 | cin>>N>>K>>M; 28 | 29 | //let the answer be in variable **Ans** 30 | cout << Ans << endl; //print your answer for every test case. 31 | return 0; 32 | } 33 | 34 | Sample Input 35 | (Plaintext Link) 36 | 1 37 | 2 2 10 38 | Sample Output 39 | (Plaintext Link) 40 | 8 41 | Explanation 42 | Total Money required is : 2 * 13 + 2 * 23 = 18 but he already has 10 so ans is 8. 43 | 44 | Time Limit: 1 sec(s) for each input file. 45 | Memory Limit: 256 MB 46 | Source Limit: 1024 KB 47 | Marking Scheme: Marks are awarded if any testcase passes. 48 | Allowed languages: C, CPP, CLOJURE, CSHARP, GO, HASKELL, JAVA, JAVASCRIPT, JAVASCRIPT_NODE, LISP, OBJECTIVEC, PASCAL, PERL, PHP, PYTHON, RUBY, R, RUST, SCALA 49 | """ 50 | 51 | def remaingAmount(numberOfBeers,eachBeerCost,rupeesInPurse): 52 | totalCost1 = 0 53 | totalCost2 = 0 54 | for i in range(eachBeerCost): 55 | if i == 0: 56 | i = 1 57 | totalCost1 = numberOfBeers * i**3 58 | else: 59 | i = i+1 60 | totalCost2 = numberOfBeers * i**3 61 | 62 | finalCost = totalCost1 + totalCost2 63 | remaingBalance = finalCost - rupeesInPurse 64 | print (abs(remaingBalance)) 65 | 66 | 67 | if __name__ == '__main__': 68 | remaingAmount(2,2,10) 69 | 70 | # 71 | # class A(): 72 | # print ("sanjay") 73 | # def __init__(self): 74 | # print ("s") 75 | # 76 | # x = A() 77 | # print (x) 78 | # 79 | # print ([i for i in range(5) if i%3 ==0 ]) -------------------------------------------------------------------------------- /Excersise/OrderedDictionary.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # 3 | # Task 4 | # 5 | # You are the manager of a supermarket. 6 | # You have a list of N 7 | # N 8 | # items together with their prices that consumers bought on a particular day. 9 | # Your task is to print each item_name and net_price in order of its first occurrence. 10 | # 11 | # item_name = Name of the item. 12 | # net_price = Quantity of the item sold multiplied by the price of each item. 13 | # 14 | # 15 | # Input Format 16 | # 17 | # 18 | # The first line contains the number of items, N 19 | # N 20 | # . 21 | # The next N 22 | # N 23 | # lines contains the item's name and price, separated by a space. 24 | # 25 | # Constraints 26 | # 27 | # 0 1 and stillEqual: 32 | # first = chardeque.removeFront() 33 | # last = chardeque.removeRear() 34 | # if first != last: 35 | # stillEqual = False 36 | 37 | return stillEqual 38 | 39 | -------------------------------------------------------------------------------- /Excersise/PlusMinus.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/plus-minus 2 | 3 | 4 | totalElements = int(input()) 5 | giveInputList = list(map(int, input().split())) 6 | 7 | print(totalElements, len(giveInputList)) 8 | if totalElements == len(giveInputList): 9 | positiveElements = [i for i in giveInputList if i>0] 10 | negativeElements = [i for i in giveInputList if i<0] 11 | neutralElements = [i for i in giveInputList if i ==0] 12 | 13 | print (round(len(positiveElements)/totalElements , 6)) 14 | print (round(len(negativeElements)/ totalElements, 6)) 15 | print (round(len(neutralElements)/ totalElements, 6)) 16 | 17 | 18 | -------------------------------------------------------------------------------- /Excersise/PrimNumFromList.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay Pradeep' 2 | 3 | 4 | def findPrime(): 5 | 6 | # num = int(input("Enter a number: ")) 7 | # 8 | # # prime numbers are greater than 1 9 | # if num > 1: 10 | # # check for factors 11 | # for i in range(2,num): 12 | # if (num % i) == 0: 13 | # print(num,"is not a prime number") 14 | # print(i,"times",num//i,"is",num) 15 | # break 16 | # else: 17 | # print(num,"is a prime number") 18 | # 19 | # # if input number is less than 20 | # # or equal to 1, it is not prime 21 | # else: 22 | # print(num,"is not a prime number") 23 | # s= [] 24 | # for i in args: 25 | # print i 26 | # if i >1: 27 | # for j in range(2,i): 28 | # if (i%j) == 0: 29 | # break 30 | # else: 31 | # s.append(i) 32 | # else: 33 | # break 34 | l = [5,3,11,16,17] 35 | s= [] 36 | for i in l: 37 | if i > 1: 38 | for j in range(2,i): 39 | if (i % j) == 0: 40 | break 41 | else: 42 | s.append(i) 43 | else: 44 | break 45 | print (s) 46 | 47 | 48 | if __name__ == '__main__': 49 | # l = [5,3,11,16,17] 50 | # findPrime(l) 51 | findPrime() 52 | -------------------------------------------------------------------------------- /Excersise/RemoveDuplicateStrings.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | # Function to remove all duplicates from string 4 | # and order does not matter 5 | def removeDupWithoutOrder(str): 6 | 7 | # set() --> A Set is an unordered collection 8 | # data type that is iterable, mutable, 9 | # and has no duplicate elements. 10 | # "".join() --> It joins two adjacent elements in 11 | # iterable with any symbol defined in 12 | # "" ( double quotes ) and returns a 13 | # single string 14 | return "".join(set(str)) 15 | 16 | # Function to remove all duplicates from string 17 | # and keep the order of characters same 18 | def removeDupWithOrder(str): 19 | return "".join(OrderedDict.fromkeys(str)) 20 | 21 | # Driver program 22 | if __name__ == "__main__": 23 | str = "geeksforgeeks" 24 | print("Without Order = ",removeDupWithoutOrder(str)) 25 | print("With Order = ",removeDupWithOrder(str)) -------------------------------------------------------------------------------- /Excersise/SecondHighestNumber.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # Let's delve into one of the most basic data types in Python, the list. You are given NN numbers. Store them in a list and find the second largest number. 4 | # 5 | # Input Format 6 | # 7 | # The first line contains NN. The second line contains an array AA[] of NN integers each separated by a space. 8 | # 9 | # Output Format 10 | # 11 | # Output the value of the second largest number. 12 | # 13 | # Sample Input 14 | # 15 | # 5 16 | # 2 3 6 6 5 17 | # Sample Output 18 | # 19 | # 5 20 | # Constraints 21 | # 2?N?102?N?10 22 | # ?100?A[i]?100?100?A[i]?100 23 | # Concept 24 | # 25 | # A list in Python is similar to an array. A list can contain any data type as well as mixed data types. A list can contain a number, a string and even another list. 26 | # Lists are mutable. They can be changed by adding or removing values from the list. 27 | 28 | input() 29 | a=list(map(int,input().split(" "))) 30 | b=max(a) 31 | while max(a)==b : 32 | a.remove(b) 33 | print (max(a)) -------------------------------------------------------------------------------- /Excersise/SherlockSquares.py: -------------------------------------------------------------------------------- 1 | # Fromm HackerEarth 2 | # Watson gives two integers ( and ) to Sherlock and asks if he can count the number of square integers between and (both inclusive). 3 | # 4 | # Note: A square integer is an integer which is the square of any integer. For example, 1, 4, 9, and 16 are some of the square integers as they are squares of 1, 2, 3, and 4, respectively. 5 | # 6 | # Input Format 7 | # The first line contains , the number of test cases. test cases follow, each in a new line. 8 | # Each test case contains two space-separated integers denoting and . 9 | # 10 | # Output Format 11 | # For each test case, print the required answer in a new line. 12 | # 13 | # Constraints 14 | # 1<=T<=100 15 | # 1<=A<=B<=10^9 16 | # 17 | # Sample Input Sample output 18 | # 2 19 | # 3 9 2 20 | # 17 24 0 21 | 22 | if __name__ == '__main__': 23 | squares = [i*i for i in range(1, 1000000001)] 24 | print (squares) 25 | print (len(squares)) 26 | iterationResult = [] 27 | # listOfPossibleSquares = [] 28 | testCases = int(input().strip()) 29 | for i in range(testCases): 30 | listOfPossibleSquares = [] 31 | fromValue, toValue = map(int, input().split()) 32 | for k in range(fromValue,(toValue+1)): 33 | if k in squares: 34 | listOfPossibleSquares.append(k) 35 | iterationResult.append(len(listOfPossibleSquares)) 36 | for i in iterationResult: 37 | print (i) -------------------------------------------------------------------------------- /Excersise/StairCase.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/staircase?h_r=next-challenge&h_v=zen 2 | 3 | 4 | totalNumberSteps = int(input()) 5 | space = " " 6 | 7 | # totalSpaceNeeded = space * totalNumberSteps 8 | # print (totalSpaceNeeded) 9 | for i in range(1, totalNumberSteps+1): 10 | print(space*(totalNumberSteps-i)+ '#'*i ) -------------------------------------------------------------------------------- /Excersise/TrailingZero.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | 4 | def trails(n): 5 | listOfMultiples = [5,25,125,625,3125,15625] 6 | 7 | ans = 0 8 | if n > 1: 9 | for i in listOfMultiples: 10 | cal = n/i 11 | if cal < 1: 12 | break 13 | else: 14 | ans = ans + cal 15 | print (ans) 16 | 17 | 18 | if __name__ == '__main__': 19 | trails(999) 20 | -------------------------------------------------------------------------------- /Excersise/TrendingLaptopBrands.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # Bob and Khatki recently started a business. They sell computers at moderate rates. To grow their business they need to know which company�s laptops are in demand. You are given description of N laptops which are sold out. Each laptop is described by their company name. Can you help them figure out which company�s laptops are in demand. The company in demand is the one whose laptops are being sold more. If there are multiple such companies print the one which is lexicographically smallest. 4 | # 5 | # Input: 6 | # 7 | # First line of input contains N, number of responses of people. Next N lines contains company name of laptop. 8 | # 9 | # Output: 10 | # 11 | # Print the company name people preferred most. In case of tie print the lexographically smallest answer. 12 | # 13 | # Constraints: 14 | # 15 | # 1 &le N ? 105 16 | 17 | # SAMPLE INPUT 18 | 19 | #9 20 | # dell 21 | # lenovo 22 | # hp 23 | # lenovo 24 | # dell 25 | # dell 26 | # apple 27 | # compaq 28 | # sony 29 | # 30 | 31 | # SAMPLE OUTPUT 32 | # dell 33 | 34 | 35 | from collections import Counter 36 | import operator 37 | 38 | def mostTrendingBrand(numOfResponse,listOfBrands): 39 | if numOfResponse>1: 40 | brandCount = Counter(listOfBrands) 41 | onlyCount = [] 42 | for ke,va in brandCount.iteritems(): 43 | onlyCount.append(va) 44 | trendingCount = max(onlyCount) 45 | trendingBrandOutput = [] 46 | for ke,va in brandCount.iteritems(): 47 | if trendingCount == va: 48 | trendingBrandOutput.append(ke) 49 | for i in trendingBrandOutput: 50 | print (i) 51 | 52 | 53 | 54 | if __name__ == "__main__": 55 | userResponseCount = input() 56 | userInputList = [] 57 | for i in range(0,userResponseCount): 58 | temp = input() 59 | userInputList.append(temp) 60 | mostTrendingBrand(userResponseCount,userInputList) 61 | -------------------------------------------------------------------------------- /Excersise/UniqueMaximumNumber.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | def testing(args): 4 | uniq = [] 5 | for i in args: 6 | if args.count(i) == 1: 7 | uniq.append(i) 8 | if len(uniq) != 0: 9 | print(max(uniq)) 10 | else: 11 | print("It seems, all the numbers are repeated!") 12 | 13 | 14 | if __name__ == '__main__': 15 | a=int(input()) 16 | b = list(input()) 17 | while True: 18 | try: 19 | b.remove(" ") 20 | except ValueError: 21 | break 22 | orgInput = [] 23 | for i in b: 24 | if i != '': 25 | orgInput.append(int(i)) 26 | else: 27 | pass 28 | print(orgInput) 29 | testing(orgInput) -------------------------------------------------------------------------------- /Excersise/WordOrder.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # 4 | # Input Format 5 | # 6 | # 7 | # The first line contains the integer, n 8 | # n 9 | # . 10 | # The next n 11 | # n 12 | # lines each contain a word. 13 | # 14 | # 15 | # Output Format 16 | # 17 | # 18 | # Output 2 19 | # 2 20 | # lines. 21 | # On the first line, output the number of distinct words from the input. 22 | # On the second line, output the number of occurrences for each distinct word according to their appearance in the input. 23 | # 24 | # 25 | # Sample Input 26 | # 27 | # 4 28 | # bcdef 29 | # abcdefg 30 | # bcde 31 | # bcdef 32 | # 33 | # 34 | # 35 | # Sample Output 36 | # 37 | # 3 38 | # 2 1 1 39 | # 40 | # 41 | # 42 | # Explanation 43 | # 44 | # 45 | # There are 3 46 | # 3 47 | # distinct words. Here, "bcdef" appears twice in the input at the first and last positions. The other words appear \ 48 | # once each. The order of the first appearances are "bcdef", "abcdefg" and "bcde" which corresponds to the output. 49 | 50 | 51 | from collections import Counter 52 | 53 | 54 | def methodToExecute(): 55 | n = int(input()) 56 | words = [input().strip() for _ in range(n)] 57 | counts = Counter(words) 58 | 59 | print(len(counts)) 60 | 61 | for word in words: 62 | derp = counts.pop(word, None) 63 | if derp == None: 64 | continue 65 | else: 66 | print(derp,end=' ') # comma stops print from ending with newline 67 | 68 | 69 | if __name__=='__main__': 70 | methodToExecute() 71 | -------------------------------------------------------------------------------- /Excersise/checkPalindrome.py: -------------------------------------------------------------------------------- 1 | def checkPalindrome(): 2 | userInput = input("Enger a string or integer") 3 | try: 4 | if type(userInput) is str: 5 | if userInput == userInput[::-1]: 6 | print ('its a palindrome') 7 | else: 8 | raise Exception 9 | else: 10 | print ("is it something else?") 11 | except Exception as e: 12 | print (e) 13 | 14 | 15 | if __name__ == '__main__': 16 | checkPalindrome() 17 | -------------------------------------------------------------------------------- /Excersise/fibonacci.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | 3 | # what is fibonacci series? 4 | 5 | # a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. 6 | # The simplest is the series 1, 1, 2, 3, 5, 8, etc. 7 | 8 | 9 | # here's the first solution, 10 | def fibonacci_first(nTimes): 11 | if nTimes == 1: return 1 12 | elif nTimes == 2: return 2 13 | else: return fibonacci_first(nTimes-1) + fibonacci_first(nTimes-2) 14 | 15 | # def p_test(): 16 | # fibonacci_first(10) 17 | # I hope if you read the above code, it's understable. 18 | # But the problem comes when nTimes value is more than 30, it's taking more time to complete if nTimes is 50 19 | 20 | # myCode = ''' 21 | # def fibonacci_first(nTimes): 22 | # if nTimes == 1: return 1 23 | # elif nTimes == 2: return 2 24 | # else: return fibonacci_first(nTimes-1) + fibonacci_first(nTimes-2) 25 | # ''' 26 | # 27 | # import timeit 28 | # # print(timeit.timeit(setup='', stmt=myCode, number=1000)) 29 | # t = timeit.timeit("p_test()") 30 | # # t.timeit(1) 31 | 32 | 33 | # here's the second solution 34 | 35 | fib_cache = {} 36 | 37 | 38 | def fibonacci_second(numberOfTimes): 39 | if numberOfTimes in fib_cache: 40 | return fib_cache[numberOfTimes] 41 | 42 | if numberOfTimes == 1: 43 | value = 1 44 | elif numberOfTimes == 2: 45 | value = 2 46 | else: 47 | value = fibonacci_second(numberOfTimes - 1) + fibonacci_second(numberOfTimes - 2) 48 | fib_cache[numberOfTimes] = value 49 | return value 50 | 51 | # myCode = ''' 52 | # fib_cache = {} 53 | # def fibonacci_second(numberOfTimes): 54 | # if numberOfTimes in fib_cache: 55 | # return fib_cache[numberOfTimes] 56 | # 57 | # if numberOfTimes == 1: 58 | # value = 1 59 | # elif numberOfTimes == 2: 60 | # value = 2 61 | # else: 62 | # value = fibonacci_second(numberOfTimes - 1) + fibonacci_second(numberOfTimes - 2) 63 | # fib_cache[numberOfTimes] = value 64 | # return value''' 65 | 66 | # print("So total execution time is, ", timeit.timeit(setup='', stmt=myCode, number=1000)) 67 | 68 | 69 | # Here's the third solution.. 70 | 71 | @lru_cache(maxsize=1000) 72 | def fibbonacci_third(nTimes): 73 | if nTimes == 1: return 1 74 | elif nTimes == 2: return 2 75 | else : return fibbonacci_third(nTimes - 1) + fibbonacci_third(nTimes - 2) 76 | 77 | 78 | for i in range(1, 30): 79 | print(i , ":", fibonacci_first(i)) 80 | 81 | for i in range(1, 151): 82 | print(i, ":", fibonacci_second(i)) 83 | 84 | for i in range(1, 151): 85 | print(i, ":" ,fibbonacci_third(i)) -------------------------------------------------------------------------------- /Excersise/first-M-MultiplesOfN: -------------------------------------------------------------------------------- 1 | # Print first m multiples of n without using any loop in Python 2 | # Given n and m, print first m multiples of a m number without using any loops in Python. 3 | # 4 | # Examples: 5 | # 6 | # Input : n = 2, m = 3 7 | # Output : 2 4 6 8 | # 9 | # Input : n = 3, m = 4 10 | # Output : 3 6 9 12 11 | 12 | 13 | # function to print the first m multiple 14 | # of a number n without using loop. 15 | def multiple(m, n): 16 | # inserts all elements from n to 17 | # (m * n)+1 incremented by n. 18 | a = range(n, (m * n) + 1, n) 19 | 20 | print(*a) 21 | 22 | 23 | if __name__ == '__main__': 24 | firstInput = int(input("Enter first number ")) 25 | secInput = int(input("Enter second number ")) 26 | 27 | multiple(firstInput, secInput) -------------------------------------------------------------------------------- /Excersise/namedtuple.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # 3 | # Task 4 | # 5 | # Dr. John Wesley has a spreadsheet containing a list of student's IDs 6 | # IDs 7 | # , marks 8 | # marks 9 | # , class 10 | # class 11 | # and name 12 | # name 13 | # . 14 | # 15 | # Your task is to help Dr. Wesley calculate the average marks of the students. 16 | # 17 | # 18 | # Average=Sum of all marksTotal Students 19 | # Average=Sum of all marksTotal Students 20 | # 21 | # Note: 22 | # 1. Columns can be in any order. IDs, marks, class and name can be written in any order in the spreadsheet. 23 | # 2. Column names are ID, MARKS, CLASS and NAME. (The spelling and case type of these names won't change.) 24 | # 25 | # 26 | # Input Format 27 | # 28 | # 29 | # The first line contains an integer N 30 | # N 31 | # , the total number of students. 32 | # The second line contains the names of the columns in any order. 33 | # The next N 34 | # N 35 | # lines contains the marks 36 | # marks 37 | # , IDs 38 | # IDs 39 | # , name 40 | # name 41 | # and class 42 | # class 43 | # , under their respective column names. 44 | # 45 | # Constraints 46 | # 47 | # 0 35 | 36 | # if you want to print the yeild values, lets again iterate. 37 | 38 | for i in justCheckingValues: 39 | print (i) -------------------------------------------------------------------------------- /HashTable/1. Implementation_Tutorial.py: -------------------------------------------------------------------------------- 1 | 2 | # CONSTRUCT A HASH TABLE 3 | # ------------------------ 4 | 5 | single_hash_table = [None] * 10 6 | print(single_hash_table) 7 | 8 | # Output: 9 | # [None, None, None, None, None, None, None, None, None, None] 10 | 11 | # Below is a simple hash function that returns the modulus of the length of the hash table. 12 | # In our case, the length of the hash table is 10. 13 | 14 | # (Modulo operator (%) is used in the hashing function. The % (modulo) operator yields the remainder from the division 15 | # of the first argument by the second.) 16 | 17 | 18 | def hashing_func(key): 19 | return key % len(hash_table) 20 | 21 | 22 | def insert(hash_table, key, value): 23 | hash_key = hashing_func(key) 24 | hash_table[hash_key] = value 25 | 26 | 27 | insert(single_hash_table, 10, 'Nepal') 28 | print(single_hash_table) 29 | # Output: 30 | # ['Nepal', None, None, None, None, None, None, None, None, None] 31 | 32 | insert(single_hash_table, 25, 'USA') 33 | print(single_hash_table) 34 | # Output: 35 | # ['Nepal', None, None, None, None, 'USA', None, None, None, None] 36 | 37 | 38 | # WE HAVE A PROBLEM, "Collision" 39 | # A collision occurs when two items/values get the same slot/index, i.e. 40 | # the hashing function generates same slot number for multiple items. 41 | # If proper collision resolution steps are not taken then the previous item in the slot will be replaced by the 42 | # new item whenever the collision occurs. 43 | 44 | # TO RESOLVE ABOVE COLLISION PROBLEM, WE HAVE TWO TYPES 45 | 46 | # 1. LINEAR PROBING 47 | # 2. CHAINING 48 | 49 | 50 | # ####### NEEDS UPDATE ##### 51 | -------------------------------------------------------------------------------- /HashTable/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/HashTable/__init__.py -------------------------------------------------------------------------------- /Lambda/WhatIsLambda.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def squareNumber(n): 4 | if type(n) == int: 5 | return n*n 6 | else: 7 | return 0 8 | 9 | def checkForEven(n): 10 | if type(n) is not int: 11 | return 12 | return n%2 ==0 13 | 14 | def add(x, y): 15 | return x+y 16 | print(squareNumber(10)) 17 | 18 | # if you want to pass a list as a parameter, then will the above function (add()) block will support? 19 | 20 | # NO 21 | 22 | sampleList =[1,2,3,4,5] 23 | outputList = [] 24 | for i in sampleList: 25 | outputList.append(squareNumber(i)) 26 | 27 | print(outputList) 28 | 29 | 30 | outputList2 = [] 31 | for i in sampleList: 32 | if checkForEven(i): 33 | outputList2.append(i) 34 | print("output list 2 is ", outputList2) 35 | # =================================================== 36 | 37 | evenNum = list(filter(lambda x: x%2 ==0, sampleList)) 38 | print(evenNum) 39 | 40 | 41 | sqNum = list(map(squareNumber, sampleList)) 42 | print("sqNum is .. ", sqNum) 43 | 44 | globalExample = map(lambda x, y: (x+y, x-y, x*y), [10, 20, 30, 40],[5,10,15,20]) 45 | globalExample = map(lambda x, y: (x+y, x-y, x*y), [10, 20, 30, 40],[5,10,15,20]) 46 | print(list(globalExample)) 47 | 48 | 49 | 50 | 51 | 52 | # List of strings 53 | l = ['sat', 'bat', 'cat', 'mat'] 54 | 55 | opList = [] 56 | for i in l: 57 | opList.append(list(i)) 58 | print(opList) 59 | 60 | map(list, l) 61 | 62 | 63 | 64 | # class calculator: 65 | # add = lambda x,y: x+y 66 | # sub = lambda x,y: x-y 67 | # mul = lambda x,y: x*y 68 | 69 | # def add(a,b): 70 | # return a+b 71 | 72 | # print("here you go ...") 73 | 74 | # cal = calculator() 75 | 76 | # print(calculator.add(10,5)) 77 | 78 | -------------------------------------------------------------------------------- /Lambda/timecomplexity.py: -------------------------------------------------------------------------------- 1 | import operator 2 | import time 3 | 4 | # Defining lists 5 | L1 = [1, 2, 3] 6 | L2 = [2, 3, 4] 7 | 8 | # Starting time before map 9 | # function 10 | t1 = time.time() 11 | 12 | # Calculating result 13 | a, b, c = map(operator.mul, L1, L2) 14 | 15 | # Ending time after map 16 | # function 17 | t2 = time.time() 18 | 19 | # Time taken by map function 20 | print("Result:", a, b, c) 21 | print("Time taken by map function: %.6f" %(t2 - t1)) 22 | 23 | # Starting time before naive 24 | # method 25 | t1 = time.time() 26 | 27 | # Calculating result usinf for loop 28 | print("Result:", end = " ") 29 | for i in range(3): 30 | print(L1[i] * L2[i], end = " ") 31 | 32 | # Ending time after naive 33 | # method 34 | t2 = time.time() 35 | print("\nTime taken by for loop: %.6f" %(t2 - t1)) -------------------------------------------------------------------------------- /Map/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/Map/__init__.py -------------------------------------------------------------------------------- /MathOperationAndLoops/ArithmeticOperators.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # Let's learn about Python's arithmetic operators. 3 | # 4 | # First, let's read two integers: 5 | # 6 | # a = int(raw_input()) 7 | # b = int(raw_input()) 8 | # The three basic arithmetic operators are the following: 9 | # 10 | # Addition (+) 11 | # Subtraction (-) 12 | # Multiplication (*) 13 | # (We'll learn about division in the next task.) 14 | # 15 | # Task 16 | # Read two integers from STDIN and print three lines where: 17 | # 18 | # The first line contains the sum of the two numbers. 19 | # The second line contains the difference of the two numbers (first - second). 20 | # The third line contains the product of the two numbers. 21 | # Input Format 22 | # The first line contains the first integer, aa. The second line contains the second integer, bb. 23 | # 24 | # Constraints 25 | # 1?a?10101?a?1010 26 | # 1?b?10101?b?1010 27 | # 28 | # Output Format 29 | # Print the three lines as explained above. 30 | # 31 | # Sample Input 32 | # 33 | # 3 34 | # 2 35 | # Sample Output 36 | # 37 | # 5 38 | # 1 39 | # 6 40 | # Explanation 41 | # 3+2?53+2?5 42 | # 3?2?13?2?1 43 | # 3?2?6 44 | 45 | if __name__ == '__main__': 46 | a = int(input("Enter your first number: ")) 47 | b = int(input("Enter your second number: ")) 48 | if (a !='' or b != ''): 49 | print("Addition of ",a, " and ", b, "is", a+b) 50 | print("Subraction of ",a, " and ", b, "is", a-b) 51 | print("Product of 1",a, " and ", b, "is", a*b) 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /MathOperationAndLoops/BaiscForLoop.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # Loops are control structures that iterate over a range to perform a certain task. 3 | # 4 | # There are two kinds of loops in Python. 5 | # 6 | # A for loop: 7 | # 8 | for i in range(0,5): 9 | print i 10 | # And a while loop: 11 | # 12 | i = 0 13 | while i < 5: 14 | print i 15 | i+=1 16 | # Here, the term range(0,5) returns a list of integers from 00 to 55: [0,1,2,3,4][0,1,2,3,4]. 17 | # 18 | # Task 19 | # Read an integer NN. For all non-negative integers i> a = 1, # Define a tuple with one member 27 | # >> a = (2, 6) 28 | # >> a[1] = 1 # You cannot alter the elements in tuple. 29 | # TypeError: 'tuple' object does not support item assignment 30 | # 31 | # For using a tuple, the method is similar to lists. Tuples are most commonly used to assign more than one variable in one statement, such as simultaneous assignment. 32 | # */ 33 | # 34 | 35 | # Enter your code here. Read input from STDIN. Print output to STDOUT 36 | from __future__ import division 37 | 38 | a = int(raw_input()) 39 | #b = int(raw_input()) 40 | #c = int(raw_input()) 41 | #d = int(raw_input()) 42 | 43 | for i in range(0,a): 44 | print i*i 45 | 46 | -------------------------------------------------------------------------------- /MathOperationAndLoops/PerformingDivision.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # Task 3 | # Read two integers and print two lines. The first line should contain integer division, aa//bb. The second line should contain float division, aa/bb. 4 | # 5 | # You don't need to perform any rounding or formatting operations. 6 | # 7 | # Input Format 8 | # The first line contains the first integer, aa. The second line contains the second integer, bb. 9 | # 10 | # Output Format 11 | # Print the two lines as described above. 12 | # 13 | # Sample Input 14 | # 15 | # 4 16 | # 3 17 | # sample Output 18 | # 19 | # 1 20 | # 1.3333333333333333 21 | 22 | # Enter your code here. Read input from STDIN. Print output to STDOUT 23 | from __future__ import division 24 | 25 | a = int(raw_input()) 26 | b = int(raw_input()) 27 | 28 | print a//b 29 | print a/b 30 | -------------------------------------------------------------------------------- /MathOperationAndLoops/PrintSpeciality.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # In Python 2, the default print is a simple IO method that doesn't give many options to play around with. 3 | # 4 | # The following two examples will summarize it. 5 | # 6 | # Example 1: 7 | # 8 | # var, var1, var2 = 1,2,3 9 | # print var 10 | # print var1, var2 11 | # Prints two lines and, in the second line, var1var1 and var2var2 are separated by a single space. 12 | # 13 | # Example 2: 14 | # 15 | # for i in xrange(10): 16 | # print i, 17 | # Prints each element separated by space on a single line. Removing the comma at the end will print each element on a new line. 18 | # 19 | # Let's import the advanced print_function from the __future__ module. 20 | # 21 | # Its method signature is below: 22 | # 23 | # print(value, ..., sep=' ', end='\n', file=sys.stdout) 24 | # Here, you can add values separated by a comma. The arguments sep, end, and file are optional, but they can prove helpful in formatting output without taking help from a string module. 25 | # 26 | # The argument definitions are below: 27 | # sep defines the delimiter between the values. 28 | # end defines what to print after the values. 29 | # file defines the output stream. 30 | # 31 | # Interesting, isn't it? 32 | # 33 | # Task 34 | # Read an integer NN. 35 | # 36 | # Without using any string methods, try to print the following: 37 | # 38 | # 1,2,3.....N1,2,3.....N 39 | # 40 | # Note that "....." represents the values in between. 41 | # 42 | # Input Format 43 | # The first line contains an integer NN. 44 | # 45 | # Output Format 46 | # Output the answer as explained in the task. 47 | # 48 | # Sample Input 49 | # 50 | # 3 51 | # Sample Output 52 | # 53 | # 123 54 | # Pro Tip 55 | # You can use the print function inside a map(). Can you do a 11 line code to solve the problem above? 56 | 57 | # Enter your code here. Read input from STDIN. Print output to STDOUT 58 | from __future__ import print_function 59 | a = int(raw_input()) 60 | s = [] 61 | for i in range(1, (a+1)): 62 | s.append(i) 63 | print(int("".join(str(x) for x in s))) 64 | 65 | -------------------------------------------------------------------------------- /MathOperationAndLoops/getInputFromUser.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # That's one way of doing it for yourself. However, we don't ask questions in competitive programming, we answer them! We will only use raw_input() to read a string without asking any questions to the system. 4 | # 5 | # Task 6 | # Read a string from the console and print it. 7 | # 8 | # Input Format 9 | # The first and only line of input contains a string. 10 | # 11 | # Constraints 12 | # String length ? 500 13 | # 14 | # Output Format 15 | # Print the same string back. 16 | # 17 | # Sample Input 18 | # 19 | # How many chickens does it take to cross the road? 20 | # Sample Output 21 | # 22 | # How many chickens does it take to cross the road? 23 | # Enter your code here. Read input from STDIN. Print output to STDOUT 24 | #getInput = raw_input("How many chickens does it take to cross the road?\n") 25 | name = input("Enter your name: ") 26 | print ("Thanks for contacting ", name) -------------------------------------------------------------------------------- /MultiTasking/Asynchronous.py: -------------------------------------------------------------------------------- 1 | # import concurrent.futures 2 | # import requests 3 | # import threading 4 | # import time 5 | 6 | 7 | # thread_local = threading.local() 8 | 9 | 10 | # def get_session(): 11 | # if not hasattr(thread_local, "session"): 12 | # thread_local.session = requests.Session() 13 | # return thread_local.session 14 | 15 | 16 | # def download_site(url): 17 | # session = get_session() 18 | # with session.get(url) as response: 19 | # print(f"Read {len(response.content)} from {url}") 20 | 21 | 22 | # def download_all_sites(sites): 23 | # with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: 24 | # executor.map(download_site, sites) 25 | 26 | 27 | # if __name__ == "__main__": 28 | # sites = [ 29 | # "https://www.dinamalar.com", 30 | # "https://thehindu.com", 31 | # ] * 80 32 | # start_time = time.time() 33 | # download_all_sites(sites) 34 | # duration = time.time() - start_time 35 | # print(f"Downloaded {len(sites)} in {duration} seconds") 36 | 37 | 38 | L=len 39 | K=print 40 | import concurrent.futures,requests as D,threading as E,time as B 41 | import google_auth_oauthlib 42 | from tabnanny import check 43 | 44 | A=E.local() 45 | def F(): 46 | if not hasattr(A,'session'):A.session=D.Session() 47 | return A.session 48 | 49 | def G(url): 50 | A=F() 51 | with A.get(url)as B:K(f"Read {L(B.content)} from {url}") 52 | 53 | def H(sites): 54 | with concurrent.futures.ThreadPoolExecutor(max_workers=10)as A:A.map(G,sites) 55 | if __name__=='__main__': 56 | C=['https://www.dinamalar.com','https://thehindu.com']*80; 57 | I=B.time() 58 | H(C) 59 | J=B.time()-I 60 | 61 | K(f"Downloaded {L(C)} in {J} seconds") -------------------------------------------------------------------------------- /MultiTasking/MultiProcessing.py: -------------------------------------------------------------------------------- 1 | import time 2 | startTime = time.time() 3 | from multiprocessing import Pool 4 | 5 | def square(x): 6 | return x**2 7 | 8 | 9 | if __name__ == "__main__": 10 | pool = Pool(processes=1) 11 | for i in range(100): 12 | print(square(i),) 13 | print(pool.map(square, range(100))) 14 | print("total time taken ", time.time() - startTime) -------------------------------------------------------------------------------- /MultiTasking/Synchronous.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | 4 | 5 | def download_site(url, session): 6 | with session.get(url) as response: 7 | print(f"Read {len(response.content)} from {url}") 8 | 9 | 10 | def download_all_sites(sites): 11 | with requests.Session() as session: 12 | for url in sites: 13 | download_site(url, session) 14 | 15 | 16 | if __name__ == "__main__": 17 | sites = [ 18 | "https://www.dinamalar.com", 19 | "https://thehindu.com", 20 | ] * 80 21 | start_time = time.time() 22 | download_all_sites(sites) 23 | duration = time.time() - start_time 24 | print(f"Downloaded {len(sites)} in {duration} seconds") -------------------------------------------------------------------------------- /OOP/AbstractExample/BaseAbstractClass/ABC.py: -------------------------------------------------------------------------------- 1 | import abc 2 | 3 | 4 | class PluginBase(object): 5 | __metaclass__ = abc.ABCMeta 6 | 7 | @abc.abstractmethod 8 | def load(self, input): 9 | """Retrieve data from the input source and return an object.""" 10 | return 11 | 12 | @abc.abstractmethod 13 | def save(self, output, data): 14 | """Save the data object to the output.""" 15 | return -------------------------------------------------------------------------------- /OOP/AbstractExample/BaseAbstractClass/DerivedClass.py: -------------------------------------------------------------------------------- 1 | import abc 2 | __import__(ABC) 3 | 4 | class RegisteredImplementation(object): 5 | def load(self, input): 6 | return input.read() 7 | 8 | def save(self, output, data): 9 | return output.write(data) 10 | 11 | 12 | PluginBase.register(RegisteredImplementation) 13 | 14 | if __name__ == '__main__': 15 | print 'Subclass:', issubclass(RegisteredImplementation, PluginBase) 16 | print 'Instance:', isinstance(RegisteredImplementation(), PluginBase) -------------------------------------------------------------------------------- /OOP/Encapsulation/Data Abstraction.py: -------------------------------------------------------------------------------- 1 | class Person: 2 | def __init__(self, first, last, mob_num, email): 3 | self.firstName = first 4 | self.lastName = last 5 | self.id = mob_num 6 | self.email = email 7 | self.friends = [] 8 | # if access == "customer": 9 | # self.previ = "customer" 10 | # elif access == "staff": 11 | # self.previ = "admin" 12 | 13 | 14 | def add_friend(self, friend): 15 | if len(self.friends) < 10 and len(friend.friends) < 10: 16 | self.friends.append(friend) # p1 is addimg p2 in his friends list 17 | friend.friends.append(self) # p2 is adding p1 in his friends list 18 | 19 | def getCustomerList(self): 20 | ''' 21 | @name : getCustomerList 22 | @param1 : NA 23 | @desc : this is previleged method, only consumable to staff/admin 24 | @return : None 25 | ''' 26 | #since we do not store information in DB, admin previleged guys cannot able to retrieve data which stands in iterpreter. 27 | pass 28 | 29 | def getFriends(self): 30 | print (len(self.friends)) 31 | for i in self.friends: 32 | print (i) 33 | 34 | 35 | p1 = Person("David", "Wolber", "922-43-9873", "wolber@usfca.edu") 36 | p2 = Person("Bob", "Jones", "902-38-9973", "jones@usfca.edu") 37 | p3 = Person("admin", "admin", "123", "admin.gmail.com") 38 | 39 | print(p1) 40 | 41 | print(p2) 42 | 43 | p1.add_friend(p2) 44 | 45 | 46 | 47 | print (p1.firstName) 48 | print (list(p1.friends)) 49 | print(p1.friends[0].firstName) 50 | 51 | print (p1.getFriends()) 52 | -------------------------------------------------------------------------------- /OOP/Inheritance/HierarchicalInheritance.py: -------------------------------------------------------------------------------- 1 | # author = 'Sanjay' 2 | 3 | 4 | class Father(object): 5 | def __init__(self, x, y): 6 | self.x = x 7 | self.y = y 8 | 9 | def myCharacter(self): 10 | print ("Lets help as much as we can!") 11 | 12 | def myBehaviour(self): 13 | print ("Old is gold!") 14 | 15 | 16 | class FirstChild(Father): 17 | 18 | def __init__(self,a): 19 | self.a = a 20 | 21 | def myCharacter(self): 22 | print ("I'm the first child, I'll get angry at times.") 23 | 24 | 25 | class SecondChild(Father): # Method resolution order 26 | def __init__(self): 27 | print("My father is all to me!") 28 | 29 | 30 | if __name__ == '__main__': 31 | secondObj = SecondChild() 32 | secondObj.myCharacter() 33 | secondObj.myBehaviour() 34 | 35 | firstChildObj = FirstChild(10) 36 | firstChildObj.myCharacter() 37 | firstChildObj.myBehaviour() #firstchild doesn't contain myBehaviour method, so it has to contact base myBehaviour only. 38 | 39 | -------------------------------------------------------------------------------- /OOP/Inheritance/HybridInheritance.py: -------------------------------------------------------------------------------- 1 | # author = 'Sanjay' 2 | 3 | 4 | class GrandFather(object): 5 | def __init__(self, x, y): 6 | self.x = x 7 | self.y = y 8 | 9 | def myCharacter(self): 10 | print ("Lets help as much as we can!") 11 | 12 | def myBehaviour(self): 13 | print ("Old is gold!") 14 | 15 | 16 | class Father(GrandFather): 17 | 18 | def __init__(self): 19 | pass 20 | 21 | def myCharacter(self): 22 | print ("I have my own Character! I'm a father of two child") 23 | 24 | 25 | class FirstChild(Father): 26 | def __init__(self): 27 | pass 28 | 29 | def myCharacter(self): 30 | print ("I have my own character, May be because I behave like my dad.") 31 | 32 | 33 | class SecondChild(Father): 34 | def __init__(self): 35 | print ("I dont need to be unique, My Father is already having good character and my grand father is having good" 36 | "behaviour") 37 | 38 | if __name__ == '__main__': 39 | firstChildObj = FirstChild() 40 | firstChildObj.myCharacter() 41 | firstChildObj.myBehaviour() 42 | # firstchild doesn't contain myBehaviour method, 43 | # it contacts father and search for myBehaviour, father also doesn't have 44 | # o it has to contact base myBehaviour only. 45 | 46 | secondChildObj = SecondChild() 47 | secondChildObj.myCharacter() 48 | secondChildObj.myBehaviour() 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /OOP/Inheritance/MultilevelInheritance.py: -------------------------------------------------------------------------------- 1 | # author = 'Sanjay' 2 | 3 | class Father(object): 4 | def __init__(self, x, y): 5 | self.x = x 6 | self.y = y 7 | 8 | def behaviour(self): 9 | print ("I'm father! my behaviour is old.") 10 | 11 | 12 | class FirstChild(Father): 13 | 14 | def __init__(self, a): 15 | self.a = a 16 | 17 | def behaviour(self): 18 | print ("I'm the child, but I feel responsible") 19 | 20 | 21 | class SecondChild(FirstChild): 22 | def __init__(self): 23 | pass 24 | 25 | ''' 26 | If method is uncommented, behaviour() will get call by its own class object. 27 | if the method is not available, then it will contact the inherited class. 28 | Even if the FirstChild class also doesn't have behaviour method, then it will contact 29 | Father class for sure and calls behaviour method. 30 | ''' 31 | # def behaviour(self): 32 | # print ("I have my own behaviour") 33 | 34 | if __name__ == '__main__': 35 | c = SecondChild() 36 | c.behaviour() 37 | print (SecondChild.__mro__) -------------------------------------------------------------------------------- /OOP/Inheritance/SingleInheritance.py: -------------------------------------------------------------------------------- 1 | # author == 'Sanjay' 2 | 3 | class A(object): 4 | 5 | def __init__(self, a, b): 6 | self.a = a 7 | self.b = b 8 | 9 | def add(self): 10 | return (self.a + self.b) 11 | 12 | def subract(self): 13 | return (abs(self.a - self.b)) 14 | 15 | def something(self): 16 | print ("Hey this is a something function") 17 | 18 | 19 | 20 | class firstChild(A): 21 | 22 | def __init__(self, x, y): 23 | 24 | self.x = x 25 | self.y = y 26 | super(firstChild, self).__init__(x, y) 27 | 28 | def multiplication(self): 29 | print(self.x * self.y) 30 | 31 | def division(self): 32 | print( self.x/self.y) 33 | 34 | # def something(self): 35 | # print ("inside firstChild") 36 | 37 | # 'Whenever we inherit A in firstChild, its not required to override all methods which Parent has.' 38 | # 'In this above code, Add and Subract are the two methods.. ' \ 39 | # 'override only when there is a logic change, else no need to calling the method and returns nothing.' 40 | 41 | if __name__ == '__main__': 42 | firstNum = int(input("enter first num")) 43 | secondNum = int(input("enter second num")) 44 | myObj = firstChild(firstNum, secondNum) 45 | myObj.multiplication() 46 | myObj.division() 47 | x = myObj.add() 48 | print (x) 49 | 50 | newObject = firstChild(10,10) 51 | newObject.something() -------------------------------------------------------------------------------- /OOP/Others/AnonymousFunction/MapFilterReduceLamba.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return x**2 3 | 4 | if __name__ == '__main__': 5 | print(square(10)) 6 | 7 | l1 = [1,2,4,5,654,5,65,778] 8 | # for i in l1: 9 | # print(square(i),end=" ") 10 | 11 | l2 = [None]*len(l1) 12 | print (l2) 13 | 14 | l3 = (list(map(square, [1,2,4,5,654,5,65,778]))) 15 | l4 = range(len(l1)) 16 | 17 | print(dict(zip(l3,l2))) 18 | 19 | from functools import reduce 20 | # print(list(lambda x,y -> x*y)) 21 | print(list(map(lambda x,y: x*y, l1, l4))) 22 | 23 | # reduce(lambda x,y: x+y, [1,2,3,4,5]) 24 | 25 | ''' 26 | [1,2,3,4,5] 27 | [(1,2),3,4,5] 28 | [(3),3,4,5] --> [(3,3),4,5] 29 | [(6),4,5] ---> [(6,4),5] 30 | [(10),5] --> [(10,5)] 31 | [15] 32 | ''' 33 | 34 | p = map(lambda x: x*2, [1,2,3,4,5]) 35 | 36 | print(list(filter(lambda x: x , list(range(1,11))))) 37 | 38 | print ("hey..") 39 | 40 | def mul(a): 41 | r = 1 42 | # for i in a: 43 | # r = r * i 44 | return (r) 45 | 46 | 47 | showingToMari = list(map(mul, [1,2,3,4,5])) 48 | print(showingToMari) 49 | 50 | -------------------------------------------------------------------------------- /OOP/Others/AnonymousFunction/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/OOP/Others/AnonymousFunction/__init__.py -------------------------------------------------------------------------------- /OOP/Others/Decorators/DecoratorsExample.py: -------------------------------------------------------------------------------- 1 | 2 | def getName(name): 3 | def greetings(): 4 | return "Hello " 5 | print(greetings() + name) 6 | return greetings() + name 7 | 8 | 9 | def my_decorator(some_function): 10 | 11 | def wrapper(): 12 | print("Something is happening before some_function() is called.") 13 | some_function() 14 | print("Something i s happening after some_function() is called.") 15 | return wrapper 16 | 17 | 18 | def just_some_function(): 19 | print("Wheee!") 20 | 21 | 22 | # just_some_function = my_decorator(just_some_function) 23 | # 24 | # just_some_function() 25 | # 26 | # getName("Sanjay") 27 | 28 | def my_decorator(some_function): 29 | 30 | def wrapper(): 31 | 32 | num = 10 33 | 34 | if num == 10: 35 | print("Yes!") 36 | else: 37 | print("No!") 38 | 39 | some_function() 40 | 41 | print("Something is happening after some_function() is called.") 42 | 43 | return wrapper 44 | 45 | if __name__ == '__main__': 46 | my_decorator(just_some_function) 47 | 48 | @my_decorator 49 | def just_some_function(): 50 | print("Wheee!") 51 | 52 | 53 | # ======================Real World Example ================================# 54 | 55 | import time 56 | 57 | 58 | def timing_function(some_function): 59 | 60 | """ 61 | Outputs the time a function takes 62 | to execute. 63 | """ 64 | 65 | def wrapper(): 66 | t1 = time.time() 67 | some_function() 68 | t2 = time.time() 69 | return "Time it took to run the function: " + str((t2 - t1)) + "\n" 70 | return wrapper 71 | 72 | 73 | @timing_function 74 | def my_function(): 75 | num_list = [] 76 | for num in (range(0, 10000)): 77 | num_list.append(num) 78 | print("\nSum of all the numbers: " + str((sum(num_list)))) 79 | 80 | 81 | print(my_function()) -------------------------------------------------------------------------------- /OOP/Others/Decorators/decorators.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | def my_decorator(some_function): 4 | 5 | def wrapper(): 6 | print("Something is happening before some_function() is called.") 7 | some_function() 8 | print("Something is happening after some_function() is called.") 9 | return wrapper 10 | 11 | 12 | def just_some_function(): 13 | print("Wheee!") 14 | 15 | 16 | if __name__ == '__main__': 17 | # just_some_function() 18 | just_some_fun = my_decorator(just_some_function) 19 | just_some_fun() 20 | # just_some_function() 21 | # my_decorator(just_some_function) 22 | -------------------------------------------------------------------------------- /OOP/Others/ExceptionalHandling/CustomException.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | 4 | def testingCustom(n): 5 | try: 6 | if n <0: 7 | # raise Exception('bad thing happened') 8 | raise SanjayException("bad thing happened") 9 | else: 10 | print ("number which you entered is", n) 11 | except SanjayException as e: 12 | SanjayException("Hey !! ") 13 | 14 | 15 | class SanjayException(Exception): 16 | # def __init__(self,dErrorArguements): 17 | # Exception.__init__(self,"my exception was raised with arguments {0}") 18 | # self.dErrorArguments = dErrorArguements 19 | # 20 | # def __str__(self): 21 | # return "sanjay" 22 | def __init__(self, argg): 23 | self.error = argg 24 | print(self.error) 25 | 26 | if __name__ == '__main__': 27 | print ("inside main") 28 | testingCustom(-9) 29 | 30 | 31 | -------------------------------------------------------------------------------- /OOP/Others/ExceptionalHandling/TryExcept.py: -------------------------------------------------------------------------------- 1 | # Author = __Sanjay 2 | 3 | from __future__ import division 4 | def isDivide(x,y): 5 | try: 6 | if x >= 1: 7 | if x > y: 8 | print (abs(x/y)) 9 | elif y > x: 10 | print (abs(y/x)) 11 | else: 12 | raise ZeroDivisionError 13 | except ZeroDivisionError as e: 14 | print (e) 15 | else: 16 | print ("inside else") 17 | finally: 18 | print ("inside finally") 19 | # raise ZeroDivisionError 20 | 21 | if __name__ == '__main__': 22 | # isDivide(1, 10) 23 | isDivide(10, 0) -------------------------------------------------------------------------------- /OOP/Others/ExceptionalHandling/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/OOP/Others/ExceptionalHandling/__init__.py -------------------------------------------------------------------------------- /OOP/Others/FileHandling/FileReadingWriting.py: -------------------------------------------------------------------------------- 1 | # Open a file 2 | import time 3 | 4 | with open('input1.txt', 'r+') as info: 5 | print ("Name of the file: ", info.name) 6 | print ("Closed or not : ", info.closed) 7 | print ("Opening mode : ", info.mode) 8 | # print ("Softspace flag : ", info.softspace) 9 | 10 | start= time.time() 11 | 12 | # line = info.readline() 13 | line2 = info.readlines() 14 | # line3 = info.xreadlines() 15 | # print ("line is ====",line) 16 | # print ("line 2 is ====",line2) 17 | # print ("line3 is ======", line3) 18 | for i,j in enumerate(line2): 19 | print (i, j) 20 | # if i == 4: 21 | # print "Hey" 22 | # print (j[0]) 23 | # j = info.write("Something I'm writing here!") 24 | # print (j[5]) 25 | 26 | # with open('file', 'r') as input_file, open('new_file', 'r+') as output_file: 27 | # for line in input_file: 28 | # if line.strip() == 'to replace': 29 | # output_file.write('new line\n') 30 | # else: 31 | # output_file.write(line) 32 | 33 | # print ("time taken to read", (end-start)) 34 | # print (data + "Hi") 35 | info.close() 36 | 37 | 38 | # for line in fileinput.input('input1.txt', inplace=True): 39 | # print (line.rstrip().replace('Something Im writing here!', 'changed text'),) 40 | 41 | def replace_line(file_name, line_num, text): 42 | lines = open(file_name, 'r').readlines() 43 | print ("Lines ... ==== ") 44 | lines[line_num] = text 45 | print(lines) 46 | out = open(file_name, 'w') 47 | out.writelines(lines) 48 | out.close() 49 | 50 | def afterReplacingDisplay(fileName): 51 | print('After replacin my text..here we go....') 52 | lines = open(fileName, 'r+').readlines() 53 | print(lines) 54 | 55 | # replace_line('input1.txt', 0, 'hey this is goods\n') 56 | # afterReplacingDisplay('input1.txt') 57 | 58 | end = time.time() 59 | print ("time difference: ", end - start) -------------------------------------------------------------------------------- /OOP/Others/FileHandling/input.txt: -------------------------------------------------------------------------------- 1 | 12:00:00 MKT PRT exchange_sanjay_name connected to 127.0.0.0.1 from 192.160.0.1 2 | 12:00:00 MKT PRT exchange_sanjay_name connected to 127.0.0.0.4 from 192.160.0.2 3 | 12:00:00 MKT PRT exchange_sanjay_name connected to 127.0.0.0.6 from 192.160.0.3 4 | 12:00:00 MKT PRT exchange_sanjay_name connected to 127.0.0.0.9 from 192.160.0.4 -------------------------------------------------------------------------------- /OOP/Others/FileHandling/input1.txt: -------------------------------------------------------------------------------- 1 | Mage 2 | hey this is goods 3 | hey this is goods 4 | hey this is sanjay 5 | trying something 6 | hope it ll go fine 7 | thanks 8 | now lets see heresSomething I'm writing here!Something I'm writing here! 9 | 10 | Mage 11 | hey this is sanjay 12 | trying something 13 | hope it ll go fine 14 | thanks 15 | 16 | 12:00:00 MKT PRT exchange_sanjay_name connected to 127.0.0.0.1 from 192.160.0.1 17 | 12:00:00 MKT PRT exchange_sanjay_name connected to 127.0.0.0.4 from 192.160.0.2 18 | 12:00:00 MKT PRT exchange_sanjay_name connected to 127.0.0.0.6 from 192.160.0.3 19 | 12:00:00 MKT PRT exchange_sanjay_name connected to 127.0.0.0.9 from 192.160.0.4 -------------------------------------------------------------------------------- /OOP/Others/FileHandling/ram.txt: -------------------------------------------------------------------------------- 1 | 12:00:01 MKT PRT exchange_sanjay_x connected to 127.0.0.0.1 from 192.160.0.1 2 | 12:10:00 MKT PRT exchange_sanjay_y connected to 127.0.0.0.6 from 192.160.0.2 3 | 12:20:00 MKT PRT exchange_sanjay_x disconnected to 127.0.0.0.4 from 192.160.0.1 4 | 12:30:00 MKT PRT exchange_sanjay_y disconnected to 127.0.0.0.9 from 192.160.0.2 5 | 12:50:00 MKT PRT exchange_sanjay_x connected to 127.0.0.0.1 from 192.160.0.1 6 | 12:56:00 MKT PRT exchange_sanjay_y connected to 127.0.0.0.6 from 192.160.0.2 -------------------------------------------------------------------------------- /OOP/Others/FileHandling/readLog.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | with open('C:\\Users\\sanja\\Documents\\GitHub\\Python-Data-Structure\\OOP\\Others\\FileHandling\\ram.txt', 'r+') as info: 5 | info = info.readlines() 6 | 7 | # print(info) 8 | 9 | commandList = ['connected', 'disconnected'] 10 | exchangeList= ['exchange_sanjay_x', 'exchange_sanjay_y'] 11 | 12 | count = 0 13 | 14 | sampleList= [] 15 | 16 | connectedList = [] 17 | disconnectedList = [] 18 | 19 | output = {} 20 | 21 | for lines in info: 22 | splittedInfo = lines.split(" ") 23 | for exchangeName in exchangeList: 24 | if exchangeName in splittedInfo and 'connected' in splittedInfo: 25 | connectedList.append(exchangeName) 26 | if exchangeName in splittedInfo and 'disconnected' in splittedInfo: 27 | disconnectedList.append(exchangeName) 28 | 29 | 30 | print(dict(Counter(connectedList))) 31 | print(dict(Counter(disconnectedList))) 32 | 33 | 34 | { 35 | 'exchange_sanjay_x': { 36 | 'timeStamp': '12:00:57', 37 | 'connectedCount': 4 38 | 'disconnectedCount': 2 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /OOP/Others/MapFilterReduceLamba.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/OOP/Others/MapFilterReduceLamba.py -------------------------------------------------------------------------------- /OOP/Polymorphism/MethodOverloading.py: -------------------------------------------------------------------------------- 1 | # author = _'Sanjay' 2 | 3 | class SampleClass(object): 4 | 5 | # for name sake, I've defined a default constructor. 6 | def __init__(self): 7 | pass 8 | 9 | def add(self, firstNum, secondNum): 10 | ''' 11 | @name: add 12 | @param: firstNum, secondNum 13 | @desc: Takes two input paramter, adding them and returning 14 | @return: sum(firstNum, secondNum) 15 | ''' 16 | return firstNum + secondNum 17 | 18 | 19 | # this method does the same as above, but the difference is, it takes 3 parameter here. 20 | def add(self, firstNum, secondNum, thirdNum): 21 | ''' 22 | @name : add 23 | @param: firstNum, secondNum, thirdNum 24 | @desc: takes three input parameter, adding them and returning 25 | @return : sum(firstNum, secondNum, threeNum) 26 | ''' 27 | return firstNum + secondNum + thirdNum 28 | 29 | objRam = SampleClass() 30 | # firstFunctionCall = objRam.add(10,20) 31 | secondFunctionCall = objRam.add(10,20,30) 32 | 33 | objRam.special_add(1,2) 34 | 35 | 36 | 37 | #Method overloading is not possible 38 | # This is compile time polymorphism. 39 | x = SampleClass() 40 | x.add(1,2,3) 41 | -------------------------------------------------------------------------------- /OOP/Polymorphism/MethodOverloading_NotEfficient.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 1. Reason for not using class? 3 | Because, 4 | ''' 5 | 6 | # Function to take multiple arguments 7 | # *args is a list [1,2,3...] 8 | def add(datatype, *args): 9 | 10 | # if datatype is int 11 | # initialize answer as 0 12 | if datatype =='int': 13 | answer = 0 14 | 15 | # if datatype is str 16 | # initialize answer as '' 17 | if datatype =='str': 18 | answer ='' 19 | 20 | # Traverse through the arguments 21 | for x in args: 22 | 23 | # This will do addition if the 24 | # arguments are int. Or concatenation 25 | # if the arguments are str 26 | answer = answer + x 27 | 28 | print(answer) 29 | 30 | 31 | # Integer 32 | add('int', 5, 6,101,203,4354,54,65,76,4,6567,87,554,65,734,34,45,56,767,778) 33 | 34 | # String 35 | add('str', 'Hi ', 'Geeks', "ram", "all", 'the', 'best') 36 | 37 | 38 | class sampleclass(): 39 | 40 | def __init__(self, *args): 41 | self.x = args 42 | 43 | 44 | def showMe(self): 45 | print(self.x) 46 | 47 | 48 | ramObj = sampleclass(10,20,30,'Sanjay') 49 | ramObj.showMe() 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /OOP/Polymorphism/MethodOverriding.py: -------------------------------------------------------------------------------- 1 | 2 | class Father(): 3 | 4 | def __init__(self, a, b): 5 | self.a = a 6 | self.b = b 7 | 8 | def role(self): 9 | print("Father of two childres") 10 | 11 | def occupation(self): 12 | print("Father is working in Bank") 13 | 14 | def travellingIn(self): 15 | print("As a father, I use Audi Car to go office") 16 | 17 | class Mother(Father): 18 | 19 | def __init__(self,): 20 | print ("b constructor") 21 | 22 | def role(self): 23 | print("Mother of Two childrens") 24 | 25 | def occupation(self): 26 | print("Home maker") 27 | 28 | def whatCooking(self): 29 | print("Mother is preparing Pasta!") 30 | 31 | 32 | class Son(Father, Mother): 33 | pass 34 | 35 | class Son(Mother): 36 | pass 37 | 38 | # creating an object of mother. 39 | instanceOfMother = Mother() 40 | 41 | instanceOfMother.role() 42 | 43 | instanceOfMother.occupation() 44 | 45 | instanceOfMother.whatCooking() 46 | 47 | instanceOfMother.travellingIn() 48 | 49 | 50 | # creating an object of Father 51 | 52 | fatherInstance = Father(10,20) 53 | 54 | fatherInstance.role() 55 | 56 | fatherInstance.travellingIn() 57 | 58 | fatherInstance.occupation() 59 | 60 | fatherInstance.whatCooking() ## this will throw error -------------------------------------------------------------------------------- /OOP/Polymorphism/SuperMethod.py: -------------------------------------------------------------------------------- 1 | class SomeBaseClass(object): 2 | def __init__(self): 3 | print('SomeBaseClass.__init__(self) called') 4 | 5 | class UnsuperChild(SomeBaseClass): 6 | def __init__(self): 7 | print('Child.__init__(self) called') 8 | SomeBaseClass.__init__(self) 9 | 10 | class SuperChild(SomeBaseClass): 11 | def __init__(self): 12 | print('SuperChild.__init__(self) called') 13 | super(SuperChild, self).__init__() 14 | 15 | s = SuperChild() 16 | 17 | print s 18 | u = UnsuperChild() 19 | # print "**" 20 | print u 21 | # print "****" 22 | 23 | class InjectMe(SomeBaseClass): 24 | def __init__(self): 25 | print('InjectMe.__init__(self) called') 26 | super(InjectMe, self).__init__() 27 | 28 | class UnsuperInjector(UnsuperChild, InjectMe): pass 29 | 30 | class SuperInjector(SuperChild, InjectMe): pass 31 | 32 | print "-----------------" 33 | x = SuperInjector() 34 | #x.mro 35 | 36 | y = UnsuperInjector() 37 | 38 | print "MRO.." 39 | print SuperInjector.mro() 40 | print UnsuperInjector.mro() -------------------------------------------------------------------------------- /OOP/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/OOP/__init__.py -------------------------------------------------------------------------------- /Paramiko/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/Paramiko/__init__.py -------------------------------------------------------------------------------- /Paramiko/paramiko.py: -------------------------------------------------------------------------------- 1 | # below code needs to be refactored to a bigger level 2 | 3 | import paramiko 4 | from paramiko import AUTH_SUCCESSFUL, AUTH_FAILED 5 | from paramiko import ( 6 | SSHException, 7 | AuthenticationException, 8 | BadAuthenticationType, 9 | PartialAuthentication, 10 | ) 11 | 12 | class CustomParamiko: 13 | def __init__(self, hostname, username, paassword): 14 | self.hostname = hostname 15 | self.username = username 16 | self.password = paassword 17 | 18 | def connectToHost(self): 19 | try: 20 | ssh_client=paramiko.SSHClient() 21 | ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 22 | ssh_client.connect(hostname=self.hostname,username=self.username,password=self.password) 23 | 24 | return {AUTH_SUCCESSFUL: "Connected Successfully"} 25 | except (SSHException, AuthenticationException, BadAuthenticationType) as e: 26 | print(e.with_traceback) 27 | return {AUTH_FAILED: "Failed to Connect"} 28 | 29 | def runCommand(self, commandToExecute): 30 | if commandToExecute == '' or len(commandToExecute) == 0 : 31 | raise Exception 32 | try: 33 | result = ssh_client.exec_command(commandToExecute) 34 | return result 35 | except Exception as e: 36 | print(e) 37 | 38 | def downloadFileFromRemote(self, remoteFilePath, localFilePath): 39 | ftp_client=ssh_client.open_sftp() 40 | ftp_client.get(remoteFilePath,localFilePath) 41 | # not sure do I need to close the connection or not. 42 | ftp_client.close() 43 | 44 | def uploadFileFromLocal(self, localFilePath, remoteFilePath): 45 | ftp_client=ssh.open_sftp() 46 | ftp_client.put(localFilePath,remoteFilePath) 47 | # not sure do I need to close the connection or not. 48 | ftp_client.close() 49 | 50 | 51 | def closeConnection(self): 52 | ssh_client.close() 53 | -------------------------------------------------------------------------------- /QDataStructure/Deque_Implementation.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # A deque, also known as a double-ended queue, is an ordered collection of items similar to the queue. 4 | # It has two ends, a front and a rear, and the items remain positioned in the collection. 5 | # What makes a deque different is the unrestrictive nature of adding and removing items. 6 | # New items can be added at either the front or the rear. 7 | # Likewise, existing items can be removed from either end. 8 | # it does not require the LIFO and FIFO orderings that are enforced by those data structures. 9 | # It is up to you to make consistent use of the addition and removal operations. 10 | 11 | # Deque() creates a new deque that is empty. It needs no parameters and returns an empty deque. 12 | 13 | # addFront(item) adds a new item to the front of the deque. It needs the item and returns nothing. 14 | 15 | # addRear(item) adds a new item to the rear of the deque. It needs the item and returns nothing. 16 | 17 | # removeFront() removes the front item from the deque. It needs no parameters and returns the item. The deque is modified. 18 | 19 | # removeRear() removes the rear item from the deque. It needs no parameters and returns the item. The deque is modified. 20 | 21 | # isEmpty() tests to see whether the deque is empty. It needs no parameters and returns a boolean value. 22 | 23 | # size() returns the number of items in the deque. It needs no parameters and returns an integer. 24 | 25 | class Deque: 26 | def __init__(self): 27 | self.items = [] 28 | 29 | def addFront(self,item): 30 | self.items.append(item) 31 | 32 | def addRear(self,item): 33 | self.items.insert(0,item) 34 | 35 | def removeFront(self): 36 | self.items.pop() 37 | 38 | def removeRear(self): 39 | self.items.pop(0) 40 | 41 | def isEmpty(self): 42 | return self.items == [] 43 | 44 | def size(self): 45 | return len(self.items) 46 | 47 | if __name__ == '__main__': 48 | d=Deque() 49 | print(d.isEmpty()) 50 | d.addRear(4) 51 | d.addRear('dog') 52 | d.addFront('cat') 53 | d.addFront(True) 54 | print(d.size()) 55 | print(d.isEmpty()) 56 | d.addRear(8.4) 57 | print(d.removeRear()) 58 | print(d.removeFront()) -------------------------------------------------------------------------------- /QDataStructure/RenamingAFile.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/QDataStructure/RenamingAFile.py -------------------------------------------------------------------------------- /QDataStructure/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/QDataStructure/__init__.py -------------------------------------------------------------------------------- /QR/HelloWorldQR.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/f31e2a1c20e85ef21beb611296e7777909cbefc1/QR/HelloWorldQR.png -------------------------------------------------------------------------------- /QR/HelloWorldQR.py: -------------------------------------------------------------------------------- 1 | import pyqrcode 2 | 3 | img = pyqrcode.create("Hello World") 4 | 5 | img.png("HelloWorldQR.png", scale=6) 6 | 7 | -------------------------------------------------------------------------------- /QR/QR_Encode.py: -------------------------------------------------------------------------------- 1 | 2 | # Hey in this file, we are going to explore about QR Code. 3 | 4 | # Now a days, it's common to people are scanning the QR Code in any shopping mall for the payment. 5 | # In general, when you scan the code via QR Code Scanner/Reader - internally it reads the data in the code and do action accordingly. 6 | 7 | # Let's how to create/make a QR code - which internally has some text or data. 8 | 9 | # We'll be writing a program - Takes input from the user, construct a QR code in .png format - output of this execution should bring a QR code (which user data will be binding internally) 10 | 11 | # Using a Python Library called ```pyqrcode``` 12 | 13 | # Here's the steps for installing that library, 14 | 15 | # Windows 16 | # 1. pip install pyqrcode 17 | # 2. pip install pypng 18 | 19 | 20 | import pyqrcode 21 | 22 | # firstLevelQRCode = pyqrcode.create("Hello World") # Hello world is the text which I'm appending to generate a QR Code. 23 | 24 | # when you try printing the img variable - QRCode(content=b'Hello World', error='H', version=2, mode='binary') 25 | # means it gives QRCode object 26 | 27 | # print(type(firstLevelQRCode)) - 28 | 29 | # finalImage = firstLevelQRCode.png("HelloWorldQR.png", scale=6) # 30 | 31 | # print("Output would have generated") 32 | 33 | def takeInputFromUser(): 34 | givenInput = input("Enter the data : ") 35 | if givenInput: 36 | print("As an output, you can expect a QR Code in .png format") 37 | return givenInput 38 | else: 39 | print("Please input some data") 40 | return None 41 | 42 | def getFileNameFromUser(): 43 | import random 44 | fileName = input("Enter the filename: ") 45 | return fileName if fileName else str(random.randint(1,100)) 46 | 47 | def constructQR(): 48 | infoFromUser = takeInputFromUser() 49 | if(infoFromUser): 50 | output = pyqrcode.create(infoFromUser) 51 | fileName = getFileNameFromUser() 52 | output.png(fileName + '.png', scale=6) 53 | print(fileName + ".png file got generated and saved in your local.") 54 | else: 55 | takeInputFromUser() 56 | 57 | if __name__ == '__main__': 58 | constructQR() -------------------------------------------------------------------------------- /RE/trail.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | sen = "8=FIX.4.2 9=166 35=j 49=broker 56=buySide 34=11 52=20100622-04:56:07 45=12 372=D 379=Order2 380=4 58=MissingDataException: Missing field. Type 50 10=070" 5 | 6 | import sys 7 | 8 | totalN = len(sys.argv) 9 | 10 | 11 | for i in range(1,totalN): 12 | print("Hey arguments passed by user", sys.argv[i]) 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ### Python Data Structure 3 | 4 | This repository will be really helpful, if you want to learn from the scratch in Python Programming Languages. Also, makes your strong in Basic Python. 5 | 6 | Here's the list of topics available to learn, 7 | 8 | * [Introduction (Basic information to learn Python and it's usability)] 9 | * [Dictionary] 10 | * [List] 11 | * [Tuple] 12 | * [Dictionary] 13 | * [Sets] 14 | * [Data collection types] 15 | * [Decorators] 16 | * [Excersises (Most of the puzzlea are from HackerRank/HackerEarth)] 17 | * [Itertools] 18 | * [Map] 19 | * [Lambda] 20 | * [OOP (Object Oriented Language)] 21 | * [Recursion] 22 | * [Strings] 23 | * [Search Techniques] 24 | * [Sorting] 25 | * [Queue] 26 | * [Zip] 27 | -------------------------------------------------------------------------------- /Recursion/RecursionTechniq.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | #calculating a sum of list of numbers. 4 | 5 | def sumOfList(inp): 6 | s = 0 7 | for i in inp: 8 | s = s +i 9 | print (s) 10 | return s 11 | 12 | #Recurssion methodology now 13 | # three LAWS OF RECURSSION 14 | # A recursive algorithm must have a base case. 15 | # A recursive algorithm must change its state and move toward the base case. 16 | # A recursive algorithm must call itself, recursively. 17 | 18 | 19 | def sumRec(inp): 20 | if len(inp) == 1: 21 | return 1 22 | else: 23 | return inp[0] + sumRec(inp[1:]) 24 | 25 | 26 | def listsum(numList): 27 | if len(numList) == 1: 28 | return numList[0] 29 | else: 30 | return numList[0] + listsum(numList[1:]) 31 | return numList 32 | 33 | if __name__ == '__main__': 34 | sumOfList([1,2,3,6,7,8,9,65,6]) 35 | sumRec([1,90,80,700]) # 3 RECURSSIVE CALLS WIL HAPPEN (TOTAL LENGTH - 1) 36 | listsum([1,90,80,700]) -------------------------------------------------------------------------------- /Recursion/TowersOfHanoi.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | 4 | def moveTower(height, fromPole, toPole, withPole): 5 | if height >= 1: 6 | moveTower(height-1, fromPole, withPole, toPole) 7 | moveDisk(fromPole,toPole) 8 | moveTower(height-1,withPole, toPole,fromPole ) 9 | 10 | 11 | def moveDisk(fp,tp): 12 | print ("moving disk from",fp,"to",tp) 13 | 14 | 15 | if __name__ == '__main__': 16 | moveTower(3,"A","B","C") -------------------------------------------------------------------------------- /Search Technique/BinarySearch.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | 4 | def binarySearch(alist, item): 5 | first = 0 6 | last = len(alist)-1 7 | found = False 8 | 9 | while first<=last and not found: 10 | midpoint = (first + last)//2 11 | if alist[midpoint] == item: 12 | found = True 13 | else: 14 | if item < alist[midpoint]: 15 | last = midpoint-1 16 | else: 17 | first = midpoint+1 18 | 19 | return found 20 | 21 | 22 | #2nd - Recursive binary search Method 23 | def binarySearch2(alist, item): 24 | if len(alist) == 0: 25 | return False 26 | else: 27 | midpoint = len(alist)//2 28 | if alist[midpoint]==item: 29 | return True 30 | else: 31 | if item item: 39 | stop = True 40 | else: 41 | pos = pos+1 42 | 43 | return found 44 | 45 | testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,] 46 | print(orderedSequentialSearch(testlist, 3)) 47 | print(orderedSequentialSearch(testlist, 13)) 48 | 49 | 50 | 51 | 52 | if __name__ == '__main__': 53 | s= [1,2,32,42,12,4,3,45,454] 54 | print(seqSearch(s,45)) 55 | 56 | testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0] 57 | print(sequentialSearch(testlist, 3)) 58 | print(sequentialSearch(testlist, 13)) 59 | -------------------------------------------------------------------------------- /Sets/Intro.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # 3 | # Input Format 4 | # 5 | # The first line contains the integer, NN, the total number of plants. 6 | # The second line contains the NN space separated heights of the plants. 7 | # 8 | # Constraints 9 | # 10 | # 0 B for B in [set(raw_input().split()) for _ in xrange(int(raw_input()))]]) for A in [set(raw_input().split())]][0] -------------------------------------------------------------------------------- /Sets/checkSubset.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # 3 | # You are given two sets, A 4 | # A 5 | # and B 6 | # B 7 | # . 8 | # Your job is to find whether set A 9 | # A 10 | # is a subset of set B 11 | # B 12 | # . 13 | # 14 | # If set A 15 | # A 16 | # is subset of set B 17 | # B 18 | # , print True. 19 | # If set A 20 | # A 21 | # is not a subset of set B 22 | # B 23 | # , print False. 24 | # 25 | # 26 | # Input Format 27 | # 28 | # 29 | # The first line will contain the number of test cases, T 30 | # T 31 | # . 32 | # The first line of each test case contains the number of elements in set A 33 | # A 34 | # . 35 | # The second line of each test case contains the space separated elements of set A 36 | # A 37 | # . 38 | # The third line of each test case contains the number of elements in set B 39 | # B 40 | # . 41 | # The fourth line of each test case contains the space separated elements of set B 42 | # B 43 | # . 44 | # 45 | # 46 | # Constraints 47 | # 48 | # 0alist[i+1]: 7 | temp = alist[i] 8 | alist[i] = alist[i+1] 9 | alist[i+1] = temp 10 | 11 | def bS(givenList): 12 | givListLen = len(givenList) - 1 13 | for i in range(givListLen): 14 | for j in range(givListLen - i): 15 | if givenList[j] > givenList[j+1]: 16 | givenList[j], givenList[j+1] = givenList[j+1], givenList[j] 17 | return givenList 18 | 19 | if __name__ == '__main__': 20 | alist = [54,26,93,17,77,31,44,55,20] 21 | bubbleSort(alist) 22 | print(alist) 23 | 24 | print(bS(alist)) -------------------------------------------------------------------------------- /Sort/InsertionSort.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | def insertionSort(alist): 4 | for index in range(1,len(alist)): 5 | 6 | currentvalue = alist[index] 7 | position = index 8 | 9 | while position>0 and alist[position-1]>currentvalue: 10 | alist[position]=alist[position-1] 11 | position = position-1 12 | 13 | alist[position]=currentvalue 14 | 15 | if __name__ == '__ main__': 16 | 17 | 18 | alist = [54,26,93,17,77,31,44,55,20] 19 | insertionSort(alist) 20 | print(alist) 21 | -------------------------------------------------------------------------------- /Sort/MergeSort.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # Merge sort is a very efficient sorting algorithm. 4 | # It’s based on the divide-and-conquer approach, a powerful algorithmic technique used to solve complex problems. 5 | 6 | def mergeSort(alist): 7 | print("Splitting ",alist) 8 | if len(alist)>1: 9 | mid = len(alist)//2 10 | lefthalf = alist[:mid] 11 | righthalf = alist[mid:] 12 | 13 | mergeSort(lefthalf) 14 | mergeSort(righthalf) 15 | 16 | i=0 17 | j=0 18 | k=0 19 | while i < len(lefthalf) and j < len(righthalf): 20 | if lefthalf[i] < righthalf[j]: 21 | alist[k]=lefthalf[i] 22 | i=i+1 23 | else: 24 | alist[k]=righthalf[j] 25 | j=j+1 26 | k=k+1 27 | 28 | while i < len(lefthalf): 29 | alist[k]=lefthalf[i] 30 | i=i+1 31 | k=k+1 32 | 33 | while j < len(righthalf): 34 | alist[k]=righthalf[j] 35 | j=j+1 36 | k=k+1 37 | print("Merging ",alist) 38 | 39 | if __name__ == '__main__': 40 | 41 | alist = [54,26,93,17,77,31,44,55,20] 42 | mergeSort(alist) 43 | print(alist) 44 | -------------------------------------------------------------------------------- /Sort/QuickSort.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | def quickSort(alist): 4 | quickSortHelper(alist,0,len(alist)-1) 5 | 6 | def quickSortHelper(alist,first,last): 7 | if first= pivotvalue and rightmark >= leftmark: 28 | rightmark = rightmark -1 29 | 30 | if rightmark < leftmark: 31 | done = True 32 | else: 33 | temp = alist[leftmark] 34 | alist[leftmark] = alist[rightmark] 35 | alist[rightmark] = temp 36 | 37 | temp = alist[first] 38 | alist[first] = alist[rightmark] 39 | alist[rightmark] = temp 40 | 41 | 42 | return rightmark 43 | 44 | if __name__ == '__main__': 45 | alist = [54,26,93,17,77,31,44,55,20] 46 | quickSort(alist) 47 | print(alist) 48 | -------------------------------------------------------------------------------- /Strings/Capitalize.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # You are given a string SS. Your task is to capitalize each word of SS. 4 | # 5 | # Input Format 6 | # 7 | # A single line of input containing the string, SS. 8 | # 9 | # Constraints 10 | # 11 | # 0 stusc: 62 | print ("Kevin", kevsc) 63 | elif kevsc < stusc: 64 | print ("Stuart", stusc) 65 | else: 66 | print ("Draw") -------------------------------------------------------------------------------- /Strings/Mutations.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # Task 4 | # Read a given string, change the character at a given index and then print the modified string. 5 | # 6 | # Input Format 7 | # The first line contains a string, SS. 8 | # The next line contains an integer ii, denoting the index location and a character cc separated by a space. 9 | # 10 | # Output Format 11 | # Using any of the methods explained above, replace the character at index ii with character cc. 12 | # 13 | # Sample Input 14 | # 15 | # abracadabra 16 | # 5 k 17 | # Sample Output 18 | # 19 | # abrackdabra 20 | 21 | 22 | userInput = input() 23 | index, stringTobeReplaced = input().split(" ") 24 | 25 | l = list(userInput) 26 | l[int(index)] = stringTobeReplaced 27 | userInput = ''.join(l) 28 | print (userInput) 29 | 30 | -------------------------------------------------------------------------------- /Strings/StringFormatting.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # 3 | # Read the integer, NN and print the decimal, octal, hexadecimal, and binary values from 11 to NN with space padding so that all fields take the same width as the binary value. 4 | # 5 | # Input Format 6 | # The first line contains an integer, NN. 7 | # 8 | # Constraints 9 | # 1?N?991?N?99 10 | # Output Format 11 | # Print NN lines. Format the fields as the width of the binary value of NN. 12 | # 13 | # Sample Input 14 | # 15 | # 17 16 | # Sample Output 17 | # 18 | # 1 1 1 1 19 | # 2 2 2 10 20 | # 3 3 3 11 21 | # 4 4 4 100 22 | # 5 5 5 101 23 | # 6 6 6 110 24 | # 7 7 7 111 25 | # 8 10 8 1000 26 | # 9 11 9 1001 27 | # 10 12 A 1010 28 | # 11 13 B 1011 29 | # 12 14 C 1100 30 | # 13 15 D 1101 31 | # 14 16 E 1110 32 | # 15 17 F 1111 33 | # 16 20 10 10000 34 | # 17 21 11 10001 35 | 36 | 37 | n = int(input()) 38 | width = len("{0:b}".format(n)) 39 | for i in range(1,n+1): 40 | print ("{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format(i, width=width)) -------------------------------------------------------------------------------- /Strings/StringSplitAndJoin.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | 4 | # In Python, a string can be split on a delimiter. 5 | # 6 | # Example: 7 | # 8 | # >>> a = "this is a string" 9 | # >>> a = a.split(" ") # a is converted to a list of strings. 10 | # >>> print a 11 | # ['this', 'is', 'a', 'string'] 12 | # Joining a string is simple: 13 | # 14 | # >>> a = "-".join(a) 15 | # >>> print a 16 | # this-is-a-string 17 | # Task 18 | # You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen. 19 | # 20 | # Input Format 21 | # The first line contains a string consisting of space separated words. 22 | # 23 | # Output Format 24 | # Print the formatted string as explained above. 25 | # 26 | # Sample Input 27 | # 28 | # this is a string 29 | # Sample Output 30 | # 31 | # this-is-a-string 32 | 33 | userInput = input() 34 | # solution 1: 35 | print (userInput.replace(" ", "-")) 36 | # Solution 2: 37 | print ("-".join(userInput.split())) -------------------------------------------------------------------------------- /Strings/StringValidators.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # Task 3 | # 4 | # You are given a string SS. 5 | # Your task is to find out if the string SS contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters. 6 | # 7 | # Input Format 8 | # 9 | # A single line containing a string SS. 10 | # 11 | # Constraints 12 | # 13 | # 0 len(list2): 65 | # for i in list(range(0, len(list2))): 66 | # print(str(list1[i]) + list2[i]) 67 | # opList.append(str(list1[i]) + list2[i]) 68 | 69 | # diff = (len(list1) - len(list2) - 1) 70 | # for i in list1[diff:]: 71 | # opList.append(list1[i]) 72 | 73 | # print(opList) 74 | 75 | 76 | 77 | # op = [(1, 'Hello'), (2, 'World'), (3, None), (4, None)] 78 | # op_2 = [(None, 'Hello'), (None, 'World'), (1, 'Hello'), (2, 'World')] 79 | 80 | # finalOp = [] 81 | 82 | # for i in op: 83 | # firstEle = "" if i[0] == None else i[0] 84 | # secEle = "" if i[1] == None else i[1] 85 | # finalOp.append(str(firstEle) + secEle) 86 | 87 | # print(finalOp) 88 | -------------------------------------------------------------------------------- /itertools/what.py: -------------------------------------------------------------------------------- 1 | from itertools import repeat 2 | lots_of_fours = repeat(4, times=100000) 3 | 4 | print(lots_of_fours) 5 | 6 | print(type(lots_of_fours)) 7 | 8 | # print(list(lots_of_fours)) 9 | 10 | # This iterator takes up 56 bytes of memory on my machine: 11 | 12 | import sys 13 | sys.getsizeof(lots_of_fours) 14 | # 56 15 | # An equivalent list of 100 million 4’s takes up many megabytes of memory: 16 | 17 | lots_of_fours = [4] * 100_000_000 18 | import sys 19 | sys.getsizeof(lots_of_fours) 20 | 21 | # 800000064 22 | # While iterators can save memory, they can also save time. For example if you wanted to print out just the first line of a 10 gigabyte log file, you could do this: 23 | 24 | print(next(open('giant_log_file.txt'))) 25 | # This is the first line in a giant file 26 | # File objects in Python are implemented as iterators. As you loop over a file, data is read into memory one line at a time. If we instead used the readlines method to store all lines in memory, we might run out of system memory. 27 | 28 | # So iterators can save us memory, but iterators can sometimes save us time also. 29 | 30 | # Additionally, iterators have abilities that other iterables don’t. For example, the laziness of iterables can be used to make iterables that have an unknown length. In fact, you can even make infinitely long iterators. -------------------------------------------------------------------------------- /test.json: -------------------------------------------------------------------------------- 1 | {"course": "python", "topic": "Python JSON"} 2 | {"course": "python", "topic": "Python JSON"} 3 | {"course": "python", "topic": "Python JSON"} 4 | {"course": "python", "topic": "Python JSON"} 5 | --------------------------------------------------------------------------------