diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..174a5cc --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,5 @@ +{ + "recommendations": [ + "github.copilot" + ] +} \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..92a2fa2 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,70 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Python: Current File (Integrated Terminal)", + "type": "python", + "request": "launch", + "program": "${file}", + "console": "integratedTerminal" + }, + { + "name": "Python: Remote Attach", + "type": "python", + "request": "attach", + "port": 5678, + "host": "localhost", + "pathMappings": [ + { + "localRoot": "${workspaceFolder}", + "remoteRoot": "." + } + ] + }, + { + "name": "Python: Module", + "type": "python", + "request": "launch", + "module": "enter-your-module-name-here", + "console": "integratedTerminal" + }, + { + "name": "Python: Django", + "type": "python", + "request": "launch", + "program": "${workspaceFolder}/manage.py", + "console": "integratedTerminal", + "args": [ + "runserver", + "--noreload", + "--nothreading" + ], + "django": true + }, + { + "name": "Python: Flask", + "type": "python", + "request": "launch", + "module": "flask", + "env": { + "FLASK_APP": "app.py" + }, + "args": [ + "run", + "--no-debugger", + "--no-reload" + ], + "jinja": true + }, + { + "name": "Python: Current File (External Terminal)", + "type": "python", + "request": "launch", + "program": "${file}", + "console": "externalTerminal" + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..7f929a1 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.pythonPath": "C:\\Python37\\python.exe" +} \ No newline at end of file diff --git a/ArgsKwArgs/KwArgs.py b/ArgsKwArgs/KwArgs.py new file mode 100644 index 0000000..ac28dcd --- /dev/null +++ b/ArgsKwArgs/KwArgs.py @@ -0,0 +1,35 @@ +# Example 3: Using **kwargs to pass the variable keyword arguments to the function +def intro(**data): + print("\nData type of argument:",type(data)) + + for key, value in data.items(): + print("{} is {}".format(key,value)) + +intro(Firstname="Sita", Lastname="Sharma", Age=22, Phone=1234567890) +intro(Firstname="John", Lastname="Wood", Email="johnwood@nomail.com", Country="Wakanda", Age=25, Phone=9876543210) +# When we run the above program, the output will be + +# Data type of argument: +# Firstname is Sita +# Lastname is Sharma +# Age is 22 +# Phone is 1234567890 + +# Data type of argument: +# Firstname is John +# Lastname is Wood +# Email is johnwood@nomail.com +# Country is Wakanda +# Age is 25 +# Phone is 9876543210 + + +# 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. + +''' +Things to Remember: +1. *args and *kwargs are special keyword which allows function to take variable length argument. +2. *args passes variable number of non-keyworded arguments list and on which operation of the list can be performed. +3. **kwargs passes variable number of keyword arguments dictionary to function on which operation of a dictionary can be performed. +4. *args and **kwargs make the function flexible. +''' \ No newline at end of file diff --git a/ArgsKwArgs/args.py b/ArgsKwArgs/args.py new file mode 100644 index 0000000..c7470a8 --- /dev/null +++ b/ArgsKwArgs/args.py @@ -0,0 +1,62 @@ + + +# Suppose, we define a function for addition of 3 numbers. + +#Example 1: Function to add 3 numbers +def adder(x,y,z): + print("sum:",x+y+z) + +adder(10,12,13) #sum: 35 +# When we run the above program, the output will be + + +# In above program we have adder() function with three arguments x, y and z. When we pass three values while calling adder() function, we get sum of the 3 numbers as the output. + +# Lets see what happens when we pass more than 3 arguments in the adder() function. + +def adder(x,y,z): + print("sum:",x+y+z) + +adder(5,10,15,20,25) #TypeError: adder() takes 3 positional arguments but 5 were given +# When we run the above program, the output will be + +# In the above program, we passed 5 arguments to the adder() function instead of 3 arguments due to which we got TypeError. + +# Introduction to *args and **kwargs in Python +# In Python, we can pass a variable number of arguments to a function using special symbols. There are two special symbols: + +''' +*args (Non Keyword Arguments) +**kwargs (Keyword Arguments) +We use *args and **kwargs as an argument when we are unsure about the number of arguments to pass in the functions. + +Python *args +As in the above example we are not sure about the number of arguments that can be passed to a function. Python has *args which allow us to pass the variable number of non keyword arguments to function. + +In the function, we should use an asterisk * before the parameter name to pass variable length arguments.The arguments are passed as a tuple and these passed arguments make tuple inside the function with same name as the parameter excluding asterisk *. +''' + +# Example 2: Using *args to pass the variable length arguments to the function + +def adder(*num): + sum = 0 + + for n in num: + sum = sum + n + + print("Sum:",sum) + +adder(3,5) #Sum: 8 +adder(4,5,6,7) # Sum: 22 +adder(1,2,3,5,6) # Sum: 17 + + +# In the above program, we used *num as a parameter which allows us to pass variable length argument list to the adder() function. +# Inside the function, we have a loop which adds the passed argument and prints the result. +# We passed 3 different tuples with variable length as an argument to the function. + +# Python **kwargs +# Python passes variable length non keyword argument to function using *args but we cannot use this to pass keyword argument. For this problem Python has got a solution called **kwargs, it allows us to pass the variable length of keyword arguments to the function. + +# In the function, we use the double asterisk ** before the parameter name to denote this type of argument. The arguments are passed as a dictionary and these arguments make a dictionary inside function with name same as the parameter excluding double asterisk **. + diff --git a/Classes/composition.py b/Classes/composition.py new file mode 100644 index 0000000..e69de29 diff --git a/Classes/decorators.py b/Classes/decorators.py new file mode 100644 index 0000000..e69de29 diff --git a/Classes/globalVariables.py b/Classes/globalVariables.py new file mode 100644 index 0000000..637f854 --- /dev/null +++ b/Classes/globalVariables.py @@ -0,0 +1,42 @@ + + +import math + + + +class AreaOfCircle(): + PI_VALUE = 3.14 + + def __init__(self, name, gender): + self.name = name + self.gender = gender + + def areaCalculation(self, radius): + return 3.14 * (radius**2) + + +# sampleObj = AreaOfCircle() + +# print(sampleObj) + +# value = sampleObj.areaCalculation(5) + +# print(value) + +# what is the class attributes the? + +# print(AreaOfCircle.PI_VALUE) + +# print(sampleObj.PI_VALUE) + +############### + +ramObj = AreaOfCircle('Ram', 'Male') + +print(ramObj.name) +print(ramObj.gender) + + +# how about this? + +print(AreaOfCircle.name) \ No newline at end of file diff --git a/Classes/inheritance.py b/Classes/inheritance.py new file mode 100644 index 0000000..e69de29 diff --git a/Classes/session-on-class.py b/Classes/session-on-class.py new file mode 100644 index 0000000..0bddb87 --- /dev/null +++ b/Classes/session-on-class.py @@ -0,0 +1,72 @@ + + +class Employee(): + + def __init__(self, name, age): + self.name = name + self.age = age + self.pi = 3.142 + + # wrong way for gettting employee name from the object. + # def getEmployeeName(self, inputFromUser): + # print("Employee name is ", inputFromUser) + + def getNewEmployeeName(self): + print("new employee name is ", self.name) + + def getEmployeeAge(self): + print(self.name + "'s age is " + self.age) + +import random + +class Bank(): + def __init__(self, name, age, dob, address): + self.name = name + self.age = age + self.dob = dob + self.address = address + self.accountNumber = random.randint(1,1000) + self.accountBalance = 0 + print("Your account got created, " + self.name) + + + def getCustomerAccountInfo(self): + print("Hello " + self.name) + print("Your account got created, here's your account number " , str(self.accountNumber)) + print("Your current balance of your account is ", str(self.accountBalance)) + + def getMyBirthDate(self): + print('Hello ' + self.name + ' you birthday is ' + self.dob) + + +ramIsTheCustomer = Bank('Ram', 26, '1/1/2020', 'London') + +ramIsTheCustomer.getCustomerAccountInfo() + +ramIsTheCustomer.getMyBirthDate() + + + +ram = Employee("Ram") +san = Employee("Sanjay") + +print(ram) +print("--------") +# print(ram.getEmployeeName("Ram")) + +ram.getNewEmployeeName() + +san.getNewEmployeeName() +sanjay.getEmployeeAge() + + + + +class EmployeeV2(): + def __init__(self, name, age, sex): + self.name = name + self.age = age + self.sex = sex + + def getEmployeeName(self): + return("Employee name is " + self.name) diff --git a/Classes/special_class_methods.py b/Classes/special_class_methods.py new file mode 100644 index 0000000..e69de29 diff --git a/Classes/state.py b/Classes/state.py new file mode 100644 index 0000000..644872d --- /dev/null +++ b/Classes/state.py @@ -0,0 +1,61 @@ + + +# Have you heard about State in Programming Language? + +# Very frequentlt this terminology is been used in Entity or Object Communication. + + +# Let's say we have to model a bank account with support for deposit and withdraw operations. +# One way to do that is by using global state + +balance = 0 #balance variable is global of the program, if this below snippet is inside the class, we can call as class attribute. + +def deposit(amount): + global balance + balance += amount + return balance + +def withdraw(amount): + global balance + balance -= amount + return balance + +sanjay = deposit(100) +print(sanjay) + +# The above example is good enough only if we want to have just a single account. Did you understand what I said? + + +# ******Things start getting complicated if want to model multiple accounts.****** + +# We can solve the problem by making the state local, probably by using a dictionary to store the state. + +def make_account(): + return {'balance': 0} + +def putDeposit(account, amount): + account['balance'] += amount + return account['balance'] + +def withdrawMoney(account, amount): + account['balance'] -= amount + return account['balance'] + +def checkBalance(account): + return account['balance'] + + +sanjay = make_account() + +ram = make_account() + +# by default, when someone creates an account, balance will show 0. +putDeposit(sanjay, 5000) + +# what is sanjay's balance amount now? +print("Sanjay has " + str(checkBalance(sanjay)) + " in his account!") + +print("Sanjay has withdrawn 2500 rs from the account, therefore the remaining balance is " + str(withdrawMoney(sanjay, 2500))) + + + diff --git a/Cryptography/__pycache__/rsa.cpython-37.pyc b/Cryptography/__pycache__/rsa.cpython-37.pyc new file mode 100644 index 0000000..fcaa439 Binary files /dev/null and b/Cryptography/__pycache__/rsa.cpython-37.pyc differ diff --git a/Cryptography/rsa.py b/Cryptography/rsa.py new file mode 100644 index 0000000..bd52d9a --- /dev/null +++ b/Cryptography/rsa.py @@ -0,0 +1,28 @@ +from Crypto.PublicKey import RSA +from Crypto.Cipher import PKCS1_OAEP +import binascii + +keyPair = RSA.generate(1024) + +pubKey = keyPair.publickey() +# print(f"Public key: (n={hex(pubKey.n)}, e={hex(pubKey.e)})") + +pubKeyPEM = pubKey.exportKey() +print(pubKeyPEM.decode('ascii')) + + +# print(f"Private key: (n={hex(pubKey.n)}, d={hex(keyPair.d)})") +privKeyPEM = keyPair.exportKey() +print(privKeyPEM.decode('ascii')) + +msg = b'D$bd1@k3' +encryptor = PKCS1_OAEP.new(pubKey) +encrypted = encryptor.encrypt(msg) +print("Encrypted:", binascii.hexlify(encrypted)) + + +decryptor = PKCS1_OAEP.new(keyPair) +decrypted = decryptor.decrypt(encrypted) +print('\nDecrypted:', decrypted.decode("utf-8")) + + diff --git a/Cryptography/test.py b/Cryptography/test.py new file mode 100644 index 0000000..0b4139d --- /dev/null +++ b/Cryptography/test.py @@ -0,0 +1,24 @@ +# Basic Fernet + +# msg = "I am going to encrypt this sentence using Fernet" +msg = "D$bd1@k3" + +from cryptography import fernet +from cryptography.fernet import Fernet + +# first generate key +eKey = Fernet.generate_key() +print("\nKey is : " + eKey.decode()) +# print("\nType of key is .. " + str(type(eKey))) +print("\nKey is : " + str(len(eKey.decode()))) + +# create a class instance object +f1 = Fernet(eKey) + +eMsg = f1.encrypt(msg.encode()) # f1 instance can encrypt only bytes +print("\nEncrypted message is - " + eMsg.decode()) +print("\nEncrypted message is -" + str(len(eMsg))) + +# decrypt with same instance +dMsg = f1.decrypt(eMsg).decode() +print("\nDecrypted Message - " + dMsg) \ No newline at end of file diff --git a/DataCollectionTypes/Dictionary/Task1.py b/DataCollectionTypes/Dictionary/Task1.py new file mode 100644 index 0000000..63a234c --- /dev/null +++ b/DataCollectionTypes/Dictionary/Task1.py @@ -0,0 +1,85 @@ + + +globalKeys = [] +globalValues = [] + +GLOBAL_FILENAME = "input1.txt" +GLOBAL_FILE_PERMISSION = "w+" + + +def iterateListFunction(args): + ''' + args : takes arguments as list. + desc : separates key and value from dict/json. + ''' + for i in args: + if type(i) == dict: + globalKeys.append(*i) + globalValues.append(list(i.values())) + + +def appendingAllElementsInAList(alist): + ''' + args : takes arguments as list. + desc : separates key and value from dict/json accordingly. + ''' + finalOutput = [] + for i in alist: + if type(i) == list: + for z in i: + finalOutput.append(z) + else: + finalOutput.append(i) + return finalOutput + +def writeFinalOutput(manipulatedOutput): + ''' + args : manipulatedOutput - separated out as list (which is internally a zip object). + desc : Writes the output to the text file. + ''' + outF = open(GLOBAL_FILENAME, GLOBAL_FILE_PERMISSION) + outF.write("Keys Values") + outF.write("\n") + for line in manipulatedOutput: + # write line to output file + outF.write(line[0] + "\t\t\t" + str(line[1])) + outF.write("\n") + outF.close() + print("Program executed successfully! Please verify output at input1.txt") + +if __name__ == '__main__': + + userGivenInput = { 'a': + [ + { 'h': 'e' }, + { 'f': 'r' }, + { + 't': [ 'w', 'x' ] + } + ] , + 'b': [ + { + 'P': [ 'd', 'c' ] + }, + { + 'l': 'q' + } + ] + } + + for k,v in userGivenInput.items(): + if type(v) == list: + iterateListFunction(v) + + finalValueOutput = [] + + for i in globalValues: + if type(i) == list: + for j in i: + finalValueOutput.append(j) + opKeys = appendingAllElementsInAList(list(globalKeys)) + opValues = appendingAllElementsInAList(globalValues) + + finalOp = list(zip(opKeys, opValues)) + + writeFinalOutput(finalOp) \ No newline at end of file diff --git a/DataCollectionTypes/Dictionary/Task2.py b/DataCollectionTypes/Dictionary/Task2.py new file mode 100644 index 0000000..b9fc5ac --- /dev/null +++ b/DataCollectionTypes/Dictionary/Task2.py @@ -0,0 +1,72 @@ +org = [] +def getOrgNames(fromGivenInput): + for orgInfo in fromGivenInput: + if not orgInfo['orgName'] in org: + org.append(orgInfo['orgName']) + return org + +def employeeInfoBasedOnOrg(orgName, userGivenInput): + output = { orgName : []} + tempOp = {} + + for info in userGivenInput: + if info['orgName'] == orgName: + tempOp[info['empName']] = info['empSal'] + + output[orgName].append(tempOp) + print(output) + +if __name__ == '__main__': + + givenInput = [ + { + "orgName": "techM", + "empName": "name1", + "empSal": "40000" + }, + { + "orgName": "techM", + "empName":"name2", + "empSal": "5000" + }, + { + "orgName": "techM", + "empName": "name3", + "empSal": "50000" + }, + { + "orgName": "Mahindra", + "empName": "name4", + "empSal": "55000" + }, + { + "orgName": "Mahindra", + "empName": "name5", + "empSal": "45000" + }, + { + "orgName": "Mahindra", + "empName": "name6", + "empSal": "35000" + } + ] + + + listOfOrgs = getOrgNames(givenInput) + + for orgName in listOfOrgs: + employeeInfoBasedOnOrg(orgName, givenInput) + + +from collections import Counter + +eop = {} +d1 = {'apple': 'sanjay', 'orange': 'sanjay', 'banana': 'sanjay'} + +# for k,v in d1.items(): +# if type(v) == str: +# eop[k] = len(v) + +# print(Counter(eop)) + +print(Counter({k:len(v) for k,v in d1.items()})) \ No newline at end of file diff --git a/DataCollectionTypes/Dictionary/Tutorials_1.py b/DataCollectionTypes/Dictionary/Tutorials_1.py index 5c531c4..aab58d8 100644 --- a/DataCollectionTypes/Dictionary/Tutorials_1.py +++ b/DataCollectionTypes/Dictionary/Tutorials_1.py @@ -8,3 +8,7 @@ print(myDict) # Output: {'name': 'AnyName', 'id': 123, 'info': 'value of id not neccessarily need to be string since it has integer as numbers'} print(myDict.keys()) #Output: dict_keys(['name', 'id', 'info']) + + + +from collections import Counter \ No newline at end of file diff --git a/DataCollectionTypes/Dictionary/to_delete_in_future_sample.py b/DataCollectionTypes/Dictionary/to_delete_in_future_sample.py new file mode 100644 index 0000000..d69ff95 --- /dev/null +++ b/DataCollectionTypes/Dictionary/to_delete_in_future_sample.py @@ -0,0 +1,79 @@ +# import pyodbc +# import json + +# # reads N number of lines of queries +# def readSQL(): +# with open('queries.sql', 'r') as sqlFile: +# line = sqlFile.readlines() +# return line + +# def sqlConnect(): +# conn = pyodbc.connect('Driver={SQL Server};' +# 'Server=DESKTOP-AV96G7N;' +# 'Database=AdventureWorks2019;' +# 'Trusted_Connection=yes;') +# cursor = conn.cursor() +# return cursor + +# def executeSQLQuery(cursorObj, query): +# execResult = cursorObj.execute(query) +# return execResult + +# def getCursorData(cursorObj): +# outputDict = {} + +# outputDict['ID'] = cursorObj[0] +# outputDict['NI_ID'] = cursorObj[1] +# outputDict['JOB_TITLE'] = cursorObj[2] + +# return outputDict + +# if _name_ == "__main__": +# sqlLine = readSQL() +# connectionString = sqlConnect() + +# sanjOp = {} + +# for rowLine in sqlLine: +# execResult = executeSQLQuery(connectionString, rowLine) +# for rows in execResult: +# print(rows) + +# # outputResult = list(sqlConnect()) +# finalListOutput = [getCursorData(row) for row in outputResult] +# outputJson = {} +# outputJson['Result'] = finalListOutput + + # """ Below code is used to create a json file if not available and dumps the output """ + # with open('data.json', 'w') as file: + # json.dump(outputJson, file) + + # """ below code with append the out to already available json file """ + # with open('data.json', 'w') as file: + # json.zzzzzzzz(outputJson, file) + + + # Ram's expectation is to have two lines of json object in a data.json file. + # Here's tee sample, + + # {'result1': [{},{},{}]} + # {'result2': [{},{},{}]} + + +import json +intellipaat = {"course":"python", "topic":"Python JSON"} +intellipaat_json = json.dumps(intellipaat) + +print(type(intellipaat_json)) + +testFile = open('test.json', 'w') + +for i in range(1,5): + testFile.write(intellipaat_json + "\n") + + +test = {} +for i in range(0,10): + test['result'+str(i)] = [] + +print(test) \ No newline at end of file diff --git a/DataCollectionTypes/List/2. ListLeaning.py b/DataCollectionTypes/List/2. ListLearning.py similarity index 100% rename from DataCollectionTypes/List/2. ListLeaning.py rename to DataCollectionTypes/List/2. ListLearning.py diff --git a/DataCollectionTypes/List/6. CombiningAllInnerListIntoOneList.py b/DataCollectionTypes/List/6. CombiningAllInnerListIntoOneList.py index 8921f18..3cfdb5f 100644 --- a/DataCollectionTypes/List/6. CombiningAllInnerListIntoOneList.py +++ b/DataCollectionTypes/List/6. CombiningAllInnerListIntoOneList.py @@ -35,7 +35,7 @@ def genericSolutionWithoutUsingRecursive(inputList): print(firstInputList) # ['a', 'b', 'c', 'd', [1, 2, 3]] ob = singleList() - # ob.appendingAllElementsInAList(firstInputList) + ob.appendingAllElementsInAList(firstInputList) # Take this example, here elements inside the below lists are again list. sampleList = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] diff --git a/DataCollectionTypes/List/FindCommonElements.py b/DataCollectionTypes/List/FindCommonElements.py new file mode 100644 index 0000000..813c44b --- /dev/null +++ b/DataCollectionTypes/List/FindCommonElements.py @@ -0,0 +1,13 @@ + +def __onlyCommonEle(p): + if len(p) == 0: + return + print(set(p[0]).intersection(*p)) + +def findCommonElements(*args): + if len(args) == 0: + return + __onlyCommonEle([i for i in args if type(i) == list]) + + +findCommonElements([1,2,3], 'a', 'c', ['a','b',1,2,4]) \ No newline at end of file diff --git a/DataCollectionTypes/List/MoveAllZerosToEnd.py b/DataCollectionTypes/List/MoveAllZerosToEnd.py new file mode 100644 index 0000000..25d3842 --- /dev/null +++ b/DataCollectionTypes/List/MoveAllZerosToEnd.py @@ -0,0 +1,35 @@ +from collections import Counter + +def moveZerosToEnd(inputList): + if type(inputList) is not list: + return + + if 0 in inputList : + ex = dict(Counter(inputList)) + if (0 in ex.keys()): + op = [i for i in inputList if i != 0] + for i in range(ex[0]): + op.append(0) + else: + return "No Zeros exist" + + + print(op) + + +# OMKAR solution - isn't working. +# def move(arr): +# count = 0 +# for a in arr: +# if not a == 0: +# arr[count] = a +# count += 1 +# while count < len(nums): +# arr[count] = 0 +# count += 1 + + + +moveZerosToEnd([1,2,3,4,0,0,0,0,3,4,43,43,435453,545455,7676]) +print(moveZerosToEnd([1,2,3,4,4])) + diff --git a/DataCollectionTypes/Sets/Excercise/difference.py b/DataCollectionTypes/Sets/Excercise/difference.py new file mode 100644 index 0000000..a4ee5d0 --- /dev/null +++ b/DataCollectionTypes/Sets/Excercise/difference.py @@ -0,0 +1,65 @@ +__author__ = 'Sanjay' +# +# +# Task +# +# +# 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. +# +# 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. +# +# +# Input Format +# +# +# The first line contains the number of students who have subscribed to the English newspaper. +# The second line contains the space separated list of student roll numbers who have subscribed to the English newspaper. +# The third line contains the number of students who have subscribed to the French newspaper. +# The fourth line contains the space separated list of student roll numbers who have subscribed to the French newspaper. +# +# Constraints +# +# 0 will say it's a dictionary - -mySet = {'apple', 'banana'} - -print(mySet[1]) # this will throw error as "it doesn't support indexing" as mentioned in the description - -# 2. get the elements out - -for item in mySet: - print(i) - -#output: -# apple -# banana - -# 3. Add Items - -# if you want to add one element into the set, then proceed like below. - -mySet.add("Cherry") - -print (mySet) #{'apple', 'cherry', 'banana'} comes in random order. - - -# 4. update Items -# if you want to add many elements in a single shot, try this below. - -mySet.update(['orange', 'pomo', 'mango']) -print (mySet) #{'cherry', 'orange', 'apple', 'pomo', 'banana', 'mango' - - -# 5. Length of Set - -len(mySet) # 6 - -# 6. Remove Item -# To remove an item in a set, use the remove(), or the discard() method. - -mySet.remove('pomo') # this will remove 'pomo' elements from the set, will not return any. -print(mySet) # {'cherry', 'orange', 'apple', 'banana', 'mango'} - - -mySet.discard("orange") -print (mySet) # {'cherry', 'apple', 'banana', 'mango'} - - -# You can also use the pop(), method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed. - -# The return value of the pop() method is the removed item. -# here's the custom example. - -s1 = {'rob', 'bob', 'alice'} -print (s1) - -#when you run the below code, it's expected to remove 'alice', but it'snt - -s1.pop() #retured me bob - -# its better not use pop() - - -# how to delete all the elements inside the Set() - -mySet.clear() # returns {} empty set - - - -# how to delete the complete set itself? - -del mySet - - -# difference() - -s1 = {1,2,3,4,5} -s2 = {4,5,6,7,8} - -s1.difference(s2) #{1,2,3} -s2.difference(s1) # {6,7,8} - - - -# symmentric_difference() -s1 = {1,2,3,4,5} -s2 = {4,5,6,7,8} - -s1.symmentric_difference(s2) #{1,2,3,6,7,8} -s2.symmentric_difference(s1) #{1,2,3,6,7,8} - - -# symmetric_difference_update() inserts the symmetric differences from this set and another -s1 = {1,2,3,4,5} -s2 = {4,5,6,7,8} - -s1.symmetric_difference_update(s2) -s1 # {1,2,3,6,7,8} - -# if you do s2.symmetric_difference_update(s1) it will return the same elements as above. - - -# difference_update() Removes the items in this set that are also included in another, specified set - -s1.difference_update(s2) # {1,2,3} -> it actually remvoved 4,5 from s1 - -s2.difference_update(s1) # {6,7,8} --> it actually removed 4,5 from s2 - - -# Union - -s1 = {1,2,3,4,5} -s2 = {4,5,6,7,8} - -s1 | s2 # {1,2,3,4,5,6,7,8} --> the common items (4,5) between two sets are not repeated - - -# Intersection - -s1 = {1,2,3,4,5} -s2 = {4,5,6,7,8} - -s1 & s2 # {4, 5} --> returns common elements which are available in two sets - - -# intersection_update() - Removes the items in this set that are not present in other, specified set(s) - -s1 = {1,2,3,4,5} -s2 = {4,5,6,7,8} - -s1.intersection_update(s2) -s1 # {4,5} because it removed not matching elements -s2 # {8, 4, 5, 6, 7} its still the same - -s1 = {1,2,3,4,5} -s2 = {4,5,6,7,8} - -s2.intersection_update(s1) -s1 # {1,2,3,4,5} -s2 # {4,5} because it removed not matching elements - - - -# issubset() - -s1 = {'a','b','c'} -s2 = {'c','d','e','a','m','b'} - -s1.issubset(s2) # --> True [Explanation: checks wether all elements of s1 is available in s2 or not, if available then returns True else False] - -s2.issubset(s1) # --> False [Explanation: checks wether all elements of s2 is available in s1 or not, if available then returns True else False] - - -# issuperset() - -s1 = {'a','b','c'} -s2 = {'c','d','e','a','m','b'} - -s1.issuperset(s2) # --> False [Explanation: checks whether all elements of s2 is available in s1 or not, if available then returns True else False] - - - - - - - - diff --git a/DataStructures/Array/What.py b/DataStructures/Array/What.py new file mode 100644 index 0000000..615d5aa --- /dev/null +++ b/DataStructures/Array/What.py @@ -0,0 +1,72 @@ +# What is array? +# Array is a data structure used to store homogeneous elements at contiguous locations. +# One memory block is allocated for the entire array to hold the elements of the array. +# The array elements can be accessed in constant time by using the index of the particular element as the subscript + +# Common array operations: +# Search +# Insert +# Delete + +# Time complexity: + +# Search: O(n) +# Insert: O(n) +# Delete: O(n) +# Indexing: O(1) + +# Disadvantage of array? +# Fixed size: The size of the array is static (specify the array size before using it, this can be overcome using Dynamic Arrays). +# One block allocation: To allocate the array itself at the beginning, sometimes it may not be possible to get the memory for the complete array (if the array size is big). +# Complex position-based insertion: To insert an element at a given position, we may need to shift the existing elements. This will create a position for us to insert the new element at the desired position. If the position at which we want to add an element is at the beginning, then the shifting operation is more expensive . + +# Arrays in Python: +# Python does not have a native support for arrays, but has a more generic data structure called LIST. +# List provides all the options as array with more functionality. But with few tweaks we can implement Array data structure in Python. + + +class Array(object): + ''' sizeOfArray: denotes the total size of the array to be initialized + arrayType: denotes the data type of the array(as all the elements of the array have same data type) + arrayItems: values at each position of array + ''' + def __init__(self, sizeOfArray, arrayType = int): + self.sizeOfArray = len(list(map(arrayType, range(sizeOfArray)))) + self.arrayItems =[arrayType(0)] * sizeOfArray # initialize array with zeroes + + def __str__(self): + return ' '.join([str(i) for i in self.arrayItems]) + + # function for search + def search(self, keyToSearch): + for i in range(self.sizeOfArray): + if (self.arrayItems[i] == keyToSearch): # brute-forcing + return i # index at which element/ key was found + + return -1 # if key not found, return -1 + + # function for inserting an element + def insert(self, keyToInsert, position): + if(self.sizeOfArray > position): + for i in range(self.sizeOfArray - 2, position - 1, -1): + self.arrayItems[i + 1] = self.arrayItems[i] + self.arrayItems[position] = keyToInsert + else: + print('Array size is:', self.sizeOfArray) + + # function to delete an element + def delete(self, keyToDelete, position): + if(self.sizeOfArray > position): + for i in range(position, self.sizeOfArray - 1): + self.arrayItems[i] = self.arrayItems[i + 1] + else: + print('Array size is:', self.sizeOfArray) + +a = Array(10, int) +print(a) + +a.insert("Sanjay", 9) +print(a) + +a.delete('Sanjay', 9) +print(a) \ No newline at end of file diff --git a/DataStructures/FB/EditApart.py b/DataStructures/FB/EditApart.py new file mode 100644 index 0000000..d074ce4 --- /dev/null +++ b/DataStructures/FB/EditApart.py @@ -0,0 +1,26 @@ + +def findActions(s1, s2): + if len(s1) > len(s2): + for i in s1: + print(i[0]) + elif len(s1) < len(s2): + pass + else: + pass + +def OneEditApart(s1, s2): + if type(s1) != str and type(s2) != str: + return False + + if len(s1) == 0 or len(s2) == 0: + return False + + eS1 = enumerate(s1) + eS2 = enumerate(s2) + + print(list(eS1)) + print(list(eS2)) + + +OneEditApart("Geeks", "Geek") +print("s") \ No newline at end of file diff --git a/DataStructures/FB/Spiral.py b/DataStructures/FB/Spiral.py new file mode 100644 index 0000000..7b253d3 --- /dev/null +++ b/DataStructures/FB/Spiral.py @@ -0,0 +1,41 @@ +def spiralOrder(matrix): + ans = [] + + if (len(matrix) == 0): + return ans + + R = len(matrix) + C = len(matrix[0]) + seen = [[0 for i in range(C)] for j in range(R)] + dr = [0, 1, 0, -1] + dc = [1, 0, -1, 0] + r = 0 + c = 0 + di = 0 + + # Iterate from 0 to R * C - 1 + for i in range(R * C): + ans.append(matrix[r]) + seen[r] = True + cr = r + dr[di] + cc = c + dc[di] + + # if (0 <= cr and cr < R and 0 <= cc and cc < C and not(seen[cr][cc])): + # r = cr + # c = cc + # else: + # di = (di + 1) % 4 + # r += dr[di] + # c += dc[di] + return ans + + +# Driver code +a = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]] + +for x in spiralOrder(a): + print(x, end=" ") +print() \ No newline at end of file diff --git a/DataStructures/LinkedList/LinkedList_EasyUnderstanding.py b/DataStructures/LinkedList/LinkedList_EasyUnderstanding.py index 3361e87..5adde8e 100644 --- a/DataStructures/LinkedList/LinkedList_EasyUnderstanding.py +++ b/DataStructures/LinkedList/LinkedList_EasyUnderstanding.py @@ -29,7 +29,7 @@ def __init__(self): def printList(self): temp = self.head while (temp): - print(temp.data,) + print(temp.data, end=",") temp = temp.next diff --git a/DataStructures/LinkedList/LinkedList_Implementation.py b/DataStructures/LinkedList/LinkedList_Implementation.py index 10df356..301cd4b 100644 --- a/DataStructures/LinkedList/LinkedList_Implementation.py +++ b/DataStructures/LinkedList/LinkedList_Implementation.py @@ -67,6 +67,4 @@ def print_list(self): s.add_at_front(5) s.add_at_end(8) s.add_at_front(9) -s.print_list() - - +s.print_list() \ No newline at end of file diff --git a/QDataStructure/Stack_Implementation.py b/DataStructures/Stack/Stack_Implementation.py similarity index 63% rename from QDataStructure/Stack_Implementation.py rename to DataStructures/Stack/Stack_Implementation.py index 9afef78..aca3784 100644 --- a/QDataStructure/Stack_Implementation.py +++ b/DataStructures/Stack/Stack_Implementation.py @@ -15,15 +15,29 @@ #The above information gives you clear understanding on Stacks Predefined functions. -class Stack: - def __init__(self): +class Stack(object): + + """ A stack is an abstract data type that serves as a collection of + elements with two principal operations: push() and pop(). push() adds an + element to the top of the stack, and pop() removes an element from the top + of a stack. The order in which elements come off of a stack are + Last In, First Out (LIFO). + https://en.wikipedia.org/wiki/Stack_(abstract_data_type) + """ + def __init__(self, defaultLimit = 10): self.items = [] + self.limit = defaultLimit def push(self, newItem): + if len(self.items) >= self.limit: + raise StackOverflowError self.items.append(newItem) def pop(self): - self.items.pop() + if self.items: + return self.items.pop() + else: + raise IndexError("pop from an empty stack") def isEmpty(self): return self.items == [] @@ -32,7 +46,7 @@ def size(self): return len(self.items) def show(self): - print self.items + print(self.items) return self.items def peek(self): @@ -41,6 +55,9 @@ def peek(self): def size(self): return len(self.items) +class StackOverflowError(BaseException): + pass + if __name__ == '__main__': obj = Stack() diff --git a/DataStructures/test/test.cs b/DataStructures/test/test.cs new file mode 100644 index 0000000..50ead5e --- /dev/null +++ b/DataStructures/test/test.cs @@ -0,0 +1,4 @@ +// write a hello world program + +// console.log("Hello") +console.writeLine("hhhh") \ No newline at end of file diff --git a/DynamicProgramming/BitMask.py b/DynamicProgramming/BitMask.py new file mode 100644 index 0000000..75a0b4d --- /dev/null +++ b/DynamicProgramming/BitMask.py @@ -0,0 +1,123 @@ +""" + +This is a Python implementation for questions involving task assignments between people. +Here Bitmasking and DP are used for solving this. + +Question :- +We have N tasks and M people. Each person in M can do only certain of these tasks. Also +a person can do only one task and a task is performed only by one person. +Find the total no of ways in which the tasks can be distributed. +""" + +from collections import defaultdict + + +class AssignmentUsingBitmask: + def __init__(self, task_performed, total): + self.total_tasks = total # total no of tasks (N) + + # DP table will have a dimension of (2^M)*N + # initially all values are set to -1 + self.dp = [ + [-1 for i in range(total + 1)] for j in range(2 ** len(task_performed)) + ] + + self.task = defaultdict(list) # stores the list of persons for each task + + # final_mask is used to check if all persons are included by setting all bits + # to 1 + self.final_mask = (1 << len(task_performed)) - 1 + + def count_ways_until(self, mask, task_no): + # if mask == self.finalmask all persons are distributed tasks, return 1 + if mask == self.final_mask: + return 1 + + # if not everyone gets the task and no more tasks are available, return 0 + if task_no > self.total_tasks: + return 0 + + # if case already considered + if self.dp[mask][task_no] != -1: + return self.dp[mask][task_no] + + # Number of ways when we don't this task in the arrangement + total_ways_util = self.count_ways_until(mask, task_no + 1) + + # now assign the tasks one by one to all possible persons and recursively + # assign for the remaining tasks. + if task_no in self.task: + for p in self.task[task_no]: + # if p is already given a task + if mask & (1 << p): + continue + + # assign this task to p and change the mask value. And recursively + # assign tasks with the new mask value. + total_ways_util += self.count_ways_until(mask | (1 << p), task_no + 1) + + # save the value. + self.dp[mask][task_no] = total_ways_util + + return self.dp[mask][task_no] + + def count_no_of_ways(self, task_performed): + # Store the list of persons for each task + for i in range(len(task_performed)): + for j in task_performed[i]: + self.task[j].append(i) + + # call the function to fill the DP table, final answer is stored in dp[0][1] + return self.count_ways_until(0, 1) + + +if __name__ == "__main__": + total_tasks = 5 # total no of tasks (the value of N) + + # Example 1 + task_performed = [[1, 3, 4], [1, 2, 5], [3, 4]] + print( + AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( + task_performed + ) + ) + + # Example 2 + task_performed = [[1, 2], [2, 3], [1, 3]] + print( + AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( + task_performed + ) + ) + + # Example 3 + task_performed = [[1, 2, 3], [2, 3, 4], [1, 4, 5]] + print( + AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( + task_performed + ) + ) + + # Example 4 + task_performed = [[1], [2], [3], [4], [5]] + print( + AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( + task_performed + ) + ) + + # Example 5 + task_performed = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]] + print( + AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( + task_performed + ) + ) + + # the list of tasks that can be done by M persons. + task_performed = [[1, 3, 4], [1, 2, 5], [3, 4]] + print( + AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( + task_performed + ) + ) \ No newline at end of file diff --git a/DynamicProgramming/__init__.py b/DynamicProgramming/__init__.py new file mode 100644 index 0000000..b03aa57 --- /dev/null +++ b/DynamicProgramming/__init__.py @@ -0,0 +1,25 @@ +""" +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. + +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. + +Example: +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. + +Here is a simple implementation of the Fibonacci sequence using dynamic programming in Python: + +def fibonacci(n): + # Create an array to store Fibonacci numbers + fib = [0] * (n + 1) + # Base cases + fib[0] = 0 + fib[1] = 1 + # Compute the Fibonacci numbers in a bottom-up manner + for i in range(2, n + 1): + fib[i] = fib[i - 1] + fib[i - 2] + return fib[n] + +print(fibonacci(10)) # Output: 55 + +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. +""" \ No newline at end of file diff --git a/DynamicProgramming/abbrevation.py b/DynamicProgramming/abbrevation.py new file mode 100644 index 0000000..69d6da6 --- /dev/null +++ b/DynamicProgramming/abbrevation.py @@ -0,0 +1,40 @@ +""" +Problem Link : https://www.hackerrank.com/challenges/abbr/problem +You can perform the following operation on some string, : + +1. Capitalize zero or more of 's lowercase letters at some index i + (i.e., make them uppercase). +2. Delete all of the remaining lowercase letters in . + +Example: +a=daBcd and b="ABC" +daBcd -> capitalize a and c(dABCd) -> remove d (ABC) +""" + +def need_transform(first_input: str, second_input: str) -> bool: + """ + Determines if string first_input can be transformed into string second_input by capitalizing + zero or more lowercase letters and deleting all other lowercase letters. + + Args: + first_input (str): The original string. + second_input (str): The target string. + + Returns: + bool: True if first_input can be transformed into second_input, False otherwise. + """ + + dp = [[False] * (len(first_input) + 1) for _ in range(len(second_input) + 1)] + dp[0][0] = True + + for i in range(len(second_input)): + for j in range(len(first_input) + 1): + if dp[i][j]: + if j < len(first_input) and first_input[i].upper() == second_input[j]: + dp[i + 1][j + 1] = True + if first_input[i].islower(): + dp[i + 1][j] = True + + return dp[len(second_input)][len(first_input)] + +print(need_transform("daBcd", "ABC")) \ No newline at end of file diff --git a/DynamicProgramming/factorial.py b/DynamicProgramming/factorial.py new file mode 100644 index 0000000..3f98374 --- /dev/null +++ b/DynamicProgramming/factorial.py @@ -0,0 +1,40 @@ + +# The @lru_cache is a decorator provided by the functools module in Python. +# It stands for "Least Recently Used cache". This decorator is used to cache +# the results of function calls, so that if the function is called again with +# the same arguments, the cached result is returned instead of recomputing +# the result. This can significantly improve the performance of functions that +# are called frequently with the same arguments, especially recursive +# functions like your factorial function. + +# Here's a brief explanation of how it works in your code: + +# Caching: When factorial is called with a particular argument, +# the result is stored in a cache. + +# Reuse: If factorial is called again with the same argument, +# the cached result is returned immediately, avoiding the need for +# recalculating the factorial. + +# Efficiency: This reduces the number of recursive calls and improves the +# performance of the function. + +# To use @lru_cache, you need to import it from the functools module. +# Here is your updated code with the necessary import statement: + +# Factorial of a number using memoization + +from functools import lru_cache + + +@lru_cache +def factorial(num: int) -> int: + if num < 0: + raise ValueError("Number should not be negative.") + + return 1 if num in (0, 1) else num * factorial(num - 1) + + +if __name__ == "__main__": + sample_input = 10 + print(factorial(sample_input)) \ No newline at end of file diff --git a/DynamicProgramming/rapdiFibonacci.py b/DynamicProgramming/rapdiFibonacci.py new file mode 100644 index 0000000..eb59ff8 --- /dev/null +++ b/DynamicProgramming/rapdiFibonacci.py @@ -0,0 +1,36 @@ +from __future__ import annotations +import sys + + +def fibonacci(n: int) -> int: + """ + return F(n) + >>> [fibonacci(i) for i in range(13)] + [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] + """ + if n < 0: + raise ValueError("Negative arguments are not supported") + return _privateFibonacci(n)[0] + + +# returns (F(n), F(n-1)) +def _privateFibonacci(userGivenNumber: int) -> tuple[int, int]: + if userGivenNumber == 0: # (F(0), F(1)) + return (0, 1) + + # F(2n) = F(n)[2F(n+1) - F(n)] + # F(2n+1) = F(n+1)^2+F(n)^2 + a, b = _privateFibonacci(userGivenNumber // 2) + + c = a * (b * 2 - a) + d = a * a + b * b + + if n%2: + return (d, c+d) + else: + return (c, d) + + +if __name__ == "__main__": + n = 5 + print(f"fibonacci({n}) is {fibonacci(n)}") \ No newline at end of file diff --git a/DynamicProgramming/wordBreak.py b/DynamicProgramming/wordBreak.py new file mode 100644 index 0000000..69b9243 --- /dev/null +++ b/DynamicProgramming/wordBreak.py @@ -0,0 +1,125 @@ +""" +Task: +Given a string and a list of words, return true if the string can be +segmented into a space-separated sequence of one or more words. + +Note that the same word may be reused +multiple times in the segmentation. + +Implementation notes: Trie + Dynamic programming up -> down. +The Trie will be used to store the words. It will be useful for scanning +available words for the current position in the string. + +Leetcode: +https://leetcode.com/problems/word-break/description/ + +Runtime: O(n * n) +Space: O(n) +""" + +import functools +from typing import Any + + +def word_break(givenInputString: str, words: list[str]) -> bool: + """ + Return True if numbers have opposite signs False otherwise. + + >>> word_break("applepenapple", ["apple","pen"]) + True + >>> word_break("catsandog", ["cats","dog","sand","and","cat"]) + False + >>> word_break("cars", ["car","ca","rs"]) + True + >>> word_break('abc', []) + False + >>> word_break(123, ['a']) + Traceback (most recent call last): + ... + ValueError: the string should be not empty string + >>> word_break('', ['a']) + Traceback (most recent call last): + ... + ValueError: the string should be not empty string + >>> word_break('abc', [123]) + Traceback (most recent call last): + ... + ValueError: the words should be a list of non-empty strings + >>> word_break('abc', ['']) + Traceback (most recent call last): + ... + ValueError: the words should be a list of non-empty strings + """ + + if not isinstance(givenInputString, str) or len(givenInputString) == 0: + raise ValueError("the string should be not empty string") + + if not isinstance(words, list) or not all( + isinstance(item, str) and len(item) > 0 for item in words + ): + raise ValueError("the words should be a list of non-empty strings") + + word_keeper_key = "WORD_KEEPER" + + + def build_trie(words: list[str]) -> dict[str, Any]: + """ + Builds a trie (prefix tree) from a list of words. + Args: + words (list[str]): A list of words to be inserted into the trie. + Returns: + dict[str, Any]: The root of the trie data structure. + Example: + >>> words = ["apple", "app", "banana"] + >>> trie = build_trie(words) + >>> print(trie) + {'a': {'p': {'p': {'l': {'e': {'word_keeper_key': True}}, 'word_keeper_key': True}}}, 'b': {'a': {'n': {'a': {'n': {'a': {'word_keeper_key': True}}}}}}} + """ + + trie: dict[str, Any] = {} + + for word in words: + trie_node = trie + for c in word: + if c not in trie_node: + trie_node[c] = {} + trie_node = trie_node[c] + trie_node[word_keeper_key] = True + + return trie + + + """ + The functools.cache decorator is used to cache the results of the function it decorates. This means that when the function is called with the same arguments, the cached result is returned instead of recomputing the result. This can significantly improve performance, especially for recursive functions like is_breakable in your code. + + In your word_break function, functools.cache is used to cache the results of the is_breakable function. This helps avoid redundant calculations and speeds up the process of checking if the string can be segmented into words from the given list. + + Here's a brief explanation of how it works in your code: + + When is_breakable is called with a specific index, the result is computed and stored in the cache. + If is_breakable is called again with the same index, the cached result is returned immediately, avoiding the need to recompute the result. + This caching mechanism helps optimize the recursive calls, making the function more efficient. + """ + @functools.cache + def is_breakable(index: int) -> bool: + + if index == len(givenInputString): + return True + + trie_node = build_trie(words) + for letter in range(index, len(givenInputString)): + trie_node = trie_node.get(givenInputString[letter], None) + + if trie_node is None: + return False + + if trie_node.get(word_keeper_key, False) and is_breakable(letter + 1): + return True + + return False + + return is_breakable(0) + + +if __name__ == "__main__": + print(word_break("applepenapple", ["apple", "pen"])) \ No newline at end of file diff --git a/ExceptionalHandling/EHFinally.py b/ExceptionalHandling/EHFinally.py new file mode 100644 index 0000000..31bcebf --- /dev/null +++ b/ExceptionalHandling/EHFinally.py @@ -0,0 +1,38 @@ + + +# Important point to be noted. + +# finally block is always executed after leaving the try statement. +# In case if some exception was not handled by except block, it is re-raised after execution of finally block. +# finally block is used to deallocate the system resources. +# One can use finally just after try without using except block, but no exception is handled in that case. + +# here's the sample exercise for understanding `finally` keyword in python + +try: + inFromUser = int(input("Hello user, give me a integer input: ")) + k = 5//inFromUser # raises divide by zero exception. + print(k) + +# handles zerodivision exception +except ZeroDivisionError: + print("Can't divide by zero") +except TypeError: + print("Given in put is not in a right datatype") + +finally: + # this block is always executed + # regardless of exception generation. + print('This is always executed') + for num in list(range(0,10)): + if num%2 ==0: + continue + print(num) + +# have you heard about break/continue + +# by default continue will not support inside finally +# from 3.8.3, continue is supported inside finally + + + diff --git a/ExceptionalHandling/ForGoodUnderstanding.py b/ExceptionalHandling/ForGoodUnderstanding.py new file mode 100644 index 0000000..d163736 --- /dev/null +++ b/ExceptionalHandling/ForGoodUnderstanding.py @@ -0,0 +1,213 @@ + +''' +What is Exception? + +Errors detected during execution are called exceptions, if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. + +''' + +print(1/0) # Syntactically it's right, but do you think this will execute? + +# print(name) # have we declared/defined before this line of code? + +# What will be the output? + +# print('2' + 5) + + +# To overcome the above examples, I'm creating method, which handles the exeptions in it. + +# First example + +def division(): + try: + print(1/0) + except ZeroDivisionError: + print("why are you trying to divide a natural number with 0?") + except ValueError: + print("Value error man..") + except TimeoutError: + print("time out error sir..") + +division() + +# Second example + +def showName(): + try: + print(name) + except ZeroDivisionError: + print("why are you trying divide a natural number with 0?") + except ValueError: + print("Value error man..") + except TimeoutError: + print("time out error sir..") + except NameError: + print("You haven't defined any such variable btw") + # Stlyish way is.. + except (RecursionError,NameError,TypeError, ZeroDivisionError) as e: + print("I catched.") + print("Unforu.. user has tried this, blah ") + # logger.log(e.messages) + pass + +showName() + +# Third Example + +def addValues(): + try: + print('2' + 'Sanjay' + 1232) + # except TypeError: + # print("I don't support this type.") + # except Exception: + # print("Master guy says, Something went wrong inside the code.") + # print("ERROR_CODE_SYMC_PO@$#:5533636") + except SanjayException: + print("Something") + +addValues() + +# Till now, we saw about predefined or system defined exceptions, isn't it? +# Think about writing our own exceptions? + +# JFYI + +''' +When we are developing a large Python program, it is a good practice to place all the user-defined +exceptions that our program raises in a separate file. Many standard modules do this. They define their +exceptions separately as exceptions.py or errors.py (generally but not always). + + +user-defined exception class can implement everything a normal class can do, but we generally make them simple and concise. +Most implementations declare a custom base class and derive others exception classes from this base class. +''' + +# first example of user defined exception. +class SanjayException(Exception): + pass + +import collections +import ExceptionalHandling + +# class RamException(): + +# def m1(self): +# ExceptionalHandling.ForGoodUnderstanding + +def evenOrOdd(number): + if type(number) is not int: + raise(SanjayException("input parameter is not in right format")) + + # if (number % 2 == 0): + # return True + # else: + # return False + return True if number %2 ==0 else False + +evenOrOdd('Sanjay') + + +# To go even deeper, here's the list of user defined exceptions. + +class Error(Exception): + """Base class for other exceptions""" + pass + + +class ValueTooSmallError(Error): + """Raised when the input value is too small""" + pass + + +class ValueTooLargeError(Error): + """Raised when the input value is too large""" + pass + +class RamsException1010(ZeroDivisionError): + pass + + + +# you need to guess this number +gloal_lucky_number = 10 + +# user guesses a number until he/she gets it right +while True: + try: + userGivenInput = int(input("Enter a number: ")) + if userGivenInput < gloal_lucky_number: + raise ValueTooSmallError + elif userGivenInput > gloal_lucky_number: + raise ValueTooLargeError + break + except ValueTooSmallError: + print("This value is too small, try again!") + print() + except ValueTooLargeError: + print("This value is too large, try again!") + print() + except RamsZeroDivisionError: + print("Sory I cannot divide by Zero!") + raise(RamsException1010("Error message")) + +print("Congratulations! You guessed it correctly.") + + +# Q & A ? + + +''' +Here's the overall predefined exception tree structure. + +BaseException + +-- SystemExit + +-- KeyboardInterrupt + +-- GeneratorExit + +-- Exception + +-- StopIteration + +-- StandardError + | +-- BufferError + | +-- ArithmeticError + | | +-- FloatingPointError + | | +-- OverflowError + | | +-- ZeroDivisionError + | +-- AssertionError + | +-- AttributeError + | +-- EnvironmentError + | | +-- IOError + | | +-- OSError + | | +-- WindowsError (Windows) + | | +-- VMSError (VMS) + | +-- EOFError + | +-- ImportError + | +-- LookupError + | | +-- IndexError + | | +-- KeyError + | +-- MemoryError + | +-- NameError + | | +-- UnboundLocalError + | +-- ReferenceError + | +-- RuntimeError + | | +-- NotImplementedError + | +-- SyntaxError + | | +-- IndentationError + | | +-- TabError + | +-- SystemError + | +-- TypeError + | +-- ValueError + | +-- UnicodeError + | +-- UnicodeDecodeError + | +-- UnicodeEncodeError + | +-- UnicodeTranslateError + +-- Warning + +-- DeprecationWarning + +-- PendingDeprecationWarning + +-- RuntimeWarning + +-- SyntaxWarning + +-- UserWarning + +-- FutureWarning + +-- ImportWarning + +-- UnicodeWarning + +-- BytesWarning +''' \ No newline at end of file diff --git a/ExceptionalHandling/__pycache__/three.cpython-37.pyc b/ExceptionalHandling/__pycache__/three.cpython-37.pyc new file mode 100644 index 0000000..24efa04 Binary files /dev/null and b/ExceptionalHandling/__pycache__/three.cpython-37.pyc differ diff --git a/ExceptionalHandling/__pycache__/two.cpython-37.pyc b/ExceptionalHandling/__pycache__/two.cpython-37.pyc new file mode 100644 index 0000000..0b46c49 Binary files /dev/null and b/ExceptionalHandling/__pycache__/two.cpython-37.pyc differ diff --git a/ExceptionalHandling/one.py b/ExceptionalHandling/one.py new file mode 100644 index 0000000..e11b35d --- /dev/null +++ b/ExceptionalHandling/one.py @@ -0,0 +1,22 @@ + +import two + + +def main(): + try: + # a = two.add(19, "a") + # if (a): + # print("success") + # return a + # else: + # print(a) + print("a"/22) + + except Exception as e: + print(e) + else: + print("sinside main functio") + finally: + print("done") + +main() \ No newline at end of file diff --git a/ExceptionalHandling/test.py b/ExceptionalHandling/test.py new file mode 100644 index 0000000..54874fd --- /dev/null +++ b/ExceptionalHandling/test.py @@ -0,0 +1,35 @@ +from collections import Counter + +# list1 = [1,2,2,2,4,4,4,4,4,4,4,4,'xyz', ['list1', 'list2'], {1:3, 2:4}] + +def convertDict1(list1): #Method 1 + try: + print("Hello") + myDict = {i:list1.count(i) for i in list1} + return myDict + except TypeError: + print("Something went wrong!") + +def convertDict2(list1): #Method 2 + myDict2 = dict(Counter(list1)) + return myDict2 + +def cleaningList1(list1): + dummyList = [] + for i in list1: + if type(i) == str or type(i) == int or isinstance(i, list): + dummyList.append(i) + else: + pass + return dummyList + +if __name__ == "__main__": + + #list1 = list(input("Enter something here:")) + list1 = [1,'xyz', ['list1', 'list2'], {1:3, 2:4}] + + firstLevel = cleaningList1(list1) + print(convertDict1(firstLevel)) + + # print(convertDict2(list1)) + # print(cleaningList1(list1)) \ No newline at end of file diff --git a/ExceptionalHandling/three.py b/ExceptionalHandling/three.py new file mode 100644 index 0000000..79f5ee5 --- /dev/null +++ b/ExceptionalHandling/three.py @@ -0,0 +1,9 @@ + + +def realAddition(a,b,c): + try: + print("inside real Addition") + return a+b+c + except Exception as e: + print(e) + return False \ No newline at end of file diff --git a/ExceptionalHandling/two.py b/ExceptionalHandling/two.py new file mode 100644 index 0000000..943aa90 --- /dev/null +++ b/ExceptionalHandling/two.py @@ -0,0 +1,10 @@ + +import three + +def add(a,b): + try: + print("inside two") + return three.realAddition(a,b, 100) + except Exception as e: + print(e) + return False \ No newline at end of file diff --git a/Excersise/ConverFloatPointNumberToDecimal.py b/Excersise/ConverFloatPointNumberToDecimal.py new file mode 100644 index 0000000..87e6a55 --- /dev/null +++ b/Excersise/ConverFloatPointNumberToDecimal.py @@ -0,0 +1,57 @@ +# Python program to convert float +# decimal to binary number + +# Function returns octal representation +def float_bin(number, places = 3): + + # split() seperates whole number and decimal + # part and stores it in two seperate variables + whole, dec = str(number).split(".") + + # Convert both whole number and decimal + # part from string type to integer type + whole = int(whole) + dec = int (dec) + + # Convert the whole number part to it's + # respective binary form and remove the + # "0b" from it. + res = bin(whole).lstrip("0b") + "." + + # Iterate the number of times, we want + # the number of decimal places to be + for x in range(places): + + # Multiply the decimal value by 2 + # and seperate the whole number part + # and decimal part + whole, dec = str((decimal_converter(dec)) * 2).split(".") + + # Convert the decimal part + # to integer again + dec = int(dec) + + # Keep adding the integer parts + # receive to the result variable + res += whole + + return res + +# Function converts the value passed as +# parameter to it's decimal representation +def decimal_converter(num): + while num > 1: + num /= 10 + return num + +# Driver Code + +# Take the user input for +# the floating point number +n = input("Enter your floating point value : \n") + +# Take user input for the number of +# decimal places user want result as +p = int(input("Enter the number of decimal places of the result : \n")) + +print(float_bin(n, places = p)) \ No newline at end of file diff --git a/Excersise/ConverFloatToDecimal.py b/Excersise/ConverFloatToDecimal.py new file mode 100644 index 0000000..87e6a55 --- /dev/null +++ b/Excersise/ConverFloatToDecimal.py @@ -0,0 +1,57 @@ +# Python program to convert float +# decimal to binary number + +# Function returns octal representation +def float_bin(number, places = 3): + + # split() seperates whole number and decimal + # part and stores it in two seperate variables + whole, dec = str(number).split(".") + + # Convert both whole number and decimal + # part from string type to integer type + whole = int(whole) + dec = int (dec) + + # Convert the whole number part to it's + # respective binary form and remove the + # "0b" from it. + res = bin(whole).lstrip("0b") + "." + + # Iterate the number of times, we want + # the number of decimal places to be + for x in range(places): + + # Multiply the decimal value by 2 + # and seperate the whole number part + # and decimal part + whole, dec = str((decimal_converter(dec)) * 2).split(".") + + # Convert the decimal part + # to integer again + dec = int(dec) + + # Keep adding the integer parts + # receive to the result variable + res += whole + + return res + +# Function converts the value passed as +# parameter to it's decimal representation +def decimal_converter(num): + while num > 1: + num /= 10 + return num + +# Driver Code + +# Take the user input for +# the floating point number +n = input("Enter your floating point value : \n") + +# Take user input for the number of +# decimal places user want result as +p = int(input("Enter the number of decimal places of the result : \n")) + +print(float_bin(n, places = p)) \ No newline at end of file diff --git a/Excersise/EvenNumEvenIndex_42.py b/Excersise/EvenNumEvenIndex_42.py new file mode 100644 index 0000000..2bdc028 --- /dev/null +++ b/Excersise/EvenNumEvenIndex_42.py @@ -0,0 +1,53 @@ +''' +Given a list of N numbers, use a single list comprehension to produce a new list that only contains those values that are: +(a) even numbers, and +(b) from elements in the original list that had even indices +For example, if list[2] contains a value that is even, that value should be included in the new list, +since it is also at an even index (i.e., 2) in the original list. +However, if list[3] contains an even number, that number should not be included in the new list since +it is at an odd index (i.e., 3) in the original list. +''' + +def EvenNumEvenIndex(someList): + if type(someList) is not list: + print("Invalid user input") + if len(someList) == 0: + print("No value in the list") + + dummyList = [] + for num in someList: + if someList.index(num) %2 == 0 and num %2 == 0: + dummyList.append(int(num)) + return dummyList + + +def getUserInput(): + listOfIntNum = [] + listOfFloatNum = [] + + inputList = input("Enter list of nunmbers: ") + inputList = inputList.split(" ") + + if inputList: + for value in inputList: + if '.' in value: + # possible that, value can be a floating number or a sentence with full stop. + try: + if isinstance(float(value), float): + listOfFloatNum.append(float(value)) + continue + except ValueError as e: + pass + try: + if isinstance(int(value), int): + listOfIntNum.append(int(value)) + except ValueError as e: + pass + + + return listOfIntNum + listOfFloatNum + +if __name__ == "__main__": + numList = getUserInput() + print(numList) + print(EvenNumEvenIndex(numList)) \ No newline at end of file diff --git a/Excersise/FindNextGreaterElement.py b/Excersise/FindNextGreaterElement.py new file mode 100644 index 0000000..a157edc --- /dev/null +++ b/Excersise/FindNextGreaterElement.py @@ -0,0 +1,15 @@ +# Function to print element and NGE pair for all elements of list +def printNGE(arr): + for i in range(0, len(arr), 1): + next = -1 + for j in range(i + 1, len(arr), 1): + if arr[i] < arr[j]: + next = arr[j] + break + + print(str(arr[i]) + " -- " + str(next)) + + +# Driver program to test above function +arr = [11, 13, 21, 3] +printNGE(arr) \ No newline at end of file diff --git a/Excersise/GoldRate/GoldRate.py b/Excersise/GoldRate/GoldRate.py new file mode 100644 index 0000000..831c87d --- /dev/null +++ b/Excersise/GoldRate/GoldRate.py @@ -0,0 +1,137 @@ +print("Hello world") + +gold_rate = { + "24K" : { + "1g": "", + "8g": "" + }, + "22K": { + "1g": "", + "8g": "" + } +} + + +import requests +from datetime import date +from datetime import datetime +from bs4 import BeautifulSoup + + +URL = "https://www.livechennai.com/gold_silverrate.asp" +r = requests.get(URL) + +soup = BeautifulSoup(r.content, 'html5lib') + +table = soup.find('table', attrs = {'class':'table-price'}) + +tempData = table.get_text() + + +allData = list(tempData.split(" ")) + + +test_list1 = [i for i in allData if i] + +test_list = [i for i in test_list1 if i != '\n'] + +dateObj = date.today() + +todayDate = dateObj.strftime("%d") + "/" + dateObj.strftime("%B") + "/" + dateObj.strftime("%Y") + "\n" +todaysDateFormatToDB = dateObj.strftime("%Y")+'-'+dateObj.strftime("%m")+'-'+dateObj.strftime("%d") + +try: + indexValue = test_list.index(todayDate) +except Exception as ex: + print("Error Info: " + ex) + +# goldRate24_1gram = test_list[indexValue+1] + +gold_rate['24K']['1g'] = test_list[indexValue+1] +gold_rate['24K']['8g'] = test_list[indexValue+2] +gold_rate['22K']['1g'] = test_list[indexValue+3] +gold_rate['22K']['8g'] = test_list[indexValue+4] + +print("24K Gold - 1 Gram price is " + gold_rate['24K']['1g']) + +print("24K Gold - 8 Gram price is " + gold_rate['24K']['8g']) + +print("22K Gold - 1 Gram price is " + gold_rate['22K']['1g']) + +print("22K Gold - 8 Gram price is " + gold_rate['22K']['8g']) + +import time +#time.sleep(25) + +import mysql.connector +from mysql.connector import Error + +def connectToDB(): + try: + + connection = mysql.connector.connect(host='localhost', + database='world', + user='root', + password='root') + if connection.is_connected(): + db_Info = connection.get_server_info() + print("\nConnected to MySQL Server version ", db_Info) + cursor = connection.cursor() + cursor.execute("select database();") + record = cursor.fetchone() + print("\nYou're connected to database: ", record) + return connection + except Error as e: + print("Error while connecting to MySQL", e) + + +def insertRecord(con): + if con.is_connected(): + + sample = [] + sample.insert(0, todaysDateFormatToDB) + sample.insert(1, gold_rate['24K']['8g']) + sample.insert(2, gold_rate['24K']['1g']) + sample.insert(3, gold_rate['22K']['8g']) + sample.insert(4, gold_rate['22K']['1g']) + + # Check current time, act accordingly. + curremtTime = datetime.now() + curremtTime = curremtTime.strftime("%H:%M") + + if (curremtTime == "12:10"): + infoSource = "Scheduled Job" + else: + infoSource = "Manual Trigger" + + workingQuery = "INSERT INTO `world`.`daily_gold_rates` (`todays_date`, `twentyFour_carot_eight_grams`,`twentyFour_carot_one_gram`, `twentyTwo_carot_eight_grams`, `twentyTwo_carot_one_gram`, `info_source`, `info_landed_time` ) VALUES ('" + str(todaysDateFormatToDB) +"','"+ gold_rate['24K']['8g'] +"'," + "'"+gold_rate['24K']['1g']+ "'," + "'"+ gold_rate['22K']['8g'] +"',"+ "'" + gold_rate['22K']['1g'] +"','" + infoSource + "'," + "'" + curremtTime +"');" + + #something3 = "INSERT INTO `world`.`daily_gold_rates` (`todays_date`,`twentyFour_carot_eight_grams`,`twentyFour_carot_one_gram`,`twentyTwo_carot_eight_grams`,`twentyTwo_carot_one_gram`) VALUES (" + "'" + sample[0] +"'," + "'" + sample[1] + "','" + sample[2] + "','" + sample[3] +"','" + sample[4] +"');" + cursor = con.cursor() + cursor.execute(workingQuery) + con.commit() + print("\n",cursor.rowcount, "Record inserted successfully into Gold Rate table") + return True + +def disconnectDB(con): + if (con.is_connected()): + con.close() + print("MySQL connection is closed\n") + else: + print("We tried, but it seems your connection is in active state! However it must be already closed.\n") + +print("\nConnecting to your database..\n") +time.sleep(5) +connectionHook = connectToDB() +print("\ncollecting records to save..\n") +time.sleep(3) +insertData = insertRecord(connectionHook) +print("\nRecords are inserted in DB, can be used for Analytics purpose in future!\n") +time.sleep(5) + +diconnect = disconnectDB(connectionHook) + +time.sleep(10) +print("\nGood Bye!") + +time.sleep(3) \ No newline at end of file diff --git a/Excersise/GoldRate/Todo.txt b/Excersise/GoldRate/Todo.txt new file mode 100644 index 0000000..955ac93 --- /dev/null +++ b/Excersise/GoldRate/Todo.txt @@ -0,0 +1,12 @@ +1. Store not only date, but also time needs to be stored - Done +2. Implementation of graph. +3. ask user for date, wait for 10 seconds, within 10 seconds if user gives input as dd/mm/yyy then find the gold rate for that date and store that in DB +4. if user didn't give any input within 10 seconds, proceed finding gold rate for today's date, display it and store in DB +5. all hard coded values inside .py file should be in a separate config or constant file. +6. rename the file +7. during schedule task - always check wether existing date data is available in DB, if available, find it's source info, inform the user saying "record already exist in DB, user can check there if needed" //if record says manually triggered, then proceed finding gold rate and store in DB +8. if existing date data shows source info as "shceduled", then inform user data is already present in DB, ask yes or no, whether to store one more record in DB +9. Get Silver Rate as well +10. Get gold rates for gulf countries as well. +11. Get gold rates for US as well. +12. Refactor the Dubai/USA and India Data in a single function, passing URL as parameter. diff --git a/Excersise/RemoveDuplicateStrings.py b/Excersise/RemoveDuplicateStrings.py new file mode 100644 index 0000000..e391e7c --- /dev/null +++ b/Excersise/RemoveDuplicateStrings.py @@ -0,0 +1,25 @@ +from collections import OrderedDict + +# Function to remove all duplicates from string +# and order does not matter +def removeDupWithoutOrder(str): + + # set() --> A Set is an unordered collection + # data type that is iterable, mutable, + # and has no duplicate elements. + # "".join() --> It joins two adjacent elements in + # iterable with any symbol defined in + # "" ( double quotes ) and returns a + # single string + return "".join(set(str)) + +# Function to remove all duplicates from string +# and keep the order of characters same +def removeDupWithOrder(str): + return "".join(OrderedDict.fromkeys(str)) + +# Driver program +if __name__ == "__main__": + str = "geeksforgeeks" + print("Without Order = ",removeDupWithoutOrder(str)) + print("With Order = ",removeDupWithOrder(str)) \ No newline at end of file diff --git a/FruitStore/Bill.py b/FruitStore/Bill.py new file mode 100644 index 0000000..eacdcf5 --- /dev/null +++ b/FruitStore/Bill.py @@ -0,0 +1,12 @@ + + +class BillFormatter: + + def __init__(self, billMap): + self.billObj = billMap + + def generateBill(self): + for fruitName, price in self.billObj.items(): + print(fruitName + " - " + str(price)) + + print("Total Bill amount to pay " + str(sum(self.billObj.values())) + " Rupees \n") \ No newline at end of file diff --git a/FruitStore/FStore.py b/FruitStore/FStore.py new file mode 100644 index 0000000..d6155d7 --- /dev/null +++ b/FruitStore/FStore.py @@ -0,0 +1,88 @@ +import time, sys + +class Cart: + def __init__(self): + self.items = {} + + def addToCart(self,fruitName, quantity): + self.items[fruitName] = quantity + + def removeFromCart(self,itemindex): + self.items.pop(itemindex) + + def showCart(self): + return self.items + + +class FStore: + + def __init__(self, stock={}): + """ + Our constructor class that instantiates fruit store. + """ + self.stock = stock + + def displayStock(self): + """ + Displays the fruits currently available for purchase in the store. + """ + for fruits, quantity in self.stock.items(): + print("we have " + str(quantity) + " of " + fruits) + return '\n' + + def getStockFromStore(self): + return self.stock + + def listOfFruits(self): + op = {} + for key, value in self.stock.items(): + op[value['id']] = [key, value['price']] + return op + + def timeDelay(self): + self.time = time.sleep(5) + return self.time + + def callExit(self): + self.exit = sys.exit(0) + return self.exit + + def getFruitsIDs(self): + fID = [] + for key, value in self.stock.items(): + fID.append(value['id']) + return fID + + def getAvailableCountForFruit(self, fruitID): + for key,value in self.stock.items(): + if int(fruitID) in list(value.values()): + # print("availab count is ", list(value.values())[0] ) + return list(value.values())[0] + + def getFruitName(self, fruitID): + for fruitName,fruitInfo in self.stock.items(): + if int(fruitID) in list(fruitInfo.values()): + return fruitName + + def updateStock(self, fruitName, quantity): + fruitInfo = self.stock[fruitName] + fruitInfo['availableCount'] = fruitInfo['availableCount'] - quantity + # print(self.stock) + + def getFruitPrice(self, fruitName): + for fn, value in self.stock.items(): + if fruitName == fn: + return value['price'] + + def giveAvailableFruitsInStock(self): + op = [] + for fn, fInfo in self.stock.items(): + if fInfo['availableCount'] > 0: + op.append(fn) + return op + + def showAvailableFruits(self): + availableFruits = self.listOfFruits() + print("Here's the available fruits, happy purchasing\n") + for id, fruit in availableFruits.items(): + print(str(id) + " - " + fruit[0] + "(each " + fruit[0] + " cost " + str(fruit[1]) + " Rupees)") \ No newline at end of file diff --git a/FruitStore/UserHandler.py b/FruitStore/UserHandler.py new file mode 100644 index 0000000..da2dd30 --- /dev/null +++ b/FruitStore/UserHandler.py @@ -0,0 +1,112 @@ +from FStore import FStore, Cart +from Bill import BillFormatter + + +import json +def getAvilableStock(): + stockInfo = open(r"FruitStore\stock.json", "r") + return json.load(stockInfo) + +openStore = FStore(getAvilableStock()) +cartInstance = Cart() + +class StoreHandler: + def __init__(self): + openStore = FStore(getAvilableStock()) + userInstance = UserHandler() + + def showAvailableFruitsFromStore(self): + self.openStore.showAvailableFruits() + + def buyFruit(self, fruitId): + if int(fruitId) in self.openStore.getFruitsIDs(): + fruitCount = int(self.userInstance.getUserInput("numbers")) + if fruitCount <= self.openStore.getAvailableCountForFruit(fruitId): + cartInstance.addToCart(self.openStore.getFruitName(fruitId), fruitCount) + self.openStore.updateStock(openStore.getFruitName(fruitId), fruitCount) + + print(str(fruitCount) + " " +self.openStore.getFruitName(fruitId) + " added to your cart \n") + else: + print("The count you entered is either exceeding or we nearing out of stock soon") + else: + print("ID which's entered isn't matching with any fruits which we have!") + + + +class CartHandler: + def __init__(self): + cartHandlerInstance = Cart() + + def showCart(self): + return self.cartHandlerInstance.showCart() + + def checkOutCart(self): + billMap = {} + cartItems = self.cartHandlerInstance.showCart() + for fn,count in cartItems.items(): + fruitPrice = openStore.getFruitPrice(fn) + billMap[fn] = fruitPrice * count + + billInstance = BillFormatter(billMap) + billInstance.generateBill() + + + +class UserHandler: + def __init__(self): + pass + + def showMainMenu(self): + print(""" + 1. Show available fruits + 2. Buy Fruits + 3. Show Cart + 4. Checkout + 5. Exit + 6. Display available Stocks (only store admin can access) + """) + + def getUserInput(self, fromWhichMenu): + inputMessage = '' + if fromWhichMenu == "fromMainMenu": + inputMessage = "Please enter your choice : " + elif fromWhichMenu == "fruitMenu": + inputMessage = "Please enter your choice : " + elif fromWhichMenu == "numbers": + inputMessage = "how many you need? " + elif fromWhichMenu == "addMoreItems": + try: + choice = input("Do you want to add more items to your cart? Y or N ").strip() + if choice == "Y" or choice == "y" or choice == "yes" or choice == "YES": + return True + else: + return False + except ValueError: + print("That's not an int!") + elif fromWhichMenu == "adminStuff": + try: + choice = getpass.getpass("Enter admin password") + if choice == "admin123": + return True + else: + return False + except ValueError: + print("That's not a valid password!") + + try: + choice = input(inputMessage).strip() + except ValueError: + print("That's not an int!") + + return choice + + def mainMenuHandler(self, menuId): + if menuId == '1' or menuId == 1: + openStore.showAvailableFruits() + elif menuId == '2' or menuId == 2: + openStore.showAvailableFruits() + choice = self.getUserInput("fruitMenu") + storeHandlerInstance = StoreHandler().buyFruit(choice) + # buyFruit(choice) + elif menuId == '4' or menuId == 4: + CartHandler.checkOutCart() diff --git a/FruitStore/__init__.py b/FruitStore/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/FruitStore/__pycache__/Bill.cpython-37.pyc b/FruitStore/__pycache__/Bill.cpython-37.pyc new file mode 100644 index 0000000..a64d07d Binary files /dev/null and b/FruitStore/__pycache__/Bill.cpython-37.pyc differ diff --git a/FruitStore/__pycache__/FStore.cpython-37.pyc b/FruitStore/__pycache__/FStore.cpython-37.pyc new file mode 100644 index 0000000..4770700 Binary files /dev/null and b/FruitStore/__pycache__/FStore.cpython-37.pyc differ diff --git a/FruitStore/__pycache__/UserHandler.cpython-37.pyc b/FruitStore/__pycache__/UserHandler.cpython-37.pyc new file mode 100644 index 0000000..d918411 Binary files /dev/null and b/FruitStore/__pycache__/UserHandler.cpython-37.pyc differ diff --git a/FruitStore/__pycache__/log.cpython-37.pyc b/FruitStore/__pycache__/log.cpython-37.pyc new file mode 100644 index 0000000..f862d9d Binary files /dev/null and b/FruitStore/__pycache__/log.cpython-37.pyc differ diff --git a/FruitStore/log.py b/FruitStore/log.py new file mode 100644 index 0000000..f24f44b --- /dev/null +++ b/FruitStore/log.py @@ -0,0 +1,17 @@ +import logging +logging.basicConfig(filename="GLOBAL_LOG.log", + format='%(asctime)s %(message)s', + datefmt='%m/%d/%Y %I:%M:%S %p') +class Log: + + def registerInfo(msg): + logging.info(msg) + + def registerWarning(warningMsg): + logging.warning(warningMsg) + + def registerError(errorMsg): + logging.error(errorMsg) + + def registerCritical(criticalMsg): + logging.critical(criticalMsg) \ No newline at end of file diff --git a/FruitStore/main.py b/FruitStore/main.py new file mode 100644 index 0000000..bf4cc7b --- /dev/null +++ b/FruitStore/main.py @@ -0,0 +1,161 @@ +from FStore import FStore +from FStore import Cart +from log import Log +import time +import getpass +import logging +import json +logging.basicConfig(filename="general.log", + format='%(asctime)s %(message)s', + datefmt='%m/%d/%Y %I:%M:%S %p') + +def getAvilableStock(): + stockInfo = open(r"FruitStore\stock.json", "r") + logging.warning("1.0 Stock Downloaded") + Log.registerWarning("Stock downloaded ....... :)") + return json.load(stockInfo) + +openStore = FStore(getAvilableStock()) +cartInstance = Cart() + + +def getUserInput(fromWhichMenu): + inputMessage = '' + if fromWhichMenu == "fromMainMenu": + inputMessage = "Please enter your choice : " + elif fromWhichMenu == "fruitMenu": + inputMessage = "Please enter fruit id : " + elif fromWhichMenu == "numbers": + inputMessage = "how many you need? " + elif fromWhichMenu == "addMoreItems": + try: + choice = input("Do you want to add more items to your cart? Y or N ").strip() + if choice == "Y" or choice == "y" or choice == "yes" or choice == "YES": + return True + else: + return False + except ValueError: + print("That's not an int!") + elif fromWhichMenu == "adminStuff": + try: + choice = getpass.getpass("Enter admin password") + if choice == "admin123": + return True + else: + return False + except ValueError: + print("That's not a valid password!") + + try: + choice = input(inputMessage).strip() + except ValueError: + print("That's not an int!") + + logging.warning("User Action: " + choice) + return choice + + + +def displayMainMenu(): + logging.warning("Displayed Main Menu to the user!") + print(""" + 1. Show available fruits + 2. Buy Fruits + 3. Show Cart + 4. Checkout + 5. Exit + 6. Display available Stocks (only store admin can access) + """) + +def addMoreItems(): + if (getUserInput("addMoreItems")): + displayFruitMenu() + choice = getUserInput("fruitMenu") + return choice + else: + print("purchase done") + + +def displayFruitMenu(): + for i in enumerate(openStore.listOfFruits(), start=1): + print(i[0], i[1]) + +def billFormat(billObj): + for fruitName, price in billObj.items(): + print(fruitName + " - " + str(price)) + + print("Total Bill amount to pay " + str(sum(billObj.values())) + " Rupees \n") + logging.warning("Total Bill amount to pay " + str(sum(billObj.values())) + " Rupees \n") + + +def checkOutCart(): + billMap = {} + cartItems = cartInstance.showCart() + logging.warning("Checking out items from cart - " + str(cartItems) + " in cart") + for fn,count in cartItems.items(): + fruitPrice = openStore.getFruitPrice(fn) + billMap[fn] = fruitPrice * count + logging.warning("Preparing bill..") + billFormat(billMap) + +def showAvailableFruits(): + availableFruits = openStore.listOfFruits() + print("Here's the available fruits, happy purchasing\n") + for id, fruit in availableFruits.items(): + print(str(id) + " - " + fruit[0] + "(each " + fruit[0] + " cost " + str(fruit[1]) + " Rupees)") + +def buyFruit(fruitId): + if fruitId == '': + return 0 + if int(fruitId) in openStore.getFruitsIDs(): + fruitCount = int(getUserInput("numbers")) + if fruitCount <= openStore.getAvailableCountForFruit(fruitId): + cartInstance.addToCart(openStore.getFruitName(fruitId), fruitCount) + openStore.updateStock(openStore.getFruitName(fruitId), fruitCount) + + print(str(fruitCount) + " " +openStore.getFruitName(fruitId) + " added to your cart \n") + logging.warning(str(fruitCount) + " " +openStore.getFruitName(fruitId) + " added to your cart") + else: + print("The count you entered is either exceeding or we nearing out of stock soon") + else: + print("ID which's entered isn't matching with any fruits which we have!") + + +if __name__ == "__main__": + + while True: + displayMainMenu() + userChoice = getUserInput("fromMainMenu") + + if userChoice == '1': + showAvailableFruits() + elif userChoice == '2': + showAvailableFruits() + choice = getUserInput("fruitMenu") + buyFruit(choice) + if(getUserInput("addMoreItems")): + for i in range(len(openStore.giveAvailableFruitsInStock())): + showAvailableFruits() + choice = getUserInput("fruitMenu") + buyFruit(choice) + else: + displayFruitMenu() + elif userChoice == '3': + cartItems = cartInstance.showCart() + print("Currently you have below items in your cart, ") + logging.warning("Showing cart to user, available item/s is/are - " + str(cartItems)) + for itemName, itemCount in cartItems.items(): + print(itemName + "-" + str(itemCount)) + time.sleep(7) + elif userChoice == '4': + checkOutCart() + print("Enjoy Shopping at Ram's Fruit Store!\n") + break + elif userChoice == '5': + break + elif userChoice == '6': + if(getUserInput("adminStuff")): + openStore.displayStock() + break + else: + print("Invalid input. Please enter number between 1-6 ") \ No newline at end of file diff --git a/FruitStore/scoring.py b/FruitStore/scoring.py new file mode 100644 index 0000000..88f8ace --- /dev/null +++ b/FruitStore/scoring.py @@ -0,0 +1,29 @@ +# if __name__ == '__main__': +# n = int(input()) +# student_marks = {} +# for _ in range(n): +# name, *line = input().split() +# scores = list(map(float, line)) +# student_marks[name] = scores +# query_name = input() +# # what if query name value doesn't exist in student_marks? + +# if query_name in student_marks.keys(): +# studentScore = student_marks[query_name] +# print(sum(studentScore)/ len(studentScore)) +# else: +# print("student name not exist") + + +import textwrap + +def wrap(string, max_width): + emptyList= [] + for i in range(0,len(string),max_width): + emptyList.append(string[i:i+max_width]) + return "\n".join(emptyList) + +if __name__ == '__main__': + string, max_width = input(), int(input()) + result = wrap(string, max_width) + print(result) \ No newline at end of file diff --git a/FruitStore/stock.json b/FruitStore/stock.json new file mode 100644 index 0000000..3d3d6fe --- /dev/null +++ b/FruitStore/stock.json @@ -0,0 +1,22 @@ +{ + "Apple": { + "availableCount": 100, + "id" : 1001, + "price": 12 + }, + "Banana": { + "availableCount": 67, + "id" : 1002, + "price": 15 + }, + "Cherry": { + "availableCount": 23, + "id" : 1005, + "price": 30 + }, + "orange": { + "availableCount": 76, + "id" : 1009, + "price": 10 + } + } \ No newline at end of file diff --git a/FruitStore/userMenu.txt b/FruitStore/userMenu.txt new file mode 100644 index 0000000..e69de29 diff --git a/GLOBAL_LOG.log b/GLOBAL_LOG.log new file mode 100644 index 0000000..0933620 --- /dev/null +++ b/GLOBAL_LOG.log @@ -0,0 +1,79 @@ +11/20/2020 11:44:33 PM 1.0 Stock Downloaded +11/20/2020 11:44:33 PM Displayed Main Menu to the user! +11/20/2020 11:44:39 PM User Action: 1 +11/20/2020 11:44:39 PM Displayed Main Menu to the user! +11/20/2020 11:44:42 PM User Action: +11/20/2020 11:44:42 PM Displayed Main Menu to the user! +11/20/2020 11:44:43 PM User Action: +11/20/2020 11:44:43 PM Displayed Main Menu to the user! +11/20/2020 11:44:43 PM User Action: +11/20/2020 11:44:43 PM Displayed Main Menu to the user! +11/20/2020 11:44:43 PM User Action: +11/20/2020 11:44:43 PM Displayed Main Menu to the user! +11/20/2020 11:44:44 PM User Action: +11/20/2020 11:44:44 PM Displayed Main Menu to the user! +11/20/2020 11:44:44 PM User Action: +11/20/2020 11:44:44 PM Displayed Main Menu to the user! +11/20/2020 11:44:44 PM User Action: +11/20/2020 11:44:44 PM Displayed Main Menu to the user! +11/20/2020 11:44:44 PM User Action: +11/20/2020 11:44:44 PM Displayed Main Menu to the user! +11/20/2020 11:45:50 PM 1.0 Stock Downloaded +11/20/2020 11:45:50 PM Stock downloaded ....... :) +11/20/2020 11:45:50 PM Displayed Main Menu to the user! +11/20/2020 11:46:00 PM User Action: 1 +11/20/2020 11:46:00 PM Displayed Main Menu to the user! +01/16/2021 12:53:22 AM 1.0 Stock Downloaded +01/16/2021 12:53:22 AM Stock downloaded ....... :) +01/16/2021 12:53:22 AM Displayed Main Menu to the user! +01/16/2021 12:53:29 AM User Action: 1 +01/16/2021 12:53:29 AM Displayed Main Menu to the user! +01/16/2021 12:53:34 AM User Action: 1002 +01/16/2021 12:53:34 AM Displayed Main Menu to the user! +01/16/2021 12:53:35 AM User Action: 5 +01/16/2021 12:54:02 AM 1.0 Stock Downloaded +01/16/2021 12:54:02 AM Stock downloaded ....... :) +01/16/2021 12:54:02 AM Displayed Main Menu to the user! +01/16/2021 12:54:11 AM User Action: 1 +01/16/2021 12:54:11 AM Displayed Main Menu to the user! +01/16/2021 12:54:14 AM User Action: 2 +01/16/2021 12:54:16 AM User Action: 1002 +01/16/2021 12:54:18 AM User Action: 6 +01/16/2021 12:54:18 AM 6 Banana added to your cart +01/16/2021 12:54:31 AM Displayed Main Menu to the user! +01/16/2021 12:54:34 AM User Action: 3 +01/16/2021 12:54:34 AM Showing cart to user, available item/s is/are - {'Banana': 6} +01/16/2021 12:54:41 AM Displayed Main Menu to the user! +01/16/2021 12:54:44 AM User Action: 4 +01/16/2021 12:54:44 AM Checking out items from cart - {'Banana': 6} in cart +01/16/2021 12:54:44 AM Preparing bill.. +01/16/2021 12:54:44 AM Total Bill amount to pay 90 Rupees + +05/19/2021 08:28:11 PM 1.0 Stock Downloaded +05/19/2021 08:28:11 PM Stock downloaded ....... :) +05/19/2021 08:28:11 PM Displayed Main Menu to the user! +05/19/2021 08:28:30 PM User Action: 1 +05/19/2021 08:28:30 PM Displayed Main Menu to the user! +05/19/2021 08:28:35 PM User Action: 2 +05/19/2021 08:28:49 PM User Action: 1001 +05/19/2021 08:28:51 PM User Action: 5 +05/19/2021 08:28:51 PM 5 Apple added to your cart +05/19/2021 08:28:59 PM User Action: 1009 +05/19/2021 08:29:01 PM User Action: 3 +05/19/2021 08:29:01 PM 3 orange added to your cart +05/19/2021 08:29:16 PM User Action: 1009 +05/19/2021 08:29:18 PM User Action: 2 +05/19/2021 08:29:18 PM 2 orange added to your cart +05/19/2021 08:29:19 PM User Action: +05/19/2021 08:29:20 PM User Action: +05/19/2021 08:29:20 PM Displayed Main Menu to the user! +05/19/2021 08:29:24 PM User Action: 3 +05/19/2021 08:29:24 PM Showing cart to user, available item/s is/are - {'Apple': 5, 'orange': 2} +05/19/2021 08:29:31 PM Displayed Main Menu to the user! +05/19/2021 08:29:31 PM User Action: +05/19/2021 08:29:31 PM Displayed Main Menu to the user! +05/19/2021 08:29:35 PM User Action: 4 +05/19/2021 08:29:35 PM Checking out items from cart - {'Apple': 5, 'orange': 2} in cart +05/19/2021 08:29:35 PM Preparing bill.. +05/19/2021 08:29:35 PM Total Bill amount to pay 80 Rupees + diff --git a/Introduction/PrintSpeciality.py b/Introduction/PrintSpeciality.py deleted file mode 100644 index cc40e0a..0000000 --- a/Introduction/PrintSpeciality.py +++ /dev/null @@ -1,64 +0,0 @@ -__author__ = 'Sanjay' -# In Python 2, the default print is a simple IO method that doesn't give many options to play around with. -# -# The following two examples will summarize it. -# -# Example 1: -# -# var, var1, var2 = 1,2,3 -# print var -# print var1, var2 -# Prints two lines and, in the second line, var1var1 and var2var2 are separated by a single space. -# -# Example 2: -# -# for i in xrange(10): -# print i, -# Prints each element separated by space on a single line. Removing the comma at the end will print each element on a new line. -# -# Let's import the advanced print_function from the __future__ module. -# -# Its method signature is below: -# -# print(value, ..., sep=' ', end='\n', file=sys.stdout) -# 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. -# -# The argument definitions are below: -# sep defines the delimiter between the values. -# end defines what to print after the values. -# file defines the output stream. -# -# Interesting, isn't it? -# -# Task -# Read an integer NN. -# -# Without using any string methods, try to print the following: -# -# 1,2,3.....N1,2,3.....N -# -# Note that "....." represents the values in between. -# -# Input Format -# The first line contains an integer NN. -# -# Output Format -# Output the answer as explained in the task. -# -# Sample Input -# -# 3 -# Sample Output -# -# 123 -# Pro Tip -# You can use the print function inside a map(). Can you do a 11 line code to solve the problem above? - -# Enter your code here. Read input from STDIN. Print output to STDOUT -from __future__ import print_function -a = int(raw_input()) -s = [] -for i in range(1, (a+1)): - s.append(i) -print(int("".join(str(x) for x in s))) - diff --git a/Iterator/What.py b/Iterator/What.py new file mode 100644 index 0000000..bfb345f --- /dev/null +++ b/Iterator/What.py @@ -0,0 +1,91 @@ +''' +Iterators are everywhere in Python. + +They are implemented within for loops, comprehensions, generators etc. but are hidden in plain sight. + +Points to remember, +1. If a variable is called then it means it has values inside to iterate upon. +2. two special methods are __iter__() and __next__() - called as iterator protocol. +3. An object can be called iterator only when it's iterable. +''' + + +# As mentioned in 3rd point + +sampleEmployees = ['ram', 'sanjay', 'london', 'chennai'] +# Now above sampleEmployees is a list variable, right? print(type(sampleEmployees)) + +# Is it iterable? Yes - Because it has bunch of elements to bring them out. isn't it? +# How do we iterate? We normally go on "FOR" loop. + +# Creating iterator object now, +sampleEmployees = iter(sampleEmployees) +print(sampleEmployees) # this tell you that, it's + +# for i in sampleEmployees: +# print(i) + + +# Iterating Through an Iterator +# We use the next() function to manually iterate through all the items of an iterator. +# When we reach the end and there is no more data to be returned, it will raise the StopIteration Exception. + +sampleNum = [1,2,3] +iterSampleNump = iter(sampleNum) + +print(next(iterSampleNump)) +print(next(iterSampleNump)) +print(next(iterSampleNump)) + +print(next(iterSampleNump)) # this will throw you a stop iteation error + + +# You may ask a question, how different is this? for loop does the same. isn't it? + +# for item in iterable: + # add anything as per the need.. + +# Can you think how this above `for` loop is implemented internally. + +# create an iterator object from that iterable +iter_obj = iter(iterable) + +# infinite loop +while True: + try: + # get the next item + element = next(iter_obj) + # do something with element + except StopIteration: + # if StopIteration is raised, break from loop + break + + +# So internally, the for loop creates an iterator object, iter_obj by calling iter() on the iterable. + +# Ironically, this for loop is actually an infinite while loop. + +# Inside the loop, it calls next() to get the next element and executes the body of the for loop with this value. +# After all the items exhaust, StopIteration is raised which is internally caught and the loop ends. +# Note that any other kind of exception will pass through. + + + +# Have you ever thought? why to make an iterator ? + +# Iterators allow you to make an iterable that computes its items as it goes. +# means that you can make iterables that are lazy, in that they don’t determine what their next item is until you ask them for it. + + +# Usage of iterator instead of a list, set, or another iterable data structure can sometimes allow us to save memory + + +# Can you convert a non-iterable object into iterator? + +sampleInt = 90 + +# print(iter(sampleInt)) +# Exception has occurred: TypeError +# 'int' object is not iterable + +# NO \ No newline at end of file diff --git a/Lambda/WhatIsLambda.py b/Lambda/WhatIsLambda.py new file mode 100644 index 0000000..0f273f4 --- /dev/null +++ b/Lambda/WhatIsLambda.py @@ -0,0 +1,77 @@ + + +def squareNumber(n): + if type(n) == int: + return n*n + else: + return 0 + +def checkForEven(n): + if type(n) is not int: + return + return n%2 ==0 + +def add(x, y): + return x+y +print(squareNumber(10)) + +# if you want to pass a list as a parameter, then will the above function (add()) block will support? + +# NO + +sampleList =[1,2,3,4,5] +outputList = [] +for i in sampleList: + outputList.append(squareNumber(i)) + +print(outputList) + + +outputList2 = [] +for i in sampleList: + if checkForEven(i): + outputList2.append(i) +print("output list 2 is ", outputList2) +# =================================================== + +evenNum = list(filter(lambda x: x%2 ==0, sampleList)) +print(evenNum) + + +sqNum = list(map(squareNumber, sampleList)) +print("sqNum is .. ", sqNum) + +globalExample = map(lambda x, y: (x+y, x-y, x*y), [10, 20, 30, 40],[5,10,15,20]) +globalExample = map(lambda x, y: (x+y, x-y, x*y), [10, 20, 30, 40],[5,10,15,20]) +print(list(globalExample)) + + + + + +# List of strings +l = ['sat', 'bat', 'cat', 'mat'] + +opList = [] +for i in l: + opList.append(list(i)) +print(opList) + +map(list, l) + + + +# class calculator: +# add = lambda x,y: x+y +# sub = lambda x,y: x-y +# mul = lambda x,y: x*y + +# def add(a,b): +# return a+b + +# print("here you go ...") + +# cal = calculator() + +# print(calculator.add(10,5)) + diff --git a/Lambda/timecomplexity.py b/Lambda/timecomplexity.py new file mode 100644 index 0000000..3aaa75c --- /dev/null +++ b/Lambda/timecomplexity.py @@ -0,0 +1,35 @@ +import operator +import time + +# Defining lists +L1 = [1, 2, 3] +L2 = [2, 3, 4] + +# Starting time before map +# function +t1 = time.time() + +# Calculating result +a, b, c = map(operator.mul, L1, L2) + +# Ending time after map +# function +t2 = time.time() + +# Time taken by map function +print("Result:", a, b, c) +print("Time taken by map function: %.6f" %(t2 - t1)) + +# Starting time before naive +# method +t1 = time.time() + +# Calculating result usinf for loop +print("Result:", end = " ") +for i in range(3): + print(L1[i] * L2[i], end = " ") + +# Ending time after naive +# method +t2 = time.time() +print("\nTime taken by for loop: %.6f" %(t2 - t1)) \ No newline at end of file diff --git a/Introduction/ArithmeticOperators.py b/MathOperationAndLoops/ArithmeticOperators.py similarity index 73% rename from Introduction/ArithmeticOperators.py rename to MathOperationAndLoops/ArithmeticOperators.py index 4a09216..c8ad09b 100644 --- a/Introduction/ArithmeticOperators.py +++ b/MathOperationAndLoops/ArithmeticOperators.py @@ -42,10 +42,13 @@ # 3?2?13?2?1 # 3?2?6 -# Enter your code here. Read input from STDIN. Print output to STDOUT -a = int(raw_input()) -b = int(raw_input()) +if __name__ == '__main__': + a = int(input("Enter your first number: ")) + b = int(input("Enter your second number: ")) + if (a !='' or b != ''): + print("Addition of ",a, " and ", b, "is", a+b) + print("Subraction of ",a, " and ", b, "is", a-b) + print("Product of 1",a, " and ", b, "is", a*b) + + -print a+b -print a-b -print a*b \ No newline at end of file diff --git a/MathOperationAndLoops/BaiscForLoop.py b/MathOperationAndLoops/BaiscForLoop.py new file mode 100644 index 0000000..ee0bb89 --- /dev/null +++ b/MathOperationAndLoops/BaiscForLoop.py @@ -0,0 +1,49 @@ +__author__ = 'Sanjay' +# Loops are control structures that iterate over a range to perform a certain task. +# +# There are two kinds of loops in Python. +# +# A for loop: +# +for i in range(0,5): + print i +# And a while loop: +# +i = 0 +while i < 5: + print i + i+=1 +# 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]. +# +# Task +# Read an integer NN. For all non-negative integers i 0: + # for num in sampleList: + # counter += num # is same as to counter = counter + num + # return counter + + strList = [] + intList = [] + floatList = [] + for i in sampleList: + if type(i) is int: + intList.append(i) + elif type(i) is float: + floatList.append(i) + elif type(i) is str: + strList.append(i) + + if len(strList) > 0: + op = '' + for ele in strList: + op += ele + ' ' + print(op) + if (len(intList) > 0): + print(sum(intList)) + # same for float as well. + +test = productAdd(1,2,3,4,5,5,5454) +print(test) + +test2 = productAdd("sanjay", "kid1", "kid2") #sanjay kid1 kid2 +print(test2) + +test4 = productAdd("sanjay", 1, 3, 4, 45, "tets") +print(test4) + +# @dispatch(str, str, str) +# def addProduct(firstStr, secondStr, thirdStr): +# op = '' +# op += firstStr + secondStr + thirdStr +# return op + + +# test3 = addProduct("sanjay", "kid1", "kid2") diff --git a/OOP/Polymorphism/MethodOverloading_NotEfficient.py b/OOP/Polymorphism/MethodOverloading_NotEfficient.py new file mode 100644 index 0000000..d30d996 --- /dev/null +++ b/OOP/Polymorphism/MethodOverloading_NotEfficient.py @@ -0,0 +1,52 @@ +''' +1. Reason for not using class? + Because, +''' + +# Function to take multiple arguments +# *args is a list [1,2,3...] +def add(datatype, *args): + + # if datatype is int + # initialize answer as 0 + if datatype =='int': + answer = 0 + + # if datatype is str + # initialize answer as '' + if datatype =='str': + answer ='' + + # Traverse through the arguments + for x in args: + + # This will do addition if the + # arguments are int. Or concatenation + # if the arguments are str + answer = answer + x + + print(answer) + + +# Integer +add('int', 5, 6,101,203,4354,54,65,76,4,6567,87,554,65,734,34,45,56,767,778) + +# String +add('str', 'Hi ', 'Geeks', "ram", "all", 'the', 'best') + + +class sampleclass(): + + def __init__(self, *args): + self.x = args + + + def showMe(self): + print(self.x) + + +ramObj = sampleclass(10,20,30,'Sanjay') +ramObj.showMe() + + + diff --git a/OOP/Polymorphism/MethodOverriding.py b/OOP/Polymorphism/MethodOverriding.py index f9e1501..a9eccde 100644 --- a/OOP/Polymorphism/MethodOverriding.py +++ b/OOP/Polymorphism/MethodOverriding.py @@ -1,19 +1,60 @@ -class A(object): +class Father(): def __init__(self, a, b): self.a = a self.b = b - def m1(self): - print "inside A" + def role(self): + print("Father of two childres") -class B(A): + def occupation(self): + print("Father is working in Bank") - def __init__(self): + def travellingIn(self): + print("As a father, I use Audi Car to go office") + +class Mother(Father): + + def __init__(self,): print ("b constructor") - # def m1(self): - # print "inside b" + + def role(self): + print("Mother of Two childrens") + + def occupation(self): + print("Home maker") + + def whatCooking(self): + print("Mother is preparing Pasta!") + + +class Son(Father, Mother): + pass + +class Son(Mother): + pass + +# creating an object of mother. +instanceOfMother = Mother() + +instanceOfMother.role() + +instanceOfMother.occupation() + +instanceOfMother.whatCooking() + +instanceOfMother.travellingIn() + + +# creating an object of Father + +fatherInstance = Father(10,20) + +fatherInstance.role() + +fatherInstance.travellingIn() + +fatherInstance.occupation() -bb = B() -bb.m1() \ No newline at end of file +fatherInstance.whatCooking() ## this will throw error \ No newline at end of file diff --git a/Paramiko/__init__.py b/Paramiko/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Paramiko/paramiko.py b/Paramiko/paramiko.py new file mode 100644 index 0000000..50b72ef --- /dev/null +++ b/Paramiko/paramiko.py @@ -0,0 +1,52 @@ +# below code needs to be refactored to a bigger level + +import paramiko +from paramiko import AUTH_SUCCESSFUL, AUTH_FAILED +from paramiko import ( + SSHException, + AuthenticationException, + BadAuthenticationType, + PartialAuthentication, +) + +class CustomParamiko: + def __init__(self, hostname, username, paassword): + self.hostname = hostname + self.username = username + self.password = paassword + + def connectToHost(self): + try: + ssh_client=paramiko.SSHClient() + ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh_client.connect(hostname=self.hostname,username=self.username,password=self.password) + + return {AUTH_SUCCESSFUL: "Connected Successfully"} + except (SSHException, AuthenticationException, BadAuthenticationType) as e: + print(e.with_traceback) + return {AUTH_FAILED: "Failed to Connect"} + + def runCommand(self, commandToExecute): + if commandToExecute == '' or len(commandToExecute) == 0 : + raise Exception + try: + result = ssh_client.exec_command(commandToExecute) + return result + except Exception as e: + print(e) + + def downloadFileFromRemote(self, remoteFilePath, localFilePath): + ftp_client=ssh_client.open_sftp() + ftp_client.get(remoteFilePath,localFilePath) + # not sure do I need to close the connection or not. + ftp_client.close() + + def uploadFileFromLocal(self, localFilePath, remoteFilePath): + ftp_client=ssh.open_sftp() + ftp_client.put(localFilePath,remoteFilePath) + # not sure do I need to close the connection or not. + ftp_client.close() + + + def closeConnection(self): + ssh_client.close() diff --git a/QR/HelloWorldQR.png b/QR/HelloWorldQR.png new file mode 100644 index 0000000..3df8a62 Binary files /dev/null and b/QR/HelloWorldQR.png differ diff --git a/QR/HelloWorldQR.py b/QR/HelloWorldQR.py new file mode 100644 index 0000000..6253d92 --- /dev/null +++ b/QR/HelloWorldQR.py @@ -0,0 +1,6 @@ +import pyqrcode + +img = pyqrcode.create("Hello World") + +img.png("HelloWorldQR.png", scale=6) + diff --git a/QR/QR_Encode.py b/QR/QR_Encode.py new file mode 100644 index 0000000..ef28eda --- /dev/null +++ b/QR/QR_Encode.py @@ -0,0 +1,58 @@ + +# Hey in this file, we are going to explore about QR Code. + +# Now a days, it's common to people are scanning the QR Code in any shopping mall for the payment. +# In general, when you scan the code via QR Code Scanner/Reader - internally it reads the data in the code and do action accordingly. + +# Let's how to create/make a QR code - which internally has some text or data. + +# We'll be writing a program - Takes input from the user, construct a QR code in .png format - output of this execution should bring a QR code (which user data will be binding internally) + +# Using a Python Library called ```pyqrcode``` + +# Here's the steps for installing that library, + +# Windows +# 1. pip install pyqrcode +# 2. pip install pypng + + +import pyqrcode + +# firstLevelQRCode = pyqrcode.create("Hello World") # Hello world is the text which I'm appending to generate a QR Code. + +# when you try printing the img variable - QRCode(content=b'Hello World', error='H', version=2, mode='binary') +# means it gives QRCode object + +# print(type(firstLevelQRCode)) - + +# finalImage = firstLevelQRCode.png("HelloWorldQR.png", scale=6) # + +# print("Output would have generated") + +def takeInputFromUser(): + givenInput = input("Enter the data : ") + if givenInput: + print("As an output, you can expect a QR Code in .png format") + return givenInput + else: + print("Please input some data") + return None + +def getFileNameFromUser(): + import random + fileName = input("Enter the filename: ") + return fileName if fileName else str(random.randint(1,100)) + +def constructQR(): + infoFromUser = takeInputFromUser() + if(infoFromUser): + output = pyqrcode.create(infoFromUser) + fileName = getFileNameFromUser() + output.png(fileName + '.png', scale=6) + print(fileName + ".png file got generated and saved in your local.") + else: + takeInputFromUser() + +if __name__ == '__main__': + constructQR() \ No newline at end of file diff --git a/RE/BeginerLevel.py b/RE/BeginerLevel.py new file mode 100644 index 0000000..2b74a6e --- /dev/null +++ b/RE/BeginerLevel.py @@ -0,0 +1,322 @@ +''' +Ram, consider this file as beginer level tutorial kinda things. +you will learn about regular expressions (RegEx), and use Python's re module to work with RegEx (with the help of examples). + +A Regular Expression (RegEx) is a sequence of characters that defines a search pattern. + +''' +# below line a regex pattern +example_pattern = '^a...s$' + +# What can we do with this above pattern? +# What did you understand when you read this pattern? + +# Matching Patterns with example.. + +# Expression String Matched +# ^a...s$ abs No match + # alias Match + # abyss Match + # Alias No match + # An abacus No match + + +# Code Implementation example, + +import re # re is the pre-defined module that exist inside Python + +sample_test_string = 'Sanjay is conducting a session to Ram alias prrampalli who is residing in London' +sample_focused_string = "abs" + +# example_pattern = '^a...s$' + +result = re.match(example_pattern, sample_focused_string) +print(result) + +if result: + print("Search successful.") +else: + print("Search unsuccessful.") + + +# from the above example, we used re.match() to check string match, there're other method under re, those are, +# re.compile +# re.sub +# re.search +# re.findall +# re.split + +# To specify regular expressions, metacharacters are used. In the above example, ^ and $ are metacharacters + +''' +What is meta characters? + +Metacharacters are characters that are interpreted in a special way by a RegEx engine. Here's a list of metacharacters: + +[] . ^ $ * + ? {} () \ | + +''' + +# 1 - We can discuss about [] + +# Expression String Matched? +# [abc] a 1 match +# ac 2 matches +# Hey Jude No match +# abc de ca 5 matches + +# [abc] will match if the string you are trying to match contains any of the a, b or c. + +# You can also specify a range of characters using - inside square brackets. + +# [a-e] is the same as [abcde]. +# [1-4] is the same as [1234]. +# [0-39] is the same as [01239]. ** + +# You can complement (invert) the character set by using caret ^ symbol at the start of a square-bracket. + +# [^abc] means any character except a or b or c. +# [^0-9] means any non-digit character. + + + +# 2 - We can now discuss about . + +''' +. -> called as period + +A period matches any single character (except newline '\n'). + +Expression String Matched? +.. a No match + ac 1 match + acd 1 match + acde 2 matches (contains 4 characters) +''' + +# 3 - We can discuss about Carret. + +''' +^ - Caret + +The caret symbol ^ is used to check if a string starts with a certain character. + +Expression String Matched? +^a a 1 match + abc 1 match + bac No match +^ab abc 1 match + acb No match (starts with a but not followed by b) + +''' + +# 4 - We can look into $ + +''' +$ - Dollar + +The dollar symbol $ is used to check if a string ends with a certain character. + +Expression String Matched? +a$ a 1 match + formula 1 match + cab No match + ram No Match + ra 1 Match +''' + + +# 5 - Astriek or star + +''' +* - Star + +The star symbol * matches zero or more occurrences of the pattern left to it. + +Expression String Matched? +ma*n mn 1 match + man 1 match + maaan 1 match + main No match (a is not followed by n) + woman 1 match + ran No match + ram No Match + maen No Match + maaaaaaan 1 Match +''' + +# 6 - Plus +''' ++ - Plus + +The plus symbol + matches one or more occurrences of the pattern left to it. + +Expression String Matched? +ma+n mn No match (no a character) + man 1 match + maaan 1 match + main No match (a is not followed by n) + woman 1 match +''' + +# 7 - ? - Question Mark +''' +The question mark symbol ? matches zero or one occurrence of the pattern left to it. + +Expression String Matched? +ma?n mn 1 match + man 1 match + maaan No match (more than one a character) + main No match (a is not followed by n) + woman 1 match + maon No match + exmain No match +''' + + +# 8 - {} - Braces + +''' +Consider this code: {n,m}. This means at least n, and at most m repetitions of the pattern left to it. + +Expression String Matched? +[a-z]{2,3} abc dat No match + abc daat 1 match (at daat) + aabc daaat 2 matches (at aabc and daaat) + aabc daaaat 2 matches (at aabc and daaaat) + a No Match + aa 1 Match + aaaaaabb 1 Match + +Let's try one more example. This RegEx [0-9]{2, 4} matches at least 2 digits max as 4 digits + +Expression String Matched? +[0-9]{2,4} ab123csde 1 match (match at ab123csde) + 12 and 345673 3 matches (12, 3456, 73) + 1 and 2 No match +''' + +# 9. | - Alternation +''' +Vertical bar | is used for alternation (or operator). + +Expression String Matched? +a|b cde No match + ade 1 match (match at ade) + acdbea 3 matches (at acdbea) + +Here, a|b match any string that contains either a or b +''' +# 10 () - Group +''' +Parentheses () is used to group sub-patterns. For example, (a|b|c)xz match any string that matches either a or b or c followed by xz + +Expression String Matched? +(a|b|c)xz ab xz No match + abxz 1 match (match at abxz) + axz cabxz 2 matches (at axzbc cabxz) +''' + +# 11. \ - Backslash +''' +Backlash \ is used to escape various characters including all metacharacters. For example, + +\$a match if a string contains $ followed by a. Here, $ is not interpreted by a RegEx engine in a special way. + +If you are unsure if a character has special meaning or not, you can put \ in front of it. +This makes sure the character is not treated in a special way. + +Special Sequences +------------------- + +Special sequences make commonly used patterns easier to write. Here's a list of special sequences: + +\A - Matches if the specified characters are at the start of a string. + +Expression String Matched? +\A the the sun Match + In the sun No match + +\b - Matches if the specified characters are at the beginning or end of a word. + +Expression String Matched? +\bfoo football Match + a football Match + afootball No match + +foo\b the foo Match + the afoo test Match + the afootest No match + +\B - Opposite of \b. Matches if the specified characters are not at the beginning or end of a word. + +Expression String Matched? +\Bfoo football No match + a football No match + afootball Match + +foo\B the foo No match + the afoo test No match + the afootest Match + +\d - Matches any decimal digit. Equivalent to [0-9] + +Expression String Matched? +\d 12abc3 3 matches (at 12abc3) + Python No match + +\D - Matches any non-decimal digit. Equivalent to [^0-9] + +Expression String Matched? +\D 1ab34"50 3 matches (at 1ab34"50) + 1345 No match + +\s - Matches where a string contains any whitespace character. Equivalent to [ \t\n\r\f\v]. + +Expression String Matched? +\s Python RegEx 1 match + PythonRegEx No match + +\S - Matches where a string contains any non-whitespace character. Equivalent to [^ \t\n\r\f\v]. + +Expression String Matched? +\S a b 2 matches (at a b) + No match + +\w - Matches any alphanumeric character (digits and alphabets). Equivalent to [a-zA-Z0-9_]. By the way, underscore _ is also considered an alphanumeric character. + +Expression String Matched? +\w 12&": ;c 3 matches (at 12&": ;c) + %"> ! No match + + +\W - Matches any non-alphanumeric character. Equivalent to [^a-zA-Z0-9_] + +Expression String Matched? +\W 1a2%c 1 match (at 1a2%c) + Python No match + +\Z - Matches if the specified characters are at the end of a string. + +Expression String Matched? +Python\Z I like Python 1 match + I like Python Programming No match + Python is fun. No match + +Tip: To build and test regular expressions, you can use RegEx tester tools such as regex101. This tool not only helps you in creating regular expressions, but it also helps you learn it. + +Now you understand the basics of RegEx, let's discuss how to use RegEx in your Python code. +''' + + +# From the above features we went through, here's the list of exercise for you! + +# 1. Write a method(giveMeNumber) takes input as string, gives output as available numbers inside the give string. + +# Sample, +# givenInput = "hey my phone number starts with 91 as country code, then my 10 digit # continues - 9944294841" + +# giveMeNumber(givenInput) #[91, 10, 9944294841] + + +# 2. \ No newline at end of file diff --git a/RE/trail.py b/RE/trail.py new file mode 100644 index 0000000..6f4411a --- /dev/null +++ b/RE/trail.py @@ -0,0 +1,12 @@ + + + +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" + +import sys + +totalN = len(sys.argv) + + +for i in range(1,totalN): + print("Hey arguments passed by user", sys.argv[i]) diff --git a/Sorting/BubbleSort.py b/Sort/BubbleSort.py similarity index 100% rename from Sorting/BubbleSort.py rename to Sort/BubbleSort.py diff --git a/Sorting/InsertionSort.py b/Sort/InsertionSort.py similarity index 100% rename from Sorting/InsertionSort.py rename to Sort/InsertionSort.py diff --git a/Sorting/MergeSort.py b/Sort/MergeSort.py similarity index 83% rename from Sorting/MergeSort.py rename to Sort/MergeSort.py index 0b991f7..d3cf9e7 100644 --- a/Sorting/MergeSort.py +++ b/Sort/MergeSort.py @@ -1,5 +1,8 @@ __author__ = 'Sanjay' +# Merge sort is a very efficient sorting algorithm. +# It’s based on the divide-and-conquer approach, a powerful algorithmic technique used to solve complex problems. + def mergeSort(alist): print("Splitting ",alist) if len(alist)>1: diff --git a/Sorting/QuickSort.py b/Sort/QuickSort.py similarity index 100% rename from Sorting/QuickSort.py rename to Sort/QuickSort.py diff --git a/general.log b/general.log new file mode 100644 index 0000000..c0d4b13 --- /dev/null +++ b/general.log @@ -0,0 +1,212 @@ +11/09/2020 11:05:39 PM stock downloaded +11/09/2020 11:10:04 PM 1.0 Stock Downloaded +11/09/2020 11:10:04 PM Display Main Menu +11/09/2020 11:10:09 PM User Action: 1 +11/09/2020 11:10:19 PM Display Main Menu +11/09/2020 11:10:22 PM User Action: 2 +11/09/2020 11:10:24 PM User Action: 1001 +11/09/2020 11:10:25 PM User Action: 12 +11/09/2020 11:10:25 PM 12 Apple added to your cart + +11/09/2020 11:10:36 PM User Action: 1009 +11/09/2020 11:10:39 PM User Action: 75 +11/09/2020 11:10:39 PM 75 orange added to your cart + +11/09/2020 11:10:44 PM User Action: 1009 +11/09/2020 11:10:46 PM User Action: 1 +11/09/2020 11:10:46 PM 1 orange added to your cart + +11/09/2020 11:11:08 PM User Action: 1007 +11/09/2020 11:11:12 PM User Action: 1005 +11/09/2020 11:11:14 PM User Action: 12 +11/09/2020 11:11:15 PM 12 Cherry added to your cart + +11/09/2020 11:11:15 PM Display Main Menu +11/09/2020 11:11:18 PM User Action: 3 +11/09/2020 11:11:25 PM Display Main Menu +11/09/2020 11:15:38 PM 1.0 Stock Downloaded +11/09/2020 11:15:38 PM Display Main Menu +11/09/2020 11:15:48 PM User Action: 1 +11/09/2020 11:15:48 PM Display Main Menu +11/09/2020 11:15:49 PM User Action: 2 +11/09/2020 11:15:50 PM User Action: 1001 +11/09/2020 11:15:53 PM User Action: 15 +11/09/2020 11:15:53 PM 15 Apple added to your cart + +11/09/2020 11:15:56 PM User Action: 1009 +11/09/2020 11:15:58 PM User Action: 76 +11/09/2020 11:15:58 PM 76 orange added to your cart + +11/09/2020 11:16:11 PM User Action: 1005 +11/09/2020 11:16:15 PM User Action: 45 +11/09/2020 11:16:18 PM User Action: +11/16/2020 10:24:30 PM 1.0 Stock Downloaded +11/16/2020 10:24:30 PM Display Main Menu +11/16/2020 10:24:46 PM User Action: 1 +11/16/2020 10:24:46 PM Display Main Menu +11/16/2020 10:24:51 PM User Action: 2 +11/16/2020 10:24:53 PM User Action: 1001 +11/16/2020 10:24:57 PM User Action: 50 +11/16/2020 10:24:57 PM 50 Apple added to your cart + +11/16/2020 10:25:10 PM User Action: 1002 +11/16/2020 10:25:12 PM User Action: 12 +11/16/2020 10:25:12 PM 12 Banana added to your cart + +11/16/2020 10:25:25 PM User Action: 1005 +11/16/2020 10:25:26 PM User Action: 5 +11/16/2020 10:25:26 PM 5 Cherry added to your cart + +11/16/2020 10:25:34 PM User Action: 1009 +11/16/2020 10:25:36 PM User Action: 23 +11/16/2020 10:25:36 PM 23 orange added to your cart + +11/16/2020 10:25:52 PM User Action: +11/16/2020 10:26:59 PM 1.0 Stock Downloaded +11/16/2020 10:26:59 PM Display Main Menu +11/16/2020 10:27:24 PM User Action: 2 +11/16/2020 10:27:25 PM User Action: 1001 +11/16/2020 10:27:26 PM User Action: 50 +11/16/2020 10:27:26 PM 50 Apple added to your cart + +11/16/2020 10:27:31 PM User Action: 1002 +11/16/2020 10:27:32 PM User Action: 12 +11/16/2020 10:27:32 PM 12 Banana added to your cart + +11/16/2020 10:27:35 PM User Action: 1005 +11/16/2020 10:27:36 PM User Action: 5 +11/16/2020 10:27:36 PM 5 Cherry added to your cart + +11/16/2020 10:27:41 PM User Action: n +11/16/2020 10:27:50 PM 1.0 Stock Downloaded +11/16/2020 10:27:50 PM Display Main Menu +11/16/2020 10:27:56 PM User Action: 2 +11/16/2020 10:27:57 PM User Action: 1001 +11/16/2020 10:28:02 PM User Action: 20 +11/16/2020 10:28:02 PM 20 Apple added to your cart + +11/16/2020 10:28:06 PM User Action: 1002 +11/16/2020 10:28:08 PM User Action: 12 +11/16/2020 10:28:08 PM 12 Banana added to your cart + +11/16/2020 10:28:10 PM User Action: 1005 +11/16/2020 10:28:11 PM User Action: 5 +11/16/2020 10:28:11 PM 5 Cherry added to your cart + +11/16/2020 10:28:17 PM User Action: +11/16/2020 10:28:47 PM User Action: +11/16/2020 10:28:47 PM Display Main Menu +11/16/2020 10:28:59 PM User Action: 3 +11/16/2020 10:29:06 PM Display Main Menu +11/16/2020 10:29:08 PM User Action: 4 +11/16/2020 10:32:50 PM 1.0 Stock Downloaded +11/16/2020 10:32:50 PM Display Main Menu +11/16/2020 10:32:59 PM User Action: 2 +11/16/2020 10:33:01 PM User Action: 1001 +11/16/2020 10:33:03 PM User Action: 23 +11/16/2020 10:33:03 PM 23 Apple added to your cart + +11/16/2020 10:33:39 PM User Action: 1002 +11/16/2020 10:33:40 PM User Action: 12 +11/16/2020 10:33:40 PM 12 Banana added to your cart + +11/16/2020 10:33:46 PM User Action: 1005 +11/16/2020 10:33:48 PM User Action: 5 +11/16/2020 10:33:48 PM 5 Cherry added to your cart + +11/16/2020 10:33:53 PM User Action: 1009 +11/16/2020 10:33:54 PM User Action: 10 +11/16/2020 10:33:54 PM 10 orange added to your cart + +11/16/2020 10:34:00 PM User Action: +11/16/2020 10:34:00 PM Display Main Menu +11/16/2020 10:34:13 PM User Action: 3 +11/16/2020 10:34:20 PM Display Main Menu +11/16/2020 10:34:24 PM User Action: 4 +11/16/2020 10:34:24 PM User contains {'Apple': 23, 'Banana': 12, 'Cherry': 5, 'orange': 10} in cart +11/16/2020 10:34:24 PM Preparing bill.. +11/16/2020 10:34:24 PM Total Bill amount to pay 706 Rupees + +11/16/2020 10:40:24 PM 1.0 Stock Downloaded +11/16/2020 10:40:24 PM Display Main Menu +11/16/2020 10:40:26 PM User Action: 2 +11/16/2020 10:40:27 PM User Action: 1001 +11/16/2020 10:40:30 PM User Action: 30 +11/16/2020 10:40:30 PM 30 Apple added to your cart +11/16/2020 10:40:31 PM Display Main Menu +11/16/2020 10:41:11 PM User Action: 3 +11/16/2020 10:41:18 PM Display Main Menu +11/16/2020 10:41:19 PM User Action: 4 +11/16/2020 10:41:19 PM User contains {'Apple': 30} in cart +11/16/2020 10:41:19 PM Preparing bill.. +11/16/2020 10:41:19 PM Total Bill amount to pay 360 Rupees + +11/16/2020 10:42:44 PM 1.0 Stock Downloaded +11/16/2020 10:42:44 PM Display Main Menu +11/16/2020 10:42:47 PM User Action: 2 +11/16/2020 10:42:49 PM User Action: 1001 +11/16/2020 10:42:50 PM User Action: 20 +11/16/2020 10:42:50 PM 20 Apple added to your cart +11/16/2020 10:42:51 PM Display Main Menu +11/16/2020 10:42:52 PM User Action: 3 +11/16/2020 10:43:00 PM Display Main Menu +11/16/2020 10:43:20 PM 1.0 Stock Downloaded +11/16/2020 10:43:20 PM Display Main Menu +11/16/2020 10:43:25 PM User Action: 2 +11/16/2020 10:43:27 PM User Action: 1001 +11/16/2020 10:43:28 PM User Action: 20 +11/16/2020 10:43:28 PM 20 Apple added to your cart +11/16/2020 10:43:31 PM Display Main Menu +11/16/2020 10:43:33 PM User Action: 3 +11/16/2020 10:43:33 PM Showing cart to user, available item/s is/are - {'Apple': 20} +11/16/2020 10:43:40 PM Display Main Menu +11/16/2020 10:43:42 PM User Action: 4 +11/16/2020 10:43:42 PM User contains {'Apple': 20} in cart +11/16/2020 10:43:42 PM Preparing bill.. +11/16/2020 10:43:42 PM Total Bill amount to pay 240 Rupees + +11/16/2020 10:44:41 PM 1.0 Stock Downloaded +11/16/2020 10:44:41 PM Display Main Menu +11/16/2020 10:44:45 PM User Action: 2 +11/16/2020 10:44:46 PM User Action: 1001 +11/16/2020 10:44:47 PM User Action: 23 +11/16/2020 10:44:47 PM 23 Apple added to your cart +11/16/2020 10:44:57 PM User Action: 1002 +11/16/2020 10:44:59 PM User Action: 12 +11/16/2020 10:44:59 PM 12 Banana added to your cart +11/16/2020 10:45:01 PM User Action: +11/16/2020 10:45:02 PM User Action: +11/16/2020 10:45:03 PM User Action: +11/16/2020 10:45:03 PM Display Main Menu +11/16/2020 10:45:14 PM User Action: 3 +11/16/2020 10:45:14 PM Showing cart to user, available item/s is/are - {'Apple': 23, 'Banana': 12} +11/16/2020 10:45:21 PM Display Main Menu +11/16/2020 10:45:22 PM User Action: 4 +11/16/2020 10:45:22 PM Checking out items from cart - {'Apple': 23, 'Banana': 12} in cart +11/16/2020 10:45:22 PM Preparing bill.. +11/16/2020 10:45:22 PM Total Bill amount to pay 456 Rupees + +11/20/2020 11:15:07 PM 1.0 Stock Downloaded +11/20/2020 11:15:07 PM Display Main Menu +11/20/2020 11:15:11 PM User Action: 1 +11/20/2020 11:15:11 PM Display Main Menu +11/20/2020 11:15:19 PM User Action: 2 +11/20/2020 11:15:23 PM User Action: 1001 +11/20/2020 11:15:24 PM User Action: 5 +11/20/2020 11:15:24 PM 5 Apple added to your cart +11/20/2020 11:15:39 PM User Action: 1002 +11/20/2020 11:15:43 PM User Action: 6 +11/20/2020 11:15:43 PM 6 Banana added to your cart +11/20/2020 11:17:25 PM User Action: 1005 +11/20/2020 11:17:30 PM User Action: 25 +11/20/2020 11:17:39 PM User Action: +11/20/2020 11:17:40 PM User Action: +11/20/2020 11:17:40 PM Display Main Menu +11/20/2020 11:17:46 PM User Action: 3 +11/20/2020 11:17:46 PM Showing cart to user, available item/s is/are - {'Apple': 5, 'Banana': 6} +11/20/2020 11:17:53 PM Display Main Menu +11/20/2020 11:17:57 PM User Action: 4 +11/20/2020 11:17:57 PM Checking out items from cart - {'Apple': 5, 'Banana': 6} in cart +11/20/2020 11:17:57 PM Preparing bill.. +11/20/2020 11:17:57 PM Total Bill amount to pay 150 Rupees + diff --git a/input1.txt b/input1.txt new file mode 100644 index 0000000..879b100 --- /dev/null +++ b/input1.txt @@ -0,0 +1,6 @@ +Keys Values +h e +f r +t ['w', 'x'] +P ['d', 'c'] +l q diff --git a/itertools/itertools_product.py b/itertools/itertools_product.py index caa2dad..a2fe834 100644 --- a/itertools/itertools_product.py +++ b/itertools/itertools_product.py @@ -48,14 +48,41 @@ # 3 4 # Sample Output - # (1, 3) (1, 4) (2, 3) (2, 4) - firstInput = list(map(int, input().split())) secondInput = list(map(int, input().split())) - for i in list(product(firstInput, secondInput)): print(i, end="") + +# list1 = [1,2,3,4] +# list2 = ['Hello', 'world'] + +# opList= [] +# if len(list1) > len(list2): +# for i in list(range(0, len(list2))): +# print(str(list1[i]) + list2[i]) +# opList.append(str(list1[i]) + list2[i]) + +# diff = (len(list1) - len(list2) - 1) +# for i in list1[diff:]: +# opList.append(list1[i]) + +# print(opList) + + + +# op = [(1, 'Hello'), (2, 'World'), (3, None), (4, None)] +# op_2 = [(None, 'Hello'), (None, 'World'), (1, 'Hello'), (2, 'World')] + +# finalOp = [] + +# for i in op: +# firstEle = "" if i[0] == None else i[0] +# secEle = "" if i[1] == None else i[1] +# finalOp.append(str(firstEle) + secEle) + +# print(finalOp) + \ No newline at end of file diff --git a/itertools/what.py b/itertools/what.py new file mode 100644 index 0000000..7290d18 --- /dev/null +++ b/itertools/what.py @@ -0,0 +1,30 @@ +from itertools import repeat +lots_of_fours = repeat(4, times=100000) + +print(lots_of_fours) + +print(type(lots_of_fours)) + +# print(list(lots_of_fours)) + +# This iterator takes up 56 bytes of memory on my machine: + +import sys +sys.getsizeof(lots_of_fours) +# 56 +# An equivalent list of 100 million 4’s takes up many megabytes of memory: + +lots_of_fours = [4] * 100_000_000 +import sys +sys.getsizeof(lots_of_fours) + +# 800000064 +# 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: + +print(next(open('giant_log_file.txt'))) +# This is the first line in a giant file +# 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. + +# So iterators can save us memory, but iterators can sometimes save us time also. + +# 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. \ No newline at end of file diff --git a/test.json b/test.json new file mode 100644 index 0000000..d8670cd --- /dev/null +++ b/test.json @@ -0,0 +1,4 @@ +{"course": "python", "topic": "Python JSON"} +{"course": "python", "topic": "Python JSON"} +{"course": "python", "topic": "Python JSON"} +{"course": "python", "topic": "Python JSON"}