├── Filter ├── __init__.py └── WhatIsFilter.py ├── Map └── __init__.py ├── OOP ├── __init__.py ├── Others │ ├── MapFilterReduceLamba.py │ ├── AnonymousFunction │ │ ├── __init__.py │ │ └── MapFilterReduceLamba.py │ ├── ExceptionalHandling │ │ ├── __init__.py │ │ ├── TryExcept.py │ │ └── CustomException.py │ ├── FileHandling │ │ ├── input.txt │ │ ├── ram.txt │ │ ├── input1.txt │ │ ├── readLog.py │ │ └── FileReadingWriting.py │ └── Decorators │ │ ├── decorators.py │ │ └── DecoratorsExample.py ├── AbstractExample │ └── BaseAbstractClass │ │ ├── ABC.py │ │ └── DerivedClass.py ├── Inheritance │ ├── HierarchicalInheritance.py │ ├── MultilevelInheritance.py │ ├── SingleInheritance.py │ └── HybridInheritance.py ├── Polymorphism │ ├── SuperMethod.py │ ├── MethodOverloading_NotEfficient.py │ ├── MethodOverloading.py │ └── MethodOverriding.py └── Encapsulation │ └── Data Abstraction.py ├── Zip ├── __init__.py └── HowToUnzip.py ├── Classes ├── composition.py ├── decorators.py ├── inheritance.py ├── special_class_methods.py ├── globalVariables.py ├── state.py └── session-on-class.py ├── Decorators └── __init__.py ├── FruitStore ├── __init__.py ├── userMenu.txt ├── __pycache__ │ ├── log.cpython-37.pyc │ ├── Bill.cpython-37.pyc │ ├── FStore.cpython-37.pyc │ └── UserHandler.cpython-37.pyc ├── Bill.py ├── log.py ├── stock.json └── scoring.py ├── Generators ├── __init__.py ├── LotteryExample.py ├── basicGenerators.py └── DiffBtwnGenratorsAndIterator.py ├── HashTable ├── __init__.py └── 1. Implementation_Tutorial.py ├── Paramiko ├── __init__.py └── paramiko.py ├── QDataStructure ├── __init__.py ├── RenamingAFile.py └── Deque_Implementation.py ├── Sets ├── permutations.py ├── itertools.py ├── Intro.py ├── Set.add().py ├── intersection.py ├── checkStrictSubset.py ├── NoIdea.py ├── symettricDifference.py └── checkSubset.py ├── .gitignore ├── .vscode ├── settings.json ├── extensions.json └── launch.json ├── .DS_Store ├── input1.txt ├── QR ├── HelloWorldQR.png ├── HelloWorldQR.py └── QR_Encode.py ├── DataStructures ├── test │ └── test.cs ├── LinkedList │ ├── LinkedList.png │ └── LinkedList_Implementation.py ├── FB │ ├── EditApart.py │ └── Spiral.py └── Stack │ └── Stack_Implementation.py ├── Cryptography ├── __pycache__ │ └── rsa.cpython-37.pyc ├── rsa.py └── test.py ├── ExceptionalHandling ├── __pycache__ │ ├── two.cpython-37.pyc │ └── three.cpython-37.pyc ├── three.py ├── two.py ├── one.py ├── test.py └── EHFinally.py ├── Excersise ├── HelloWorld.py ├── Min-MaxSum.py ├── youtubeDownload.py ├── StairCase.py ├── DiscoverMonk.py ├── CheckingInternetIsWorking.py ├── TrailingZero.py ├── FindNextGreaterElement.py ├── checkPalindrome.py ├── LargestPrimeNumber.py ├── usingNumpy.py ├── CompareTriplets.py ├── Factorial.py ├── PlusMinus.py ├── CheckingStringPalindromeOrNot.py ├── UniqueMaximumNumber.py ├── first-M-MultiplesOfN ├── EvenTree.py ├── toSwathi.py ├── python_encryption.py ├── PalindromeChecker.py ├── SecondHighestNumber.py ├── RemoveDuplicateStrings.py ├── 24HourTimeFormat.py ├── FindingTraceInBreadthFirstSearch.py ├── FolderSizeOfDirectory.py ├── GoldRate │ └── Todo.txt ├── ListAddition.py ├── EvenOrOddWithoutUsingModDiv.py ├── ConvertDecimalToBinary.py ├── Fraction.py ├── PrimNumFromList.py ├── SherlockSquares.py ├── MostCommon.py ├── DiagonalSum.py ├── WordOrder.py ├── FindDigits.py ├── ConverFloatToDecimal.py ├── ConverFloatPointNumberToDecimal.py ├── DynamicProgramming.py ├── TrendingLaptopBrands.py ├── EvenNumEvenIndex_42.py ├── OrderedDictionary.py ├── Hashing.py ├── FindingNumbers.py ├── NaviBeer.py ├── LibraryFineCollections.py ├── namedtuple.py └── fibonacci.py ├── test.json ├── RE └── trail.py ├── DataCollectionTypes ├── List │ ├── FindCommonElements.py │ ├── 3. ListComprehension.py │ ├── MoveAllZerosToEnd.py │ ├── 5. NestedList.py │ ├── 7. OrderedList.py │ ├── 8. MostRepeatedElementsInList.py │ ├── 4. ListTutorial.py │ └── 6. CombiningAllInnerListIntoOneList.py ├── Dictionary │ ├── Tutorials_1.py │ ├── Task2.py │ ├── to_delete_in_future_sample.py │ └── Task1.py ├── Sets │ ├── 2. SymettricDifference.py │ └── Excercise │ │ ├── unionOperation.py │ │ └── difference.py └── Tuples │ └── Tuples.py ├── MultiTasking ├── MultiProcessing.py ├── Synchronous.py └── Asynchronous.py ├── Recursion ├── TowersOfHanoi.py └── RecursionTechniq.py ├── Strings ├── CompareTwoStrings.py ├── Capitalize.py ├── TextWrap.py ├── SwapCases.py ├── Mutations.py ├── StringSplitAndJoin.py ├── FindAString.py ├── StringFormatting.py ├── StringValidators.py ├── MinionGame.py └── DesignerDoorMat.py ├── Sort ├── InsertionSort.py ├── BubbleSort.py ├── MergeSort.py └── QuickSort.py ├── itertools ├── Triplets.py ├── what.py └── itertools_product.py ├── README.md ├── MathOperationAndLoops ├── Mod Power.py ├── PerformingDivision.py ├── Mod Divmod.py ├── IntegerAllSizes.py ├── getInputFromUser.py ├── BaiscForLoop.py ├── Number Swaping.py ├── ArithmeticOperators.py └── PrintSpeciality.py ├── Lambda ├── timecomplexity.py └── WhatIsLambda.py ├── DynamicProgramming ├── rapdiFibonacci.py ├── abbrevation.py ├── factorial.py └── __init__.py ├── Search Technique ├── BinarySearch.py └── SequentialSearch.py └── ArgsKwArgs └── KwArgs.py /Filter/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Map/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /OOP/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Zip/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Classes/composition.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Classes/decorators.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Classes/inheritance.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Decorators/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /FruitStore/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /FruitStore/userMenu.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Generators/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /HashTable/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Paramiko/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /QDataStructure/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Classes/special_class_methods.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /QDataStructure/RenamingAFile.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /OOP/Others/MapFilterReduceLamba.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /OOP/Others/AnonymousFunction/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /OOP/Others/ExceptionalHandling/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Sets/permutations.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | .gitignore 3 | .idea/ 4 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "C:\\Python37\\python.exe" 3 | } -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/HEAD/.DS_Store -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "github.copilot" 4 | ] 5 | } -------------------------------------------------------------------------------- /input1.txt: -------------------------------------------------------------------------------- 1 | Keys Values 2 | h e 3 | f r 4 | t ['w', 'x'] 5 | P ['d', 'c'] 6 | l q 7 | -------------------------------------------------------------------------------- /QR/HelloWorldQR.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/HEAD/QR/HelloWorldQR.png -------------------------------------------------------------------------------- /DataStructures/test/test.cs: -------------------------------------------------------------------------------- 1 | // write a hello world program 2 | 3 | // console.log("Hello") 4 | console.writeLine("hhhh") -------------------------------------------------------------------------------- /QR/HelloWorldQR.py: -------------------------------------------------------------------------------- 1 | import pyqrcode 2 | 3 | img = pyqrcode.create("Hello World") 4 | 5 | img.png("HelloWorldQR.png", scale=6) 6 | 7 | -------------------------------------------------------------------------------- /DataStructures/LinkedList/LinkedList.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/HEAD/DataStructures/LinkedList/LinkedList.png -------------------------------------------------------------------------------- /FruitStore/__pycache__/log.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/HEAD/FruitStore/__pycache__/log.cpython-37.pyc -------------------------------------------------------------------------------- /Cryptography/__pycache__/rsa.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/HEAD/Cryptography/__pycache__/rsa.cpython-37.pyc -------------------------------------------------------------------------------- /FruitStore/__pycache__/Bill.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/HEAD/FruitStore/__pycache__/Bill.cpython-37.pyc -------------------------------------------------------------------------------- /FruitStore/__pycache__/FStore.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/HEAD/FruitStore/__pycache__/FStore.cpython-37.pyc -------------------------------------------------------------------------------- /ExceptionalHandling/__pycache__/two.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/HEAD/ExceptionalHandling/__pycache__/two.cpython-37.pyc -------------------------------------------------------------------------------- /FruitStore/__pycache__/UserHandler.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/HEAD/FruitStore/__pycache__/UserHandler.cpython-37.pyc -------------------------------------------------------------------------------- /ExceptionalHandling/__pycache__/three.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanjaypradeep/Python-Data-Structure/HEAD/ExceptionalHandling/__pycache__/three.cpython-37.pyc -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /Sets/itertools.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # a=map(int,raw_input().split(" ")) 4 | # b=map(int,raw_input().split(" ")) 5 | from itertools import product 6 | a = [1,2] 7 | b = [3,4] 8 | s= tuple(product(a, b)) 9 | for i in list(product(a, b)): 10 | print(i, end="") 11 | -------------------------------------------------------------------------------- /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/youtubeDownload.py: -------------------------------------------------------------------------------- 1 | # make sure you have PyTube library 2 | # If not, then install via pip 3 | # pip install pytube 4 | # once installation is successfull, you can run this code and enjoy. 5 | 6 | from pytube import YouTube 7 | 8 | YouTube('https://www.youtube.com/watch?v=ID_OF_THE_VIDEO').streams.first().download() 9 | -------------------------------------------------------------------------------- /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 ) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /FruitStore/Bill.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class BillFormatter: 4 | 5 | def __init__(self, billMap): 6 | self.billObj = billMap 7 | 8 | def generateBill(self): 9 | for fruitName, price in self.billObj.items(): 10 | print(fruitName + " - " + str(price)) 11 | 12 | print("Total Bill amount to pay " + str(sum(self.billObj.values())) + " Rupees \n") -------------------------------------------------------------------------------- /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]) -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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") -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /Strings/CompareTwoStrings.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | def compareTwoStrings(s1,s2): 4 | if s1 and s2 is not '': 5 | x = list(s1) 6 | y = list(s2) 7 | x.sort() 8 | y.sort() 9 | print (x,y) 10 | if s1 == s2: 11 | print("both strings are equal") 12 | else: 13 | print("its wrong") 14 | else: 15 | raise RuntimeError("something went bad") 16 | 17 | if __name__ == '__main__': 18 | compareTwoStrings("abcde","edcba") 19 | -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /FruitStore/log.py: -------------------------------------------------------------------------------- 1 | import logging 2 | logging.basicConfig(filename="GLOBAL_LOG.log", 3 | format='%(asctime)s %(message)s', 4 | datefmt='%m/%d/%Y %I:%M:%S %p') 5 | class Log: 6 | 7 | def registerInfo(msg): 8 | logging.info(msg) 9 | 10 | def registerWarning(warningMsg): 11 | logging.warning(warningMsg) 12 | 13 | def registerError(errorMsg): 14 | logging.error(errorMsg) 15 | 16 | def registerCritical(criticalMsg): 17 | logging.critical(criticalMsg) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 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") -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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= 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) -------------------------------------------------------------------------------- /Strings/TextWrap.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | 4 | # Task 5 | # 6 | # You are given a string SS and width ww. 7 | # Your task is to wrap the string into a paragraph of width ww. 8 | # 9 | # Input Format 10 | # 11 | # The first line contains a string, SS. 12 | # The second line contains the width, ww. 13 | # 14 | # Constraints 15 | # 16 | # 00] 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/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 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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") -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /MathOperationAndLoops/Mod Power.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # Task 4 | # You are given three integers: aa, bb, and mm, respectively. Print two lines. 5 | # The first line should print the result of pow(a,b). The second line should print the result of pow(a,b,m). 6 | # 7 | # Input Format 8 | # The first line contains aa, the second line contains bb, and the third line contains mm. 9 | # 10 | # Constraints 11 | # 1?a?101?a?10 12 | # 1?b?101?b?10 13 | # 2?m?10002?m?1000 14 | # 15 | # Sample Input 16 | # 17 | # 3 18 | # 4 19 | # 5 20 | # Sample Output 21 | # 22 | # 81 23 | # 1 24 | from __future__ import division 25 | 26 | a = int(raw_input()) 27 | b = int(raw_input()) 28 | m = int(raw_input()) 29 | 30 | t = pow(a,b) 31 | 32 | print t 33 | print t % m -------------------------------------------------------------------------------- /Sort/BubbleSort.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | def bubbleSort(alist): 4 | for passnum in range(len(alist)-1,0,-1): 5 | for i in range(passnum): 6 | if alist[i]>alist[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)) -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /Strings/SwapCases.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # You are given a string SS. Your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa. 3 | # 4 | # For Example: 5 | # 6 | # Www.HackerRank.com ? wWW.hACKERrANK.COM 7 | # Pythonist 2 ? pYTHONIST 2 8 | # Input Format 9 | # 10 | # A single line containing a string SS. 11 | # 12 | # Constraints 13 | # 14 | # 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 | -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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())) -------------------------------------------------------------------------------- /FruitStore/scoring.py: -------------------------------------------------------------------------------- 1 | # if __name__ == '__main__': 2 | # n = int(input()) 3 | # student_marks = {} 4 | # for _ in range(n): 5 | # name, *line = input().split() 6 | # scores = list(map(float, line)) 7 | # student_marks[name] = scores 8 | # query_name = input() 9 | # # what if query name value doesn't exist in student_marks? 10 | 11 | # if query_name in student_marks.keys(): 12 | # studentScore = student_marks[query_name] 13 | # print(sum(studentScore)/ len(studentScore)) 14 | # else: 15 | # print("student name not exist") 16 | 17 | 18 | import textwrap 19 | 20 | def wrap(string, max_width): 21 | emptyList= [] 22 | for i in range(0,len(string),max_width): 23 | emptyList.append(string[i:i+max_width]) 24 | return "\n".join(emptyList) 25 | 26 | if __name__ == '__main__': 27 | string, max_width = input(), int(input()) 28 | result = wrap(string, max_width) 29 | print(result) -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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)}") -------------------------------------------------------------------------------- /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]) -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /Strings/FindAString.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left. 4 | # 5 | # NOTE: String letters are case-sensitive. 6 | # 7 | # Input Format 8 | # 9 | # The first line of input contains the original string. The next line contains the substring. 10 | # 11 | # Constraints 12 | # 13 | # 1?len(string)?2001?len(string)?200 14 | # Each character in the string is an ascii character. 15 | # 16 | # Output Format 17 | # 18 | # Output the integer number indicating the total number of occurrences of the substring in the original string. 19 | # 20 | # Sample Input 21 | # 22 | # ABCDCDC 23 | # CDC 24 | # Sample Output 25 | # 26 | # 2 27 | 28 | line, target = [raw_input() for _ in range(2)] 29 | score = 0 30 | for i in range(len(line)): 31 | if line[i:i+len(target)] == target: 32 | score += 1 33 | print score -------------------------------------------------------------------------------- /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/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/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) -------------------------------------------------------------------------------- /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/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() -------------------------------------------------------------------------------- /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)) -------------------------------------------------------------------------------- /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__) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 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 | -------------------------------------------------------------------------------- /Sets/Set.add().py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # 4 | # Task 5 | # 6 | # Apply your knowledge of the .add() operation to help your friend Rupal. 7 | # 8 | # Rupal has a huge collection of country stamps. She decided to count the total number of distinct country stamps in her collection. She asked for your help. You pick the stamps one by one from a stack of NN country stamps. 9 | # 10 | # Find the total number of distinct country stamps. 11 | # 12 | # Input Format 13 | # 14 | # The first line contains an integer NN, the total number of country stamps. 15 | # The next NN lines contains the countrey's name where the stamp is from. 16 | # Constraints 17 | # 18 | # 0 len(b): 32 | genericCheck(a,b) 33 | elif(len(b) > len(a)): 34 | genericCheck(a,b) 35 | else: 36 | ListAdditionOutputWithCommaSeparated(a,b) -------------------------------------------------------------------------------- /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)) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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!") -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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)) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Lambda/WhatIsLambda.py: -------------------------------------------------------------------------------- 1 | """ 2 | What is a lambda function in Python? 3 | 4 | A lambda function is a small anonymous function defined with the 'lambda' keyword. 5 | It can take any number of arguments but can only have one expression. 6 | 7 | Syntax: 8 | lambda arguments: expression 9 | """ 10 | 11 | # Example 1: Basic lambda function 12 | add = lambda x, y: x + y 13 | print("add(2, 3):", add(2, 3)) # Output: 5 14 | 15 | # Example 2: Lambda with map 16 | numbers = [1, 2, 3, 4] 17 | squared = list(map(lambda x: x ** 2, numbers)) 18 | print("Squared numbers:", squared) # Output: [1, 4, 9, 16] 19 | 20 | # Example 3: Lambda with filter 21 | evens = list(filter(lambda x: x % 2 == 0, numbers)) 22 | print("Even numbers:", evens) # Output: [2, 4] 23 | 24 | # Example 4: Lambda with sorted 25 | pairs = [(2, 3), (1, 4), (5, 0)] 26 | sorted_pairs = sorted(pairs, key=lambda pair: pair[1]) 27 | print("Pairs sorted by second element:", sorted_pairs) # Output: [(5, 0), (2, 3), (1, 4)] 28 | 29 | # Comparison: Regular function vs lambda 30 | def multiply(x, y): 31 | return x * y 32 | 33 | multiply_lambda = lambda x, y: x * y 34 | 35 | print("multiply(3, 4):", multiply(3, 4)) # Output: 12 36 | print("multiply_lambda(3, 4):", multiply_lambda(3, 4)) # Output: 12 37 | 38 | # Note: Lambda functions are best for short, simple operations. -------------------------------------------------------------------------------- /DataCollectionTypes/Tuples/Tuples.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # Tuples are data structures that look a lot like lists. Unlike lists, tuples are immutable (meaning that they cannot be modified once created). This restricts their use because we cannot add, remove, or assign values; however, it gives us an advantage in space and time complexities. 4 | # 5 | # A common tuple use is the swapping of 22 numbers: 6 | # 7 | # a,b = b,a 8 | # Here a,ba,b is a tuple, and it assigns itself the values of b,ab,a. 9 | # 10 | # Another awesome use of tuples is as keys in a dictionary. In other words, tuples are hashable. 11 | # 12 | # Task 13 | # You are given an integer, NN, on a single line. The next line contains NN space-separated integers. Create a tuple, TT, of those NN integers, then compute and print the result of hash(TT). 14 | # 15 | # Note: hash() is one of the functions in the __builtins__ module. 16 | # 17 | # Input Format 18 | # 19 | # The first line contains an integer, NN (the number of elements in the tuple). 20 | # The second line contains NN space-separated integers describing TT. 21 | # 22 | # Output Format 23 | # 24 | # Print the result of hash(TT). 25 | # 26 | # Sample Input 27 | # 28 | # 2 29 | # 1 2 30 | # Sample Output 31 | # 32 | # 3713081631934410656 33 | 34 | input() 35 | print (hash(tuple(map(int, raw_input().strip().split(" "))))) 36 | -------------------------------------------------------------------------------- /Generators/LotteryExample.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # How to create a generator in Python? 4 | # It is fairly simple to create a generator in Python. It is as easy as defining a normal function with 5 | # yield statement instead of a return statement. 6 | # 7 | # If a function contains at least one yield statement (it may contain other yield or return statements), 8 | # it becomes a generator function. Both yield and return will return some value from a function. 9 | # 10 | # The difference is that, while a return statement terminates a function entirely, yield statement pauses the function 11 | # saving all its states and later continues from there on successive calls. 12 | # 13 | 14 | import random 15 | import time 16 | 17 | def lottery(): 18 | # returns 6 numbers between 1 and 40 19 | for i in range(6): 20 | yield random.randint(1, 40) #bascially yield always returns the value. 21 | 22 | # returns a 7th number between 1 and 15 23 | time.sleep(10) 24 | yield random.randint(100,110) #after completing the above iterations, pointer comes here, yeilds returns the value from random.randint(1,15) 25 | 26 | print (lottery()) #this really prints the generator object id 27 | 28 | # if you want to get all Lottery() values, iterate it. 29 | 30 | for random_number in lottery(): 31 | print("And the next number is... %d!" %(random_number)) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /MathOperationAndLoops/Number Swaping.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # /* 3 | # You are given two integers. Store them into two variables and then exchange them. Rather than using any fancy logic, make sure to use a tuple to do the task. Print the two numbers. 4 | # 5 | # Input Format 6 | # 7 | # Two integers on separate lines. 8 | # 9 | # Output Format 10 | # 11 | # Two integers on separate lines. 12 | # 13 | # Sample Input 14 | # 15 | # 2 16 | # 1 17 | # Sample Output 18 | # 19 | # 1 20 | # 2 21 | # Concept 22 | # 23 | # A tuple is similar to a list. However, a tuple is immutable. It cannot be changed. Once you assign some value to a tuple, it cannot be changed. Also, no additional members can be added once a tuple is assigned. 24 | # 25 | # For example: 26 | # >> 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 | -------------------------------------------------------------------------------- /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 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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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/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 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")) -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /Search Technique/SequentialSearch.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | 4 | def seqSearch(aList, item): 5 | pos =0 6 | found = False 7 | 8 | while pos 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 | -------------------------------------------------------------------------------- /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/__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 | """ -------------------------------------------------------------------------------- /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 | ''' -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Sets/intersection.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | # 3 | # Task 4 | # 5 | # 6 | # The students of District College have subscriptions to English and French newspapers. Some students have subscribed only to English, some have subscribed only to French, and some have subscribed to both newspapers. 7 | # 8 | # You are given two sets of student roll numbers. One set has subscribed to the English newspaper, one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to both newspapers. 9 | # 10 | # 11 | # Input Format 12 | # 13 | # 14 | # The first line contains n 15 | # n 16 | # , the number of students who have subscribed to the English newspaper. 17 | # The second line contains n 18 | # n 19 | # space separated roll numbers of those students. 20 | # The third line contains b 21 | # b 22 | # , the number of students who have subscribed to the French newspaper. 23 | # The fourth line contains b 24 | # b 25 | # space separated roll numbers of those students. 26 | # 27 | # Constraints 28 | # 29 | # 0 B for B in [set(raw_input().split()) for _ in xrange(int(raw_input()))]]) for A in [set(raw_input().split())]][0] -------------------------------------------------------------------------------- /Zip/HowToUnzip.py: -------------------------------------------------------------------------------- 1 | # How to unzip? 2 | # Unzipping means converting the zipped values back to the individual self as they were. This is done with the help of “*” operator 3 | 4 | # Python code to demonstrate the working of 5 | # unzip 6 | 7 | # initializing lists 8 | 9 | name = ["Manjeet", "Nikhil", "Shambhavi", "Astha"] 10 | roll_no = [4, 1, 3, 2] 11 | marks = [40, 50, 60, 70] 12 | 13 | # using zip() to map values 14 | mapped = zip(name, roll_no, marks) 15 | 16 | # converting values to print as list 17 | mapped = list(mapped) 18 | 19 | # printing resultant values 20 | print("The zipped result is : ", mapped) 21 | 22 | 23 | # =====================================Unzipping=============================================== 24 | 25 | # it's not but getting the values from object, 26 | 27 | namz, roll_noz, marksz = zip(*mapped) 28 | 29 | print("The unzipped result: \n", end="") 30 | 31 | # printing initial lists 32 | print("The name list is : ", namz) 33 | 34 | print("The roll_no list is : ", roll_noz) 35 | 36 | print("The marks list is : ",marksz) 37 | 38 | # Practical Applications: There aremany possible applications that can be said to be exected using zip, 39 | # be it student database or scorecard or any other utility that requires mapping of groups.A small example of scorecard is 40 | # demonstrated below. 41 | 42 | # Python code to demonstrate the application of 43 | # zip() 44 | 45 | # initializing list of players. 46 | players = ["Sachin", "Sehwag", "Gambhir", "Dravid", "Raina"] 47 | 48 | # initializing their scores 49 | scores = [100, 15, 17, 28, 43] 50 | 51 | # printing players and scores. 52 | for pl, sc in zip(players, scores): 53 | print("Player : %s Score : %d" % (pl, sc)) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Sets/NoIdea.py: -------------------------------------------------------------------------------- 1 | # There is an array of nn integers. There are also 22 disjoint sets, AA and BB, each containing mm integers. You like all the integers in set AA and dislike all the integers in set BB. Your initial happiness is 00. For each ii integer in the array, if i?Ai?A, you add 11 to your happiness. If i?Bi?B, you add ?1?1 to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end. 2 | # 3 | # Note: Since AA and BB are sets, they have no repeated elements. However, the array might contain duplicate elements. 4 | # 5 | # Constraints 6 | # 1?n?1051?n?105 7 | # 1?m?1051?m?105 8 | # 1?Any integer in the input?1091?Any integer in the input?109 9 | # 10 | # Input Format 11 | # 12 | # The first line contains integers nn and mm separated by a space. 13 | # The second line contains nn integers, the elements of the array. 14 | # The third and fourth lines contain mm integers, AA and BB, respectively. 15 | # 16 | # Output Format 17 | # 18 | # Output a single integer, your total happiness. 19 | # 20 | # Sample Input 21 | # 22 | # 3 2 23 | # 1 5 3 24 | # 3 1 25 | # 5 7 26 | # Sample Output 27 | # 28 | # 1 29 | # Explanation 30 | # 31 | # You gain 11 unit of happiness for elements 33 and 11 in set AA. You lose 11 unit for 55 in set BB. The element 77 in set BB does not exist in the array so it is not included in the calculation. 32 | # 33 | # Hence, the total happiness is 2?1=12?1=1. 34 | 35 | # Enter your code here. Read input from STDIN. Print output to STDOUT 36 | a= raw_input() == "" or list(map(int, raw_input().split())) 37 | b = set(map(int, raw_input().split())) 38 | c = set(map(int, raw_input().split())) 39 | print sum([1 if x in b else 0 for x in a]) - sum([1 if x in c else 0 for x in a]) -------------------------------------------------------------------------------- /Strings/MinionGame.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # Kevin and Stuart want to play the 'The Minion Game'. 4 | # 5 | # Game Rules 6 | # 7 | # Both players are given the same string, SS. 8 | # Both players have to make substrings using the letters of the string SS. 9 | # Stuart has to make words starting with consonants. 10 | # Kevin has to make words starting with vowels. 11 | # The game ends when both players have made all possible substrings. 12 | # 13 | # Scoring 14 | # A player gets +1 point for each occurrence of the substring in the string SS. 15 | # 16 | # For Example: 17 | # String SS = BANANA 18 | # Kevin's vowel beginning word = ANA 19 | # Here, ANA occurs twice in BANANA. Hence, Kevin will get 2 Points. 20 | # 21 | # For better understanding, see the image below: 22 | # 23 | # banana.png 24 | # 25 | # Your task is to determine the winner of the game and their score. 26 | # 27 | # Input Format 28 | # 29 | # A single line of input containing the string SS. 30 | # Note: The string SS will contain only uppercase letters: [A?Z][A?Z]. 31 | # 32 | # Constraints 33 | # 34 | # 0 stusc: 62 | print ("Kevin", kevsc) 63 | elif kevsc < stusc: 64 | print ("Stuart", stusc) 65 | else: 66 | print ("Draw") -------------------------------------------------------------------------------- /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") -------------------------------------------------------------------------------- /DataCollectionTypes/Sets/Excercise/unionOperation.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # Task 4 | # The students of District College have subscriptions to English and French newspapers. Some students have subscribed only to English, some have subscribed to only French and some have subscribed to both newspapers. 5 | # 6 | # You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and the other set is subscribed to the French newspaper. The same student could be in both sets. Your task is to find the total number of students who have subscribed to at least one newspaper. 7 | # 8 | # Input Format 9 | # 10 | # The first line contains an integer, nn, the number of students who have subscribed to the English newspaper. 11 | # The second line contains nn space separated roll numbers of those students. 12 | # The third line contains bb, the number of students who have subscribed to the French newspaper. 13 | # The fourth line contains bb space separated roll numbers of those students. 14 | # 15 | # Constraints 16 | # 17 | # 0 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/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)) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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()) -------------------------------------------------------------------------------- /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 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/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 | -------------------------------------------------------------------------------- /Sets/symettricDifference.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | # 4 | # Task 5 | # 6 | # 7 | # Students of District College have subscriptions to English and French newspapers. Some students have subscribed to English only, some have subscribed to French only, 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 either the English or the French newspaper but not both. 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 35 | 36 | # if you want to print the yeild values, lets again iterate. 37 | 38 | for i in justCheckingValues: 39 | print (i) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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)) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /itertools/itertools_product.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | from itertools import * 3 | 4 | # 5 | # Task 6 | # 7 | # You are given a two lists A 8 | # A and B 9 | # Your task is to compute their cartesian product A 10 | # A 11 | # XB 12 | # B 13 | # . 14 | # 15 | # Example 16 | # A = [1, 2] 17 | # B = [3, 4] 18 | # 19 | # AxB = [(1, 3), (1, 4), (2, 3), (2, 4)] 20 | # 21 | # 22 | # Note: A 23 | # A 24 | # and B 25 | # B are sorted lists, and the cartesian product's tuples should be output in sorted order. 26 | 27 | # Input Format 28 | 29 | # The first line contains the space separated elements of list A 30 | # A 31 | # . 32 | # The second line contains the space separated elements of list B 33 | # B 34 | # . 35 | # Both lists have no duplicate integer elements. 36 | # Constraints 37 | # 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 [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 | -------------------------------------------------------------------------------- /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 | # 0 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() -------------------------------------------------------------------------------- /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()})) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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()) -------------------------------------------------------------------------------- /.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 | } -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/NaviBeer.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Sanjay' 2 | 3 | """ 4 | Navi and beer 5 | Max. Marks 100 6 | Navi and beer 7 | Navi is at the Beer Bar where he has ordered N beers. After seeing his love with the beers, Bar's Manager has decided to make as much money as they can by asking Navi to pay K * i3 Rupees for the ith beer. But Navi has only M Rupees in his purse. So you are required to lent him some money so that he can still be able to pay for all of the N beers. 8 | Input: 9 | First line will contain T (No. of test cases). 10 | Each test case will contain only one line having three space separated integers : N, K and M 11 | Output: 12 | For every test case, print the required answer in a new line. 13 | Constraints: 14 | 1 ? T ? 105 15 | 1 ? N, K ? 103 16 | 1 ? M ? 106 17 | Sample Code: 18 | #include 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/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/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