├── .idea └── vcs.xml ├── Basic ├── Comments.md ├── ConditionalStatementIfelse.md ├── ElseinLoop.md ├── FirstProgram.md ├── ForLoop.md ├── IdleShortcuts.md ├── Introduction.md ├── PIPIntroduction.md ├── UserInput.md ├── VariableAndDataTypes.md ├── WhileLoop.md ├── commentsinpython.py ├── datatype.py ├── indentation.md ├── indentation.py └── variable.py ├── Class ├── 1.BasicOfClass.py ├── 2.MethodsInClass.py ├── 3.DifferenceBetweenClassVariableAndInstanceVariable.py ├── 4.CreateAndFetchDocuments.py ├── 5.InheritanceInPythonClass.py ├── 6.MultilevelInheritance.py ├── 7.Multipleinheritance.py ├── Abstraction.md ├── AttributesandMethods.md ├── BasicOfInheritance.md ├── ClassesandObjects.md ├── Constructor class.md ├── DocStrings.md ├── Encapsulation.md ├── Hybridinheritance.md ├── InstanceandClassVariables.md ├── Methodoverriding.png ├── MultilevelInheritance.md ├── Polymorphism.md ├── SingleInheritance.md ├── abstractclasses.png ├── hybridinheritance.png ├── methodOverloading.png ├── multilevelinheritance.png ├── multipleinheritance.md ├── multipleinheritance.png └── singleinheritance.png ├── DataStructureAndAlgorithm ├── After_Item.png ├── Array.md ├── ArrayOperation.md ├── BasicOfDataStructureandAlgorithm.md ├── BasicOfQueue.md ├── BasicOfStack.md ├── BasicOfTree.md ├── BinarySearch.md ├── BinarySearhTree.md ├── BinaryTree.md ├── CreatenTraverseLinkedList.md ├── Deque.md ├── DequeUsingList.md ├── IMG_20190823_143918.jpg ├── InsertionOnLinkedList.md ├── LinearSearch.md ├── LinkedList.md ├── OperationOnBST.md ├── QueueImplementationUsingList.md ├── RemoveNodeInLinkedList.md ├── StackOperation.md ├── TypeOfBinaryTree.md ├── UpdateLinkedList.md ├── array.png ├── atEnd.png ├── dequeue.png ├── dequeue2.png ├── insertatbegining.png ├── llis2t.png ├── llist.png ├── queue.png ├── singlelinkedlist.png ├── sinplenode.png ├── stack.png ├── stackOperation.png ├── traverselinkedkist.png └── tree │ ├── binarytree.png │ ├── child.png │ ├── degree.png │ ├── depth.png │ ├── edge.png │ ├── height.png │ ├── inorder.png │ ├── internalcode.png │ ├── leaf.png │ ├── level.png │ ├── node.png │ ├── parent.png │ ├── postorder.png │ ├── preorder.png │ ├── root.png │ ├── siblings.png │ └── tree.png ├── Data_Structure_In_Python ├── Dictionary │ ├── 1.BasicOfDictionary.py │ ├── 2.AddingRemovingElement.py │ ├── BasicOfDictionary.md │ └── BasicOperation.md ├── List │ ├── 1.BasicOfList.py │ ├── 2.LoopOnList.py │ ├── 3.Split_List_Using_Missing_denometer.py │ ├── BasicOfList.md │ ├── ExtendedSlicing.md │ ├── Insertdeleteupdateonlist.md │ ├── ListComprehension.md │ └── ListMethods.md ├── Set │ ├── 1.BasicOfSet.py │ ├── 2.AddingAndRemovingElement.py │ ├── BasicOfSet.md │ ├── InsertRemoveitemfromset.md │ └── MathmaticalOperationonset.md ├── String │ ├── 1.BasicOfStrings.py │ ├── 2.StringMethods.py │ ├── 3.FindOperatorInString.py │ ├── 4.StringFromatting.py │ ├── BasicOfStrings.md │ ├── StringFormatting.md │ └── StringMethods.md └── Tuple │ ├── 1.Basic_of_tuple.py │ ├── 2.OperationOnTuple.py │ ├── BasicOfTuple.md │ ├── FunctionOnTuple.md │ └── OperationOnTuple.md ├── ErrorHandling ├── 1.BasicOFErrorHandling.py ├── 2.ErrorHandlingusingInfinteloop.py └── BasicOfException.md ├── FileHandeling ├── BasicOpenFile.md ├── FileMethods.md ├── ReadContentOfFile.md └── WriteContetToFile.md ├── Function ├── 1.BasicOfFunction.py ├── 2.ExampleOfFunction.py ├── 3.LambdaFunction.py ├── BasicOfFunction.md ├── FunctionParameter.md └── Lambdafunction.md ├── IDLETricks └── 1.shortcuts.txt ├── Logging ├── 1.BasicOfLogging.py ├── 2.WriteLogToFile.py └── simplelog.log ├── Loops ├── 1.ForLoop.py ├── 2.AdavancedForLoop.py ├── 3.ForLoopOnList.py ├── 4.WhileLoop.py └── 5.InfinteWhileLoop.py ├── MachineLearning ├── BasicIntroduction.md ├── JupyterNotebook │ ├── BasicOfJupyterNotebook.md │ ├── ShortCutsofJupyter.md │ └── img │ │ ├── RunCell.gif │ │ ├── basics.png │ │ ├── img │ │ ├── new.png │ │ ├── newfile.png │ │ ├── open.png │ │ ├── opened.png │ │ ├── path.png │ │ ├── pip.png │ │ └── run.png ├── Numpy │ ├── 1.BasicOfNumpy.py │ ├── 2.Indexing_Selection_in_Numpy.py │ ├── 3.Operation_on_numpy_array.py │ ├── BasicNumpy.md │ ├── CreationOfNumpy.md │ ├── Notebook │ │ └── Type Of Numpy Array.ipynb │ └── img │ │ ├── np1d.png │ │ ├── np2d.png │ │ ├── np3d.png │ │ └── numpyarray.png ├── Pandas │ ├── 1.BasicofPandas.py │ ├── 1.IntroductionOfPandas.py │ ├── 2.SeriesInPandas.py │ ├── 3.DataFramesInPandas.py │ ├── 4.ConditionalSelectionPandas.py │ ├── 5.SingleDataFramePlotUSingMatplotlib.py │ ├── 6.ChangingIndexAndHeaders.py │ ├── 7.ImportAndExportFiles.py │ └── 8.Concatenate,Merge,Join.py └── img │ └── field.png ├── Module ├── BasicOfModule.md ├── CustomModule.md ├── os │ ├── AccessFileNames.md │ ├── BasicOfOsModule.md │ └── pathModuleInOS.md ├── platform │ └── platform.md └── wikipedia │ ├── 1.BasicOfWikipedia.py │ └── 2.WikipediaPageParsing.py ├── PythonQuestions.md ├── README.md ├── Regex ├── 1.BasicOfRegularExpression.py ├── 2.SomeTextManipulation.py ├── 3.MatchingSetOfCharacter.py ├── 4.EscapingMetacharcters.py ├── 5.FindSingleAndMultipleOccurence.py ├── 6.Findallonfileinput.py ├── BasicOfRegex.md ├── BuiltInFunctions.md ├── EscapingMetacharacters.md ├── Identifiers.md ├── Modifiers.md └── inputfile.txt ├── Threading ├── 0.MultiprocessingAndMultithreadingDifference.py ├── 1.BasicOfThreading.py └── 2.GetReturnValueFromThread.py ├── UsefulStuffs ├── Email │ ├── 1.SimpleEmailSend.py │ └── 2.AdvancedEmailSender.py └── SystemInformer │ ├── NetworkInfo.py │ ├── OsInfo.py │ ├── Readme.txt │ ├── SoftwareInfo.py │ ├── SystemDrives.py │ ├── main.py │ └── requirements.txt ├── UserInput ├── 1.UserInput.py └── 2.UserInputExamples.py ├── ZipFileHandleing ├── 1.Basicofzipfile.py └── 2.ExtractDataFromZipFile.py └── _config.yml /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Basic/Comments.md: -------------------------------------------------------------------------------- 1 | ## Comments In Python 2 | #### Basic of Comments 3 | - Comments are very important while writing a program. 4 | - It describes what's going on inside a program so that a person looking at the source code does not have a hard time figuring it out. 5 | 6 | ### For comments there are two options 7 | #### 1.Single line comment 8 | - we use the hash (#) symbol to start writing a comment. 9 | Python Interpreter ignores comment. 10 | For example: 11 | ```python 12 | #this is first comment 13 | #this is second comment 14 | a=5 15 | #code with comment 16 | ``` 17 | 18 | ### 2.Multi line comment 19 | - Use triple quotes, either ''' or """. For multicommenting. 20 | - These triple quotes are generally used for multi-line strings. But they can be used as multi-line comment as well. Unless they are not docstrings, they do not generate any extra code. 21 | 22 | For Example: 23 | ```python 24 | ''' this is multi line comment 25 | Second line comment 26 | Third line comment Fourth line ''' 27 | ``` 28 | Or 29 | ```python 30 | """this is multi line comment 31 | Second line comment 32 | Third line comment 33 | Fourth line """ 34 | ``` 35 | 36 | ### Is this possible to assign multiple lines to a single variable 37 | - yes you can use in following ways: 38 | ```python 39 | #Assign Multiline Text to Variable 40 | myvar= """this is multi line comment 41 | Second line comment 42 | Third line comment 43 | Fourth line """ 44 | 45 | #for print result print(myvar) 46 | print(myvar) 47 | ``` 48 | 49 | Output 50 | ``` 51 | this is multi line comment 52 | Second line comment 53 | Third line comment 54 | Fourth line 55 | ``` 56 | 57 | Note:- multi line comments are also used to create doc string for function or class 58 | -------------------------------------------------------------------------------- /Basic/ConditionalStatementIfelse.md: -------------------------------------------------------------------------------- 1 | ## Conditional Statement 2 | 3 | ### if 4 | 5 | Like any other programming language python also support **if-else** for the conditional statement. 6 | 7 | ### Python supports the usual logical conditions from mathematics 8 | ``` 9 | == :- Equals 10 | a == b 11 | 12 | != :- Not Equals 13 | a != b 14 | 15 | < :- Less than 16 | a < b 17 | 18 | <= :- Less than or equal to 19 | a <= b 20 | 21 | > :- Greater than 22 | a > b 23 | 24 | >= :- Greater than or equal to 25 | a >= b 26 | ``` 27 | These conditions can be used in several ways, most commonly in **"if statements".** 28 | 29 | Syntax: 30 | ```python 31 | if (condition) : 32 | #exexute this block 33 | ``` 34 | Or without braces 35 | ```python 36 | if condition : 37 | #exexute this block 38 | ``` 39 | 40 | For example 41 | ```python 42 | a=5 43 | if a==5: 44 | print("A value is 5") 45 | ``` 46 | Output: 47 | ``` 48 | A value is 5 49 | ``` 50 | 51 | ### If else 52 | - when we want to check one condition and if that condition met we need to execute **if** block code otherwise run **else** block 53 | 54 | Syntax: 55 | ```python 56 | if condition : 57 | #exexute this block 58 | else: 59 | #execute this else block 60 | ``` 61 | 62 | For example 63 | ```python 64 | a=5 65 | if (a==5): 66 | print("A value is 5") 67 | else: 68 | print("A value is not 5") 69 | ``` 70 | 71 | Output : 72 | ``` 73 | A value is 5 74 | ``` 75 | 76 | Or you can simple write 77 | ```python 78 | a=5 79 | if a==5: 80 | print(" A value is 5") 81 | else: 82 | print("A value is not 5") 83 | ``` 84 | Output: 85 | ``` 86 | A value is 5 87 | ``` 88 | 89 | 90 | ### Nested if-else 91 | - There may be a situation when you want to check for another condition after a condition resolves to true. 92 | In such a situation, you can use the nested if construct. 93 | 94 | Syntax: 95 | ```PYTHON 96 | if condition: 97 | #code 98 | if condition: 99 | #code here for inner if 100 | else: 101 | #else code 102 | else: 103 | #outer else code add here 104 | ``` 105 | 106 | ### How to use elif 107 | When you want to execute multiple conditions you can use **elif** 108 | 109 | Santax: 110 | ```python 111 | if condition: 112 | #add code here 113 | elif second condition: 114 | #add another code block 115 | elif third_condition: 116 | #add another code block 117 | else: 118 | #add final else block 119 | ``` 120 | Here first condition check if it doesn't true then it check second condition if all **elif** conditions are fail at that time it will execute **else** block 121 | 122 | ### How to write multiple conditions in single if statement 123 | Use logical operator **and(&), or(|)** to checking multiple conditions 124 | 125 | syntax 126 | ```python 127 | if condition and condition2 and condition3: 128 | #code block 129 | ``` 130 | 131 | Example: 132 | ```python 133 | a=5 134 | b=6 135 | c=3 136 | large=0 137 | if a>b and a>c : 138 | large=a 139 | elif b>a and b>c : 140 | large=b 141 | else: 142 | large=c 143 | 144 | print(large) 145 | ``` 146 | Output: 147 | ``` 148 | 6 149 | ``` 150 | -------------------------------------------------------------------------------- /Basic/ElseinLoop.md: -------------------------------------------------------------------------------- 1 | ## Else in Loop 2 | 3 | ### Introduction : 4 | - In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. 5 | But Python also allows us to use the else condition with for loops. 6 | - Such type of else is useful only if there is an if condition present inside the loop which somehow depends on the loop variable. 7 | 8 | ### What is the use of else in the loop? 9 | - The else block just after for/while is executed only when the loop is NOT terminated by a break statement. 10 | 11 | Here else block will be executed because for loop doesn't contain any **break** statement 12 | ```python 13 | for i in range(1, 4): 14 | print(i) 15 | else: 16 | print("this will be executed") 17 | ``` 18 | 19 | Output: 20 | ``` 21 | 1 22 | 2 23 | 3 24 | this will be executed 25 | ``` 26 | 27 | 28 | Here else block will not executed because for loop contains **break** statement 29 | ```python 30 | for i in range(1, 4): 31 | print(i) 32 | break 33 | else: 34 | print("this will not executed") 35 | ``` 36 | Output: 37 | ``` 38 | 1 39 | ``` 40 | 41 | #### Note 42 | if for loop contain an if statement 43 | and if statement contains break. 44 | Consider that if statement not executed this time else block of for loop will be executed 45 | 46 | 47 | ### Explain in details with example 48 | E.g. if 5 exists in any string, if yes print accordingly. 49 | 50 | Code: 51 | ```python 52 | strings="HELLO" 53 | for i in strings: 54 | if i== '5': 55 | print("5 found") 56 | break 57 | else: 58 | print("5 not found") 59 | ``` 60 | Output: 61 | ``` 62 | 5 not found 63 | ``` 64 | -------------------------------------------------------------------------------- /Basic/FirstProgram.md: -------------------------------------------------------------------------------- 1 | ## Write And Execute Python Basic Program. 2 | - As Consider we have already completed python setup in windows machine in the previous tutorial Now the main basic task is to write a full python code and execute our python first program. 3 | 4 | ### What is the use of python idle terminal ? 5 | you can write your small code on idle terminal and press enter to execute 6 | 7 | Example: 8 | ```python 9 | print("I am from terminal ") 10 | ``` 11 | Output: 12 | ``` 13 | I am from terminal 14 | ``` 15 | 16 | you can use python idle terminal as a calculator 17 | Example: 18 | ```python 19 | >5+6-7 20 | ``` 21 | and press enter to execute you will get the final result in the next line 22 | ```python 23 | >4 24 | ``` 25 | 26 | ### How to write a program in idle and run in python? 27 | - After the opening of the idle terminal just press **Ctrl+n** to open a notepad like a python text editor. 28 | - And write the required code inside the editor. 29 | - Now save that file as your required name with **extension.py** 30 | 31 | Example: 32 | ``` 33 | filename.py 34 | ``` 35 | 36 | ### How To Run Python file. 37 | There are 2 way to run python file 38 | 39 | 1.Normal 40 | - Open Python file in python IDLE. 41 | - Now just press **f5** or go running menu option and select **run** to execute the python file. 42 | - Now the result will be displayed on your python Shell. 43 | 44 | 2. Using Terminal 45 | - Open command prompt or terminal in your shell. 46 | - Go to directory copy path and in command prompt and change command prompt directory using the following command. 47 | ```python 48 | >cd "directory path" 49 | ``` 50 | - after changing directory just type 51 | ```python 52 | dir>python filename.py 53 | ``` 54 | - Now your required result will be displayed on command prompt 55 | 56 | ### Error And Solution 57 | 58 | - if **"python command is not recognized"** occured 59 | 60 | ### Solution 61 | #### Add Python Path To System Variable 62 | 63 | - Visit following path 64 | ``` 65 | My Computer >(Right Click) 66 | Properties > 67 | Advanced System Settings > 68 | Environment Variables 69 | ``` 70 | - Just add the path as C:\Python37 (or wherever you installed python) to **PATH** Variable. 71 | - And Also Add python/scripts path to an environment variable. 72 | 73 | -------------------------------------------------------------------------------- /Basic/ForLoop.md: -------------------------------------------------------------------------------- 1 | ## Loop Statement 2 | 3 | Python supports two types of loops 4 | 1. For 5 | 2. While 6 | 7 | ### For Loop 8 | - For loop iterate over a given sequence such as list, string, tuple dictionary or any iterable object. 9 | - For loops can iterate over a sequence of numbers using the **range** and **xrange** functions. 10 | 11 | Syntax: 12 | ```python 13 | for variable in (iterable object) : 14 | print(variable) 15 | ``` 16 | Normally for range function contain three different parameter 17 | 1. starting number 18 | 2. Stop number+1 19 | 3. difference or step number(optional if not given then it will increment by 1) 20 | 21 | Example 1 22 | if you want to print 0 to 10 numbers using for loop 23 | ```python 24 | for i in range(11): 25 | print(i) 26 | ``` 27 | Output: 28 | ``` 29 | 0 30 | 1 31 | 2 32 | 3 33 | 4 34 | 5 35 | 6 36 | 7 37 | 8 38 | 9 39 | 10 40 | ``` 41 | 42 | If we do not give the starting number and difference by default range function start from 0 and increment it by 1 until the given number. 43 | 44 | Example 2 45 | if you want to print 2 to 20 with difference 2 46 | ```python 47 | for i in range(2,21,2): 48 | print(i) 49 | 50 | ``` 51 | Output: 52 | ``` 53 | 2 54 | 4 55 | 6 56 | 8 57 | 10 58 | 12 59 | 14 60 | 16 61 | 18 62 | 20 63 | ``` 64 | range function consider starting given no as it is (include starting number as it is given) but exclude stop number so we always provide ending number by incrementing 1. 65 | 66 | ### For Loop on String 67 | if you want to print every character or alphanumeric values as one by one we can easily print using for loop. 68 | ```python 69 | mystring="I am python student" 70 | for st in mystring: 71 | print(st) 72 | ``` 73 | 74 | Output: 75 | ``` 76 | I 77 | 78 | a 79 | m 80 | 81 | p 82 | y 83 | t 84 | h 85 | o 86 | n 87 | 88 | s 89 | t 90 | u 91 | d 92 | e 93 | n 94 | t 95 | ``` 96 | 97 | ### For loop on List 98 | ```python 99 | mylst=[4,6,3,9,3] 100 | for i in mylst: 101 | print(i) 102 | ``` 103 | 104 | Output: 105 | ``` 106 | 4 107 | 6 108 | 3 109 | 9 110 | 3 111 | ``` 112 | ### Some Examples On For Loop 113 | 114 | prints out the numbers 0,1,2,3,4,5,6 115 | ```python 116 | for x in range(7): 117 | print(x) 118 | ``` 119 | 120 | Output: 121 | ``` 122 | 0 123 | 1 124 | 2 125 | 3 126 | 4 127 | 5 128 | 6 129 | ``` 130 | 131 | prints out 2,3,4,5,6,7 132 | ```python 133 | for x in range(2, 8): 134 | print(x) 135 | ``` 136 | 137 | Output: 138 | ``` 139 | 2 140 | 3 141 | 4 142 | 5 143 | 6 144 | 7 145 | ``` 146 | 147 | prints out 3,6,9 148 | ```python 149 | for x in range(3, 11, 3): 150 | print(x) 151 | ``` 152 | 153 | Output: 154 | ``` 155 | 3 156 | 6 157 | 9 158 | ``` 159 | -------------------------------------------------------------------------------- /Basic/IdleShortcuts.md: -------------------------------------------------------------------------------- 1 | ## IDLE Shortcuts 2 | 3 | ### Following are some idle shortcuts that help to rewrite code on idle 4 | 5 | 6 | ### 1. Tab Completion:  7 | Type some code and then press the **TAB** key. IDLE will offer suggestions to help you complete your statement. 8 | 9 | ### 2. Recall Code Statement:  10 | 11 |   Press **Alt-P** to recall the previous code statement entered IDLE or press **Alt-N** to move to the next code statement. 12 | 13 | ### 3.  Edit Recalled Code 14 | 15 |   Once you recall your code statement, you can edit it and move around the statement using the arrow keys. 16 |   It’s possible to edit any statement that you’ve previously entered, even code statements that span multiple lines. 17 | 18 | ### 4.  Adjust Idle Preference 19 | 20 | just click on options and click on configure idle there 21 | 1. Font/tab 22 | 23 |   - Here select one appropriate font according to your need you also select the size of text 24 | 25 | 2. highlight 26 | 27 |  - Select a highlighting theme 28 | 29 | 3. keys  30 | 31 |  - Here you can add your own shortcut keys. 32 | 33 | 4. General  34 | 35 | - You can change the window size 36 | -------------------------------------------------------------------------------- /Basic/PIPIntroduction.md: -------------------------------------------------------------------------------- 1 | ## Python Package installer(PIP) :postal_horn:. 2 | 3 | ### What is pip? 4 | - PIP stands for **Python Package installer**. 5 | - PIP is a package manager for Python packages or modules. 6 | - Pip is a package management system used to install and manage software packages written in Python. 7 | - We can find Many packages in the default source for packages and their dependencies. 8 | - Python Package installer. Python 2.7.9 and later, and Python 3.4 and later include pip by default. 9 | 10 | ### Check if PIP is Installed? 11 | - Open command prompt and type the following 12 | 13 | `>pip --version` 14 | 15 | If the above shows the pip version, then pip is already installed on your system. 16 | 17 | ### How to upgrade PIP 18 | Open the command prompt and type the following 19 | ```python 20 | >python -m pip install –upgrade pip 21 | ``` 22 | 23 | ### Use of PIP 24 | You can install packages in 2 different ways. 25 | 26 | #### 1.Normal package without .Whl file  27 | - Go to https://pypi.org 28 | - Search required packages such as pandas, numpy, OpenCV. 29 | - Now type in the terminal 30 | 31 | ```python 32 | >pip install pacakagename 33 | ``` 34 | - Which package name is showing in the website portal 35 | 36 | #### 2.Use the wheel of that Package 37 | - Just open https://pypi.org 38 | - Search required packages such as pandas, numpy, OpenCV. 39 | - Do to download section and download .whl file which is an archive for packages. 40 | - Go to the download folder. And open command prompt their and type 41 | 42 | ```python 43 | >pip install downloaded_package.whl 44 | ``` 45 | 46 | ### Get List of installed packages list 47 | Use the list command to list all the packages installed on your system: 48 | Example 49 | ```python 50 | >pip list 51 | ``` 52 | ### How to Remove Uninstall Packages 53 | Use the uninstall command to remove a package: 54 | 55 | Example 56 | ```python 57 | >pip uninstall pacakagename 58 | ```` 59 | 60 | ### How to create requirement.txt file using pip 61 | - Save all the packages in the file with 62 | 63 | Example: 64 | ```python 65 | >pip freeze >requirements.txt 66 | ``` 67 | Keep in mind that in this case, **requirements.txt** file will list all packages that have been installed in the system. 68 | So before creating any project first create an environment and run above command to list out required package name in **requirements.txt** 69 | 70 | ### Install project dependencies using requirements.txt  71 | - first, go to the folder where **requirements.txt** file is placed and type the following command in terminal  72 | 73 | Example: 74 | ```python 75 | >pip install -r requirements.txt 76 | ``` 77 | -------------------------------------------------------------------------------- /Basic/UserInput.md: -------------------------------------------------------------------------------- 1 | ## User Input 2 | 3 | ### For Reading User Input 4 | - For reading user input from terminal or shell we used keyword **input()** function. 5 | 6 | - In python version 2 we need to get 7 | 1. number using **input()** and 8 | 2. strings using **raw_input()** 9 | 10 | - In python version 3 **input()** function handle string as well as number. 11 | 12 | Syntax: 13 | ```python 14 | msg=input("message") 15 | print(msg) 16 | ``` 17 | You can put message as a blank that is an option to show message when accepting user input 18 | 19 | Example: 20 | ```python 21 | name=input("Enter your name:") 22 | print(name) 23 | #this will accept user input and save it within 24 | #name variable and print name. 25 | ``` 26 | 27 | You can also ask user message In a print statement and later ask user input function using **input()** 28 | ```python 29 | #this will ask user on terminal on same line 30 | username=input('Enter user name:') 31 | 32 | print('Enter Username:') 33 | uname=input() #this will ask input on new line 34 | 35 | print(username) 36 | print(uname) 37 | ``` 38 | 39 | Note: python 3 consider number and string as data type string while reading from user input 40 | 41 | Python 2 42 | ```python 43 | nm1=input() 44 | #when user input 5 as nm1 45 | print(type(nm1)) 46 | # this will print *int* as data type 47 | ``` 48 | Output 49 | ``` 50 | 5 51 | 52 | ``` 53 | 54 | Python 3 55 | ```python 56 | nm1=input() 57 | #when user input 5 as nm1 58 | print(type(nm1)) 59 | #this will print *Str* as data type 60 | ``` 61 | Output 62 | ``` 63 | 5 64 | 65 | ``` 66 | 67 | #### Examples 68 | Read string 69 | ```python 70 | mystring=input("Enter string") 71 | print(mystring) 72 | ``` 73 | ### For Printing Output on Console 74 | - The **print()** function prints the given object to the standard output device (screen) or to the text stream file. 75 | 76 | Syntax: 77 | ```python 78 | print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) 79 | ``` 80 | **objects**: object to the printed. * indicates that there may be more than one object 81 | 82 | **sep**: objects are separated by sep. Default value: ' ' 83 | 84 | **end**: the end is printed at last 85 | 86 | **file**: must be an object with a write(string) method. If omitted it, sys.stdout will be used which prints objects on the screen. 87 | 88 | **flush**: If True, the stream is forcibly flushed. Default value: False. 89 | 90 | Example: 91 | Normal single object print 92 | ```python 93 | #intilize The Variable 94 | mystring="i am python" 95 | number=5 96 | 97 | #print mystring and number 98 | print(mystring) 99 | print(number) 100 | ``` 101 | 102 | Output 103 | ``` 104 | i am python 105 | 5 106 | ``` 107 | 108 | Pass Multiple Objects to print() 109 | ```python 110 | #Assign Variable and numbers 111 | mystring="i am python" 112 | number=5 113 | 114 | #print mystring and number 115 | print(mystring,number) 116 | ``` 117 | 118 | Output 119 | ``` 120 | i am python 5 121 | ``` 122 | -------------------------------------------------------------------------------- /Basic/WhileLoop.md: -------------------------------------------------------------------------------- 1 | ## Loop Statement : While Loop 2 | 3 | ### Introduction 4 | 5 | - While loops repeat as long as a certain boolean condition is met. 6 | - The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. 7 | - Mostly while loop is used when we want to iterate a dynamical number of times repetition of an object. 8 | - The loop iterates while the condition is true. 9 | - When the condition becomes false, program control passes to the line immediately following the loop. 10 | - Iteration means executing the same block of code over and over, potentially many times. 11 | 12 | Syntax: 13 | ```python 14 | while [condition]: 15 | #run this code until while condtion is true 16 | ``` 17 | Example: 18 | ```python 19 | a=10 20 | while a!=0: 21 | print(a) 22 | a-=1 23 | ``` 24 | Output: 25 | ``` 26 | 10 27 | 9 28 | 8 29 | 7 30 | 6 31 | 5 32 | 4 33 | 3 34 | 2 35 | 1 36 | ``` 37 | 38 | ### Interruption of Loop Iteration 39 | - In each example you have seen so far, the entire body of the while loop is executed on each iteration. 40 | - Python provides two keywords that terminate a loop iteration prematurely: 41 | ``` 42 | 1. break 43 | 2. continue 44 | ``` 45 | 46 | ### 1.break 47 | - Immediately terminates a loop entirely. 48 | - Program execution proceeds to the first statement following the loop body. 49 | 50 | Example: 51 | ```python 52 | n= 5 53 | while n > 0: 54 | n -= 1 55 | if n == 2: 56 | break 57 | print(n) 58 | print('Loop ended.') 59 | ``` 60 | 61 | Output: 62 | ``` 63 | 4 64 | 3 65 | Loop ended. 66 | ``` 67 | 68 | when n becomes 2 the break statement is executed.loop is terminated completely, 69 | and program execution jumps to the **print()** statement on line 7. 70 | 71 | ### 2. continue 72 | - Immediately terminates the current loop iteration. 73 | - Execution jumps to the top of the loop, and the controlling expression is re-evaluated to determine whether the loop will execute again or terminate. 74 | 75 | Example: 76 | ```python 77 | n = 5 78 | while n > 0: 79 | n -= 1 80 | if n == 2: 81 | continue 82 | print(n) 83 | print('Loop ended.') 84 | ``` 85 | 86 | Output 87 | ``` 88 | 4 89 | 3 90 | 1 91 | 0 92 | Loop ended. 93 | ``` 94 | when n is 2, the continue statement causes termination of that iteration. 95 | Thus, 2 isn’t printed. 96 | Execution returns to the top of the loop, the condition is re-evaluated, and it is still true. 97 | 98 | -------------------------------------------------------------------------------- /Basic/commentsinpython.py: -------------------------------------------------------------------------------- 1 | '''comment are not shown when you run a program they are used to describe the what type of the code we have done''' 2 | #you can comment in two way 3 | #1.sinle line comment (use # symbol before comment) 4 | 5 | #this is simple single line commment 6 | 7 | #2.multiline commnet use('''comment here''') 8 | ''' 9 | this is first line 10 | this is second line 11 | this is third line 12 | 13 | ''' 14 | 15 | #Note: do not put # inside a qoutes 16 | print('# this is not a comment') #this is comment 17 | -------------------------------------------------------------------------------- /Basic/datatype.py: -------------------------------------------------------------------------------- 1 | #in python to findout datatype of any variable , object use :type(variable name,object name) 2 | inttype=type(343) 3 | print('343 datatype:',inttype) #answer:343 datatype: 4 | 5 | floattype=type(5.34) 6 | print('5.34 datatype:',floattype) #answer: 5.34 datatype: 7 | 8 | #in python single charcter also has datatype string 9 | singlecharacter=type('p') 10 | print('p datatype:',singlecharacter) #answer :p datatype: 11 | 12 | multiplecharacter=type('python') 13 | print('python datatype:',multiplecharacter)#answer:python datatype: 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Basic/indentation.md: -------------------------------------------------------------------------------- 1 | ## Indentation 2 | 3 | 4 | ### Basic of Indentation 5 | **indentation** concepts which play a vital role in python app development 6 | 7 | - One of the most distinctive features of Python is its use of indentation to mark blocks of code. 8 | - Other some languages such as c and c++ uses curly braces(**{}**) to differentiate block of code 9 | - But in python, we use indentation to differentiate block of code (basically tab of some active space) 10 | - we use a colon as the starting of code block and afterwords all code block will be placed. 11 | - Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements. 12 | - A code block (body of a function, loop, etc.) starts with indentation and ends with the first unindented line. 13 | - The amount of indentation is up to you, but it must be consistent throughout that block. 14 | 15 | ### For example: 16 | consider if loop 17 | In C Programing 18 | ```python 19 | if(conditions) { 20 | #main code 21 | } 22 | ``` 23 | In python Programing: 24 | 25 | With Brackets 26 | ```python 27 | if(conditions) : 28 | #Write Your Main Code Here 29 | ``` 30 | 31 | without Brackets 32 | ```python 33 | if conditions: 34 | #Write Your Main Code Here 35 | ``` 36 | 37 | ### How can we write code block in one line 38 | - Indentation can be ignored in line with continuation. 39 | - But it's a good idea to always indent. It makes the code more readable. 40 | Example: 41 | with Brackets 42 | ```python 43 | if(conditions) :#main code 44 | ``` 45 | 46 | Without Brackets 47 | ```python 48 | if conditions: #Write Your Main Code Here 49 | ``` 50 | 51 | ### If you give the wrong indentation which error will occurred 52 | 53 | Consider following code block 54 | ```python 55 | if(1==1) : 56 | print("First line") 57 | print("second line") 58 | ``` 59 | 60 | Above Program Create Following Error 61 | ```python 62 | IndentationError: unindent does not match any outer indentation level 63 | ``` 64 | 65 | Correct Solution 66 | ```python 67 | if 1==1 : 68 | print("First line") 69 | print("second line") 70 | ``` 71 | 72 | Output 73 | ``` 74 | First line 75 | second line 76 | ``` 77 | -------------------------------------------------------------------------------- /Basic/indentation.py: -------------------------------------------------------------------------------- 1 | #in c and c++ like language to diffrenciate block of code we use curly braces 2 | #in python to show the block of the code we use the indentation (basicaly tab of some active space) 3 | a=2 4 | if a==2: 5 | print('a is equal to 2') # this line contains one indentation tab that python anyalze this code of block is for if statement 6 | 7 | -------------------------------------------------------------------------------- /Basic/variable.py: -------------------------------------------------------------------------------- 1 | 2 | #Unlike other programming languages, Python has no command for declaring a variable. 3 | 4 | #A variable is created the moment you first assign a value to it. 5 | 6 | x = 5 #int 7 | y = "John" #string 8 | z=[1,2,4,5] #list 9 | -------------------------------------------------------------------------------- /Class/1.BasicOfClass.py: -------------------------------------------------------------------------------- 1 | # Class 2 | # to create a class you need to use class keyword 3 | # First alphabet of class name must be capital 4 | # class contains attributes and method 5 | # When a object of class is created then by default __init__() method is called 6 | # init() method is called constructor of class who will assign some memory unit to the attributes 7 | 8 | # The first paramater of constructor is self 9 | 10 | class Person(): # here Person is class name 11 | def __init__(self, name, age, gender, salary): 12 | # print('Init method is called') 13 | self.name = name 14 | self.age = age 15 | self.gender = gender 16 | self.salary = salary 17 | 18 | 19 | person1 = Person('rajesh', 23, 'male', 14523) 20 | # for this object self=person1 so if we want to know the name of person1 then 21 | print(person1.name) 22 | 23 | person2 = Person('ragini', 22, 'female', 14690) 24 | # self=person2 25 | # salary of person2 26 | print(person2.salary) 27 | -------------------------------------------------------------------------------- /Class/2.MethodsInClass.py: -------------------------------------------------------------------------------- 1 | # every class has one method __init__() which is automatically called when the class object is created 2 | 3 | # every class method need one parameter that is self or you can write your classname intead of self 4 | 5 | # 1.using Self keywords 6 | class Person(): 7 | def __init__(self, name, age, salary): 8 | self.name = name 9 | self.age = age 10 | self.salary = salary 11 | 12 | def isegl(self): # this is new method defination 13 | if self.age >= 18: 14 | return True 15 | else: 16 | return False 17 | 18 | 19 | person1 = Person('Abhi', 17, 3333) 20 | print(person1.isegl()) # calling method using instance of class means object of class 21 | 22 | 23 | # 2.using Class name 24 | class Person2(): 25 | def __init__(Person2, name, age, salary): 26 | Person2.name = name 27 | Person2.age = age 28 | Person2.salary = salary 29 | 30 | def isegl(Person2): # this is new method defination 31 | if Person2.age >= 18: 32 | return True 33 | else: 34 | return False 35 | 36 | 37 | person1 = Person('Abhi', 19, 3333) 38 | print(person1.isegl()) # calling method using instance of class means object of class 39 | 40 | -------------------------------------------------------------------------------- /Class/3.DifferenceBetweenClassVariableAndInstanceVariable.py: -------------------------------------------------------------------------------- 1 | 2 | #there are two TYPE Of Variables 3 | #1.instance variable-defined in __init__() method 4 | #2.Class Varaible-defined in class 5 | 6 | #Static(Class) variables and instance variables both are member variables because they are both associated with a specific class 7 | 8 | #Instance Variable 9 | #Instance variables are not shared between the objects of a class. Each instance will have their own copy of instance variables 10 | #every object has it's own personal copy of an instance. 11 | #to call instance variable we need to self.varaiblename 12 | #Instance variables can be accessed only through object reference 13 | 14 | 15 | #Class Varaible 16 | #Class variables only have one copy that is shared by all the different objects of a class 17 | #Class variables are common to all instances of a class. These variables are shared between the objects of a class 18 | #to call Class variable we need to classname.varaiblename 19 | #Class variables can be accessed using either class name or object reference. 20 | 21 | 22 | 23 | #Example of instance variable 24 | class Circle(): 25 | def __init__(self,radious,pi): 26 | self.radious=radious 27 | self.pi=pi #instance variable 28 | def area(self): 29 | return self.pi*self.radious**2 30 | circle1=Circle(3,3.14) #we are sending instance varaible 31 | print(circle1.area()) 32 | 33 | 34 | 35 | #Example of Class variable 36 | 37 | class Circlec(): 38 | pi=3.14 #this is called class variable we are defining here 39 | def __init__(self,radious): 40 | self.radious=radious 41 | def area(self): 42 | return Circlec.pi*self.radious**2 #Here we called class variable 43 | circlec=Circlec(3) 44 | print(circlec.area()) 45 | -------------------------------------------------------------------------------- /Class/4.CreateAndFetchDocuments.py: -------------------------------------------------------------------------------- 1 | #To write simple Document inside a program 2 | 3 | #we can write document using '''document or help add here''' inside 4 | #1.class 5 | #2.Normal Function 6 | #3.Methods 7 | 8 | 9 | #To fetch the our written code document we have two different method to collect documents 10 | #1.__doc__ 11 | #2.help() function 12 | 13 | 14 | #1.__doc__ 15 | #Doc string is used to get detail information about code 16 | #Simple syntax of __doc__ for class is : Classname.__doc__ 17 | # __doc__ for class method:Classname.methodname.__doc__ 18 | # __doc__ for simple normal function:FunctionName.__doc__ 19 | 20 | 21 | #2.help() function 22 | #help() function is used to retrive all document related to class unctions and method 23 | #we can simple define help as :help(any class,function object) 24 | #help give all document about 25 | #1.about class and 26 | #2.defined method inside of class 27 | #3.dictionaries 28 | 29 | def CustomFunction(): 30 | '''I am a simple custom function'''#document about function 31 | print('i am from custom function') 32 | class Circle(): 33 | '''this is Circle Class used to find out area''' #Add Document About Class here 34 | def __init__(self,radious,pi): 35 | self.radious=radious 36 | self.pi=pi 37 | def area(self): 38 | '''this is area method inside Circle ''' #document inside a method 39 | return self.pi*self.radious**2 40 | circle1=Circle(3,3.14) 41 | print(circle1.area()) 42 | 43 | #TO print out Class Document 44 | print(Circle.__doc__) 45 | 46 | 47 | #To print out method documnet from class 48 | print(Circle.area.__doc__) 49 | 50 | 51 | ##To print out simple function Document 52 | print(CustomFunction.__doc__) 53 | 54 | 55 | #To printout all document of class then we can use help function 56 | help(Circle) 57 | 58 | 59 | #to printout all data about predefined objects 60 | help(list) 61 | -------------------------------------------------------------------------------- /Class/5.InheritanceInPythonClass.py: -------------------------------------------------------------------------------- 1 | # Inheritance 2 | # inheritance means creating a new class who access variables and methods from parent class 3 | # A class can inherit attributes and behaviour methods from another class, called the superclass. A class which inherits from a superclass is called a subclass, also called heir class or child class 4 | 5 | # simple Example 6 | # laptop -has atrributes brand,screen,hdd,ram, 7 | # gaming laptop-has attributes brand,screen ,hdd,ram,graphicscard,processing clock speed 8 | 9 | 10 | # You can derive initailization from parent class in two way 11 | # 1. super().__init__(Variable from parent claas) 12 | # 2.Classname.__init__(self,Variable from parent claas) 13 | 14 | # Now First Create a Class for normal Laptop 15 | 16 | # this is base class/parent class 17 | class Laptop(): 18 | def __init__(self, brand, screen, hdd, ram): 19 | self.screen = screen 20 | self.ram = ram 21 | self.brand = brand 22 | self.hdd = hdd 23 | 24 | def showinfo(self): 25 | print('The laptop brand is {} whose screen size is {}. And who has {} TB hdd and {} gb ram'.format(self.brand, 26 | self.screen, 27 | self.hdd, 28 | self.ram)) 29 | 30 | def data(self): 31 | print('data is for normal laptop') 32 | 33 | 34 | # Now Create Another class for GamingLaptop 35 | # but gaming laptop has some attributes which are already present in laptop class 36 | # so create new class with name GamingLaptop which inherits laptop class inside it 37 | 38 | # this is derived class 39 | class GamingLaptop(Laptop): # add parent class name inside bracket 40 | def __init__(self, brand, screen, hdd, ram, graphics, cpuspeed): 41 | super().__init__(brand, screen, hdd, 42 | ram) # call parent class method __init__() to define brand,screen,hdd,ram from base class or parent class Laptop 43 | # now define remaining attributes here 44 | 45 | self.graphics = graphics 46 | self.cpuspeed = cpuspeed 47 | 48 | def data(self): 49 | print('data is for Gaming laptop') 50 | 51 | 52 | # Now create a object of derived class and call method from parent class 53 | lenovogaming = GamingLaptop('Lenovo', 15.6, 1, 8, 4, '3.0ghz') 54 | lenovogaming.showinfo() 55 | 56 | # method overriding 57 | # derived class has a same name method as compare to parent class then only derived class methood is called 58 | # both class has same method data() 59 | lenovogaming.data() # this will call method of GamingLaptop Class 60 | 61 | 62 | -------------------------------------------------------------------------------- /Class/6.MultilevelInheritance.py: -------------------------------------------------------------------------------- 1 | # multilevel inheritance 2 | # In multiple inheritance, the features of all the base classes are inherited into the derived class. 3 | # We can inherit a derived class from another derived class, this process is known as multilevel inheritance 4 | 5 | # base class for GamingLaptop 6 | class Laptop(): # base class/parent class 7 | def __init__(self, brand, screen, hdd, ram): 8 | self.screen = screen 9 | self.ram = ram 10 | self.brand = brand 11 | self.hdd = hdd 12 | 13 | def showinfo(self): 14 | print('The laptop brand is {} whose screen size is {}. And who has {} TB hdd and {} gb ram'.format(self.brand, 15 | self.screen, 16 | self.hdd, 17 | self.ram)) 18 | 19 | def data(self): 20 | print('data is for normal laptop') 21 | 22 | 23 | # this is derived class from Laptop 24 | # this is Base class for SuperGamingLaptop 25 | class GamingLaptop(Laptop): # derived class /sub class 26 | def __init__(self, brand, screen, hdd, ram, graphics, cpuspeed): 27 | super().__init__(brand, screen, hdd, 28 | ram) # call parent class method __init__() to define brand,screen,hdd,ram from base class or parent class Laptop 29 | # now define remaining attributes here 30 | self.graphics = graphics 31 | self.cpuspeed = cpuspeed 32 | 33 | def data(self): 34 | print('data is for Gaming laptop') 35 | 36 | 37 | # this is derived class from GamingLaptop 38 | class SuperGamingLaptop(GamingLaptop): 39 | def __init__(self, brand, screen, hdd, ram, graphics, cpuspeed, processor): 40 | super().__init__(brand, screen, hdd, ram, graphics, cpuspeed) 41 | self.processor = processor 42 | 43 | 44 | lenovogaming = SuperGamingLaptop('Lenovo', 15.6, 1, 8, 4, '3.0ghz', 'I7') 45 | lenovogaming.showinfo() # when we call this method first it find in SupergamingLaptop class if it not found then search it in GamingLaptop class is also that method not found then it will find out that method in laptop And run from ther 46 | 47 | lenovogaming.data() # this method run from GamingLaptop Class 48 | -------------------------------------------------------------------------------- /Class/7.Multipleinheritance.py: -------------------------------------------------------------------------------- 1 | # One class extending more than one class is called multiple inheritance. 2 | 3 | #parent class 1 4 | class A: 5 | def __init__(self): 6 | print('i am from Class A') 7 | self.name = 'John' 8 | self.age = 23 9 | 10 | def getName(self): 11 | return self.name 12 | 13 | #parent class 2 14 | class B: 15 | def __init__(self): 16 | print('i am from Class B') 17 | self.name = 'Richard' 18 | self.id = '32' 19 | 20 | def getName(self): 21 | return self.name 22 | 23 | 24 | class C(B,A): #extend two base class 25 | print('i am from Class c') 26 | def __init__(self): 27 | A.__init__(self) 28 | B.__init__(self) 29 | 30 | def getName(self): 31 | return self.name 32 | 33 | 34 | C1 = C() 35 | print(C1.getName()) 36 | 37 | 38 | #When You called c Class then __init__method of c is fist called after calling c class inside init() method 39 | #then class A is called because in C class Initilization we called A class initilization first 40 | #then Class B is called 41 | 42 | 43 | #firstly name value=jhon 44 | #After calling to B class name value is override with jhon 45 | 46 | #So the Final Output is Richard -------------------------------------------------------------------------------- /Class/AttributesandMethods.md: -------------------------------------------------------------------------------- 1 | ## Attributes and Methods 2 | 3 | 4 | ## Attributes 5 | - variable inside a class are called attributes. 6 | - A class attribute is a Python variable that belongs to a class rather than a particular object. 7 | - It is shared between all the objects of the class. 8 | - Attributes are defined outside the constructor methods. 9 | 10 | Syntax: 11 | ```python 12 | class : 13 | variablename=value 14 | ``` 15 | Example: 16 | ```python 17 | class Person: 18 | #Initialize Attributes 19 | name="python" 20 | age=25 21 | ``` 22 | ### How to get values of Class attribute using class objects? 23 | 24 | - for accessing, class attributes use class name and dot(.) notation 25 | 26 | Syntax: 27 | ```python 28 | classobject.variablename(attributename) 29 | ``` 30 | 31 | Example: 32 | ```python 33 | #Initilize class 34 | class Person: 35 | #Initialize Attributes 36 | name="python" 37 | age=25 38 | 39 | #initialize the class object 40 | p1=Person() 41 | 42 | #To Access name Attributes 43 | name=p1.name 44 | print(name) 45 | #Result:python 46 | 47 | #To Access age Attributes 48 | age=p1.age 49 | print(age) 50 | #Result:25 51 | ``` 52 | Output: 53 | ``` 54 | python 55 | 25 56 | `` 57 | 58 | ### Modify Class Attributes using Class object 59 | - To modify class attributes use normal assignment(=) operator with class object and attributes name 60 | 61 | Syntax: 62 | ```python 63 | classobject.attributename=Value 64 | ``` 65 | 66 | Example: 67 | ```python 68 | #Initilize class 69 | class Person: 70 | #Initialize Attributes 71 | name="python" 72 | age=25 73 | 74 | #initialize the class object 75 | p1=Person() 76 | 77 | #Name Attribute Value Before Modification 78 | name=p1.name 79 | print(name) 80 | #Result:python 81 | 82 | #Modify name value "python" to "python 3.7" 83 | p1.name="python 3.7" 84 | 85 | #Now just get the value of name Attribute 86 | name=p1.name 87 | print(name) 88 | #Result:python 3.7 89 | ``` 90 | 91 | Output: 92 | ``` 93 | python 94 | python 3.7 95 | ``` 96 | 97 | 98 | ## Methods 99 | - A function inside a class is called a method. 100 | - The method is accessible within the class. 101 | - Methods can accept n number of parameters and return value using the return keyword. 102 | 103 | ### How to define method? 104 | - **def** keyword is used to define the method. 105 | - The first parameter of the method is **self**. 106 | - In the method, attributes are called with Classname dot(.)notation 107 | 108 | Syntax: 109 | ```python 110 | Class : 111 | def MethodName(self,Paramter1,paramter2): 112 | #Code inside a method 113 | ``` 114 | 115 | Example: 116 | ```python 117 | #initialize the class 118 | class Person: 119 | #initialize the Method 120 | def Display(self): 121 | print(Person.name) 122 | ``` 123 | 124 | ### How to call a method from a class using an object? 125 | 126 | - to call a method from a class using class object we use dot(**.**) Notation 127 | 128 | Syntax: 129 | ```python 130 | classobject.methodname() 131 | ``` 132 | 133 | Example: 134 | ```python 135 | #initilize the class 136 | class Person: 137 | #initialize the methods 138 | def Display(self): 139 | print("the simple output from the Display method") 140 | 141 | #initialize the class objects 142 | p1=Person() 143 | 144 | #call Display method from Person class using p1 class object 145 | p1.Display() 146 | 147 | #Result: the simple output from the Display method 148 | ``` 149 | Output: 150 | ``` 151 | the simple output from the Display method 152 | ``` 153 | -------------------------------------------------------------------------------- /Class/Constructor class.md: -------------------------------------------------------------------------------- 1 | ## Constructor 2 | 3 | ### Basic Of Constructor 4 | 5 | - A constructor is a special type of method(function) inside a class. 6 | - A constructor is automatically called at the time of object creation(Instantiated). 7 | - A constructor is used to assign some memory to an instance of a class 8 | - Constructor in python is created using the __init__ method. 9 | - __init__() method take the first parameter as self(You can use any name but for maintaining  standard naming convention use self keyword only)  10 | - It's a bad idea to write your logical code inside. Because constructor block is automatically called whenever create a new object of that class. 11 | 12 | There are two types of constructor available in python 13 | ``` 14 | - empty Constructor 15 | - parameterized Constructor 16 | ``` 17 | ### 1.Empty Constructor 18 | 19 | Syntax: 20 | ```python 21 | class : 22 |     def __init__(self): 23 |         #initilize instance variable here 24 | ``` 25 | 26 | Example: 27 | ```python 28 | #Initilize the class 29 | class Person: 30 | #initilize The class constructor 31 | def __init__(self): 32 | print("The constructor is called") 33 | 34 | 35 | #Create an object of a Person Class 36 | p1=Person() 37 | ``` 38 | Output: 39 | ``` 40 | Constructor is called 41 | ``` 42 | 43 | Here when we have created **p1** as class object the __init__() constructor is automatically called. 44 | the block of __init__() is instantiated. 45 | 46 | ### 2.Parametrized Constructor 47 | - To use parameterized constructor __init__() method accepts **n** no of element and you need to pass only **n-1** parameter when you are creating an object of a class 48 | - to define an instance variable self keyword is used instance variables are called in any method using self keyword with dot(.) notation and variable name 49 | ```python 50 | self.variablename 51 | ``` 52 | 53 | - If constructor accepting 3 elements and you passing 6 elements to the constructor. The constructor creates an exception 54 | 55 | Syntax: 56 | ```python 57 | #In Class 58 | class : 59 |     def __init__(self,paramter list): 60 |        #initilize instance variable here 61 |        self.parameter1=parameter1 62 |        self.parameter2=parameter2 63 | 64 | #Creating Objects  65 | objectname=(paramters except self) 66 | ``` 67 | 68 | Example: 69 | ```python 70 | #Initilize the class 71 | class Person: 72 | #initilize The class constructor 73 | def __init__(self,name,age): 74 | print("The constructor is called") 75 | #Initilize the instance Variable 76 | self.name=name 77 | self.age=age 78 | 79 | #Simple method for displaying output 80 | def Display(self): 81 | print('name: '+self.name) 82 | print('age: '+str(self.age)) 83 | 84 | #Create an object of a Person Class and pass jhon as name and 25 as age. 85 | p1=Person("jhon",25) 86 | 87 | #Now to display the output call Display Method 88 | p1.Display() 89 | ``` 90 | Output: 91 | ``` 92 | The constructor is called 93 | name: jhon 94 | age: 25 95 | ``` 96 | -------------------------------------------------------------------------------- /Class/Hybridinheritance.md: -------------------------------------------------------------------------------- 1 | ## Hybrid Inheritance 2 | 3 | ![Hybrid Inheritance](https://github.com/chavarera/PythonScript/blob/master/Class/hybridinheritance.png) 4 | 5 | ### Hybrid Inheritance 6 | - when more than one inheritance is combined to achieve inheritance then it is called as Hybrid Inheritance 7 | 8 | 9 | ### Skelton Example of Hybrid Inheritance 10 | ```python 11 | class A: 12 | pass 13 | class B(A): 14 | pass 15 | class C(A): 16 | pass 17 | class D(B, C): 18 | pass 19 | ``` 20 | 21 | ### Example 1 22 | ```python 23 | class A: 24 | def __init__(self): 25 | print("Class A Is Initialized") 26 | self.Avar="I am A Class variable" 27 | class B(A): 28 | def __init__(self): 29 | A.__init__(self) 30 | self.Bvar="I am B Class variable" 31 | print("From Class B "+self.Avar) 32 | 33 | class C(A): 34 | def __init__(self): 35 | print("Class C Is Initialized") 36 | A.__init__(self) 37 | print("From Class C "+self.Avar) 38 | 39 | self.Cvar="I am C Class variable" 40 | 41 | class D(B, C): 42 | def __init__(self): 43 | B.__init__(self) 44 | C.__init__(self) 45 | print("From Class D ") 46 | print(self.Avar) 47 | print(self.Bvar) 48 | print(self.Cvar) 49 | d1=D() 50 | ``` 51 | Output: 52 | ``` 53 | Class A Is Initialized 54 | From Class B I am A Class variable 55 | Class C Is Initialized 56 | Class A Is Initialized 57 | From Class C I am A Class variable 58 | From Class D 59 | I am A Class variable 60 | I am B Class variable 61 | I am C Class variable 62 | ``` 63 | -------------------------------------------------------------------------------- /Class/InstanceandClassVariables.md: -------------------------------------------------------------------------------- 1 | ## Instance and Class Variables 2 | - the variable inside class also called attributes. 3 | - there are two different types of variables appears in classes and object. 4 | 1.instance variable 5 | 2.class variable 6 | 7 | ## 1.instance variable 8 | - instance variable defined inside a constructor __init__() method of the class. 9 | - Every object has its copy of an instance 10 | - to call an instance variable inside a class self keyword is used. 11 | ```python 12 | self.variablename 13 | ``` 14 | - instance variables can be accessed outside of class using class object reference or class name 15 | ```python 16 | objectname.instancevariablename 17 | ``` 18 | 19 | Syntax: 20 | ```python 21 | class : 22 | def __init__(self,variable, var2): 23 | self.variable=variable 24 | self.var2=var2 25 | ``` 26 | 27 | Example: 28 | ```python 29 | #class initilization 30 | class Circle(): 31 | #Define constructor with paramter 32 | def __init__(self,radious,pi): 33 | #declare instance variables here 34 | self.radious=radious 35 | self.pi=pi #instance variable 36 | def area(self): 37 | return self.pi*self.radious**2 38 | 39 | #create Object of class and pass parameter 40 | circle1=Circle(3,3.14) #we are sending instance variable 41 | 42 | #Call area method using class object 43 | print("Circle Of Area") 44 | print(circle1.area()) 45 | ``` 46 | Output: 47 | ``` 48 | Circle Of Area 49 | 28.26 50 | ``` 51 | 52 | ## 2.class variable 53 | - class variable defined outside of __init__() methods. 54 | - Here only one copy of the class variable created and it shared with all objects of a class. 55 | - to access class variables inside a class  we need to use class name dot(.) Notation and class variable  56 | classname.variable_name 57 | - The class variable can be accessed outside of class using class name either object reference 58 | ```python 59 | objectname.classvariable 60 | ``` 61 | 62 | Syntax: 63 | ```python 64 | class : 65 | #class variables 66 | Var1=value 67 | 68 | def __init__(self,variable, var2): 69 | #instance variable 70 | ``` 71 | 72 | Example: 73 | ```python 74 | #class initilization 75 | class Circlec(): 76 | 77 | #declare class variables here 78 | pi=3.14 79 | 80 | #Define constructor with paramter 81 | def __init__(self,radious): 82 | self.radious=radious 83 | def area(self): 84 | #Here we called class variable in another method 85 | return Circlec.pi*self.radious**2 86 | 87 | #create Object of class and pass parameter 88 | circlec=Circlec(3) 89 | 90 | #Call area method using class object 91 | print(circlec.area()) 92 | ``` 93 | Output: 94 | ``` 95 | 28.26 96 | ``` 97 | -------------------------------------------------------------------------------- /Class/Methodoverriding.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/Class/Methodoverriding.png -------------------------------------------------------------------------------- /Class/MultilevelInheritance.md: -------------------------------------------------------------------------------- 1 | ## Multilevel Inheritance 2 | 3 | ### Introduction 4 | 5 | - The features of all the base classes are inherited into the derived class We can inherit a derived class from another derived class, this process is known as multilevel inheritance. 6 | - This is an example of a child and grandchild relationship. 7 | - Multi-level inheritance is archived when a derived class inherits another derived class. 8 | - There is no limit on the number of levels up to which, the multi-level inheritance is archived in python. 9 | - when we call a method using derived class and if that method is not available in that derived class it will check it in its parent class. if that method is not present in parent class then it will search it from a grandparent. 10 | 11 | ![Multilevel Inheritance](https://github.com/chavarera/PythonScript/blob/master/Class/multilevelinheritance.png) 12 | 13 | ### Algorithm 14 | 15 | 1. Create a Parent Class A. 16 | ```python 17 | class A: 18 | ``` 19 | 2.Create Class B and inherit it from class A 20 | ```python 21 | class B(A): 22 | ``` 23 | 3.Create Class C and inherit from class B 24 | ```python 25 | class C(B): 26 | ``` 27 | 4. Repeat this process until you Required. 28 | 29 | 5. Create an object of last derived class and access methods and attributes of all the above parent and grandparent class. 30 | 31 | ### Syntax 32 | ```python 33 | #Parent Class For B 34 | class : 35 | #initilize attributes and methods 36 | 37 | #Child Class for Class A And Parent class For Class C 38 | class (A): 39 | #initilize class b cand call constructor of class A 40 | 41 | #Child class for B 42 | class (B): 43 | #call the constructor of class B 44 | #Access here All the properties of class A and Class B 45 | 46 | #Create an object of C Class 47 | c1=C() 48 | ``` 49 | 50 | ### Example 1 51 | ```python 52 | class A: 53 | def __init__(self): 54 | self.Avar="I am A Class variable" 55 | class B(A): 56 | def __init__(self): 57 | A.__init__(self) 58 | self.Bvar="I am B Class variable" 59 | class C(B): 60 | def __init__(self): 61 | B.__init__(self) 62 | print(self.Avar) 63 | b1=C() 64 | ``` 65 | Output: 66 | ``` 67 | I am A Class variable 68 | ``` 69 | 70 | 71 | 72 | ### Example 2 73 | ```python 74 | #Parent Class A 75 | class A: 76 | def __init__(self): 77 | self.Avar="I am A Class variable" 78 | self.a=10 79 | 80 | #Child class B 81 | class B(A): 82 | def __init__(self): 83 | #Call the parent class A Constructor 84 | A.__init__(self) 85 | 86 | #initilize Instance variables for B class 87 | self.Bvar="I am B Class variable" 88 | self.a=20 89 | 90 | class C(B): 91 | def __init__(self): 92 | #Call the parent class B Constructor 93 | B.__init__(self) 94 | 95 | print('---------------------In Class C----------------------------') 96 | 97 | #Read Variable from class A 98 | print("--------------Class A variable--------------\n") 99 | print(self.Avar) 100 | 101 | print("\n--------------Class B variable--------------\n") 102 | #Read Variable From Class B 103 | print(self.Bvar) 104 | 105 | print('\n---------The variable from first parent class---------\n') 106 | #Print a value 107 | print(self.a) 108 | 109 | #create object of C class 110 | b1=C() 111 | ``` 112 | Output 113 | ``` 114 | #Result 115 | ---------------------In Class C---------------------------- 116 | --------------Class A variable-------------- 117 | 118 | I am A Class variable 119 | 120 | --------------Class B variable-------------- 121 | 122 | I am B Class variable 123 | 124 | ---------The variable from first parent class--------- 125 | 126 | 20 127 | ``` 128 | -------------------------------------------------------------------------------- /Class/abstractclasses.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/Class/abstractclasses.png -------------------------------------------------------------------------------- /Class/hybridinheritance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/Class/hybridinheritance.png -------------------------------------------------------------------------------- /Class/methodOverloading.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/Class/methodOverloading.png -------------------------------------------------------------------------------- /Class/multilevelinheritance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/Class/multilevelinheritance.png -------------------------------------------------------------------------------- /Class/multipleinheritance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/Class/multipleinheritance.png -------------------------------------------------------------------------------- /Class/singleinheritance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/Class/singleinheritance.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/After_Item.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/After_Item.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/Array.md: -------------------------------------------------------------------------------- 1 | ## Array 2 | 3 | #### Introduction 4 | - The array is the most commonly used data structure in most of the programming languages. 5 | - The collection of elements of the same data types grouped together called is an array. 6 | - All elements of an array must be of the same datatypes. 7 | - We can create an array in python by importing an array module. 8 | - In Python list treated as an array but the list contains a different type of element inside it where array support only a single type of element to be stored in it. 9 | 10 | #### How to create Array? 11 | First import array module as follows 12 | ```python 13 | import array 14 | ``` 15 | Create an array using array module 16 | ```python 17 | array=array.array('singletypecode',[element of similar data types]) 18 | ``` 19 | 20 | - If you pass different type element to array it will generate an error 21 | - Arrays represent basic values and behave very much like lists 22 | 23 | **Applications of An Array** 24 | 1. lookup table 25 | 2. hash table 26 | 3. heaps 27 | 28 | 29 | **Advantages of an Array** 30 | - Very easy to implement and use. 31 | - Fast data structure 32 | - Any item from any position can be accessed because of indexes are present in an array 33 | - arrays can have as many dimensions as we want 34 | - The size of the array can be changed dynamically. 35 | 36 | **Disadvantages of an Array** 37 | - Store only similar data types item in the array 38 | 39 | Examples: 40 | ```python 41 | #import array module 42 | import array 43 | 44 | #Create a integer elements array 45 | arr=array.array('i',[1,2,3,4,5,6,7]) 46 | 47 | #print array 48 | print("Normal Array") 49 | print(arr) 50 | 51 | #print type of an array 52 | print("\n Type of an Array") 53 | print(type(arr)) 54 | ``` 55 | Output: 56 | ``` 57 | Normal Array 58 | array('i', [1, 2, 3, 4, 5, 6, 7]) 59 | 60 | Type of an Array 61 | 62 | ``` 63 | -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/BasicOfQueue.md: -------------------------------------------------------------------------------- 1 | ## Queue 2 | 3 | - After Stack, Another fundamental data structure is a queue. 4 | - It's Similar to stack but insertion and deletion of element done according to 5 | "First-In-First-Out" manner. 6 | - In stack Insertion and removal of element done at the one end only, But in **Queue** insertion done at one end and removal of element done at another end so it is first in first out approach. 7 | - The first time added element will be removed First time and second inserted element removed at the second position in this way queue follows a Queue. 8 | - The queue is an Abstract data type in java it is an interface 9 | - Insert Operation done At one point and that one point is called as **Rear** 10 | - Removal Of Element Done at Another End Called as **Front** 11 | 12 | ![queue](https://github.com/chavarera/PythonScript/blob/master/DataStructureAndAlgorithm/queue.png) 13 | 14 | ### you can Perform the Following Operation on Queue 15 | 16 | #### 1. enqueue: 17 | Adding data element to abstract data types. 18 | 19 | #### 2. dequeue: 20 | Removing items from the abstract data types 21 | 22 | #### 3. peek: 23 | Peek is used to getting the last item from a queue instead of removing the last element. 24 | 25 | ### Real-Time Application of Queue 26 | - Movie Ticket Counter. 27 | - BFS(Breadth-First Search). 28 | - Job Scheduling in Operating System. 29 | - Bank line where people who come first will do his transaction first. 30 | - Keypress sequence in the keyboard. 31 | - The lines or Queue. 32 | - Vehicle waiting to pay toll on the road. 33 | 34 | 35 | ### Implementation 36 | 37 | - The queue can be implemented with dynamic arrays as well as a linked list 38 | 1. Using **queue** Module 39 | 2. Dynamic Array 40 | 3. Linked List 41 | 42 | 43 | ### Perform Operation on the queue using the queue python module 44 | 45 | #### 1.Initialize the queue 46 | - for initializing the queue data structure using *queue* Module first import *queue* model in script 47 | ``` 48 | import queue 49 | ``` 50 | - After the import of the queue module now initialize the queue object. 51 | ``` 52 | que=queue.Queue(maxszie=) 53 | ``` 54 | Following are the two common terms used in queue 55 | **1. queue Overflow** 56 | - when we try to insert data element into a Queue above is max size, it is called queue *OverFlow.* 57 | **2. queue Underflow** 58 | - when we try to remove an element from an empty queue then its called as *Underflow.* 59 | 60 | Example: 61 | ```python 62 | import queue 63 | 64 | #Initilize the queue by using maxsize 65 | que=queue.Queue(maxsize=5) 66 | print(que) 67 | ``` 68 | 69 | Output: 70 | ``` 71 | #Result: 72 | 73 | ``` 74 | 75 | 76 | ### 2.Insertion and removal item from queue 77 | - Inserting element at end of queue 78 | Syntax: 79 | ``` 80 | Queue.put(data_Element) 81 | ``` 82 | Example: 83 | ``` 84 | #import required module 85 | import queue 86 | 87 | #Initilize the queue by using maxsize 88 | que=queue.Queue(maxsize=5) 89 | print(que) 90 | 91 | 92 | #Insert 6 into queue 93 | que.put(6) 94 | print("6 Inserted") 95 | 96 | #insert 7 97 | que.put(7) 98 | print("7 inserted") 99 | 100 | #Get Element From Queue 101 | print(que.get()) 102 | print("6 is Removed") 103 | 104 | #Get Next Element From Queue 105 | print(que.get()) 106 | print("7 is Removed") 107 | ``` 108 | 109 | Output: 110 | ``` 111 | 112 | 6 Inserted 113 | 7 inserted 114 | 6 115 | 6 is Removed 116 | 7 117 | 7 is Removed 118 | ``` 119 | -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/BasicOfStack.md: -------------------------------------------------------------------------------- 1 | ## Stack 2 | 3 | ### Basic of Stacks 4 | - Simple Stack meaning arranging objects on over another. 5 | - Stack plays a very vital role in the data structure in any programming language. 6 | - A Stack is a Container of objects that are inserted and removed according to the Last-In-First-Out (LIFO) Principal. 7 | - The stack data structure allows operation at only one end that end is called top. 8 | - The stack is a Recursive data structure according to the structural definition of the stack 9 | 10 | 1. A stack is either empty 11 | or 12 | 2. It consists of one top and rest of element stacked together 13 | 14 | ![Stack](https://github.com/chavarera/PythonScript/blob/master/DataStructureAndAlgorithm/stack.png) 15 | ### Stack support two different operations 16 | ### 1. Push(Insert ELement) 17 | which adds an element to the collection. 18 | ### 2. Pop(Remove Element) 19 | removes the most recently added element that was not yet removed. 20 | 21 | - We can add an element or remove elements only from the end of the stack called the top of the stack. 22 | 23 | ### Some Real-Time Example Application of Stacks 24 | - Stack of dinner plates. 25 | - Stack of Moulded chairs. 26 | - Web browser back button(History is Saved in stack LIFO manner) 27 | last visited page saved in top of the stack and when we press back button top of the URL stack is opened in a web browser. 28 | - undo and redo operation in text Editors. 29 | - Bangle set - One has to remove the last inserted bangle to insert a new bangle in the set. 30 | - A set of books - You can only remove the last inserted book to insert a new book in the stack. 31 | 32 | 33 | ### Implementation 34 | - The stack is an Adapter class means that stack is built on top of other data structures. 35 | 36 | The stack can be implemented using 37 | ``` 38 | 1. List 39 | 2. Array List 40 | 3. Linked list 41 | 4. Vector 42 | ``` 43 | 44 | #### Implementation Of Stack Using List 45 | create empty stack using list 46 | ``` 47 | self.stack=[] 48 | ``` 49 | 50 | Function: 51 | ```python 52 | def __init__(self): 53 | self.stack=[] 54 | ``` 55 | 56 | Full Example: 57 | ```python 58 | #Create A Stack Class 59 | class STACKS: 60 | def __init__(self): 61 | self.stack=[] 62 | 63 | #Initilize Stacks Objects 64 | s1=STACKS() 65 | ``` 66 | -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/BinarySearhTree.md: -------------------------------------------------------------------------------- 1 | ## Binary Search Tree 2 | 3 | ### Binary Search Tree 4 | - As we already Know A binary tree is a tree whose children are never more than two same features are in a binary search tree along with some criteria to build it. 5 | - Binary Search Tree is one type of implementations specially designed especially for Searching. 6 | - In a Binary search tree, all the nodes are arranged in a specific order 7 | - A tree can be called as a binary search tree if and only if the maximum number of children of any of the nodes is two 8 | and the left child is always smaller than the right child 9 | - A Binary Search Tree or Ordered Binary Tree is one type of binary tree where the nodes are arranged in order 10 | 11 | - If you perform Inorder Traversal on Binary search tree you will get sorted values of inserted items 12 | 13 | 14 | Binary Search Tree (BST) is a special type of Binary Tree that follows the following condition: 15 | ``` 16 | - All the left nodes(left Subtree recursively) have a smaller value than the value of the parent node. 17 | - All the right nodes((right Subtree recursively)) have values greater than or equal to the parent node. 18 | ``` 19 | 20 | Example 1 21 | ``` 22 | 5 23 | / \ 24 | 3 9 25 | ``` 26 | 27 | Example 2 28 | ``` 29 | 50 30 | / \ 31 | 25 75 32 | / \ / \ 33 | 20 30 70 80 34 | ``` 35 | 36 | Example 3 37 | ``` 38 | 8 39 | / \ 40 | 7 12 41 | / / \ 42 | 4 11 28 43 | / \ 44 | 2 5 45 | ``` 46 | 47 | Binary Search Tree (BST) is a special form of Binary Tree data structure where each node has a comparable value, 48 | and smaller valued children attached to the left and larger valued children attached to the right. 49 | 50 | Following Example Is not Binary Search Tree 51 | ``` 52 | 7 53 | / \ 54 | 9 12 55 | ``` 56 | Because here 9 is placed at the left side of 7 which is wrong because the only small element can be placed at the left side tree of the root node. 57 | 58 | 59 | Simple Example To Create A Binary Tree 60 | ```python 61 | class Node: 62 | def __init__(self): 63 | self.value=value 64 | self.left=None 65 | self.right=None 66 | 67 | root=Node(5) 68 | root.left=Node(3) 69 | root.right=Node(9) 70 | 71 | ''' 72 | Above Example Create A Simple Binary Search Tree 73 | 5 74 | / \ 75 | 3 9 76 | ''' 77 | ``` 78 | 79 | In Next Lessons, We Are going to create some concrete example of Binary Search Tree 80 | ``` 81 | - Insert element 82 | - Search element 83 | - Delete element 84 | - Traverse elements 85 | - Sort element 86 | ``` 87 | -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/CreatenTraverseLinkedList.md: -------------------------------------------------------------------------------- 1 | ## Create and Traverse linked list 2 | 3 | #### Basic Operation 4 | ``` 5 | 1. Create Node 6 | 2. Create a Linked List 7 | 3. Traverse Linked list 8 | ``` 9 | 10 | ### 1. Create A Node 11 | 12 | - create a normal class and initialize two parameters 13 | - We already know that in single linked list node contains two block 14 | ``` 15 | 1. data block. 16 | 2. memory address of the next Node. 17 | ``` 18 | ![Simple Node](https://github.com/chavarera/PythonScript/blob/master/DataStructureAndAlgorithm/sinplenode.png) 19 | - At the time of node initialization, the memory address of the current node is set to be None 20 | - Our node class will contain two member variables data and link. 21 | - The value of the data will be set by the value passed through the constructor. 22 | - The link value will be initially set to None 23 | 24 | Example: 25 | ```python 26 | class Node: 27 | def _init_(self,data): 28 | self.data=data 29 | self.link=None 30 | ``` 31 | 32 | ### 2. Create Single Linked list Class 33 | 34 | - Create a Class for a single linked list and write down different methods for insert item, remove the item and traverse a linked list. 35 | - Initially, Singly linked list pointing to the starting or the first node of the linked list. 36 | - The Single linked list contains the only member that is start_node which is initially set to None Because the linked list will be empty 37 | at the time of the creation of the linked list. 38 | ![singleNone](https://github.com/chavarera/PythonScript/blob/master/DataStructureAndAlgorithm/singlelinkedlist.png) 39 | 40 | Example 41 | ```python 42 | #Create Node 43 | class Node: 44 | def _init_(self,data): 45 | self.data=data 46 | self.link=None 47 | 48 | 49 | #Simple Initialization of Single Linked List 50 | class SingleLinkedList: 51 | #Constructor of a class contains only one member 52 | def _init_(self): 53 | #Member of the single linked list. 54 | self.start_node=None #Set to None for Initialization 55 | ``` 56 | 57 | ### 3.Traversing a linked list 58 | - **self.start_node** is the current node and if it is **None** then the Linked list is empty. 59 | ```python 60 | if self.start_node is None: 61 | print("No Element In List ") 62 | return 63 | ``` 64 | - if **self.start_node** is not **None** then print the node with **node.data**. 65 | - And Assign Node to next link node 66 | ```python 67 | node=node.link 68 | ``` 69 | ![Traverse](https://github.com/chavarera/PythonScript/blob/master/DataStructureAndAlgorithm/traverselinkedkist.png) 70 | 71 | Example: 72 | ```python 73 | def TraverseList(self): 74 | if self.start_node is None: 75 | print("No Element In List ") 76 | return 77 | else: 78 | node=self.start_node 79 | while node is not None: 80 | print(node.data) 81 | node=node.link 82 | ``` 83 | **self.start_node** is the start node of the single linked list so it assigned to a node if it is **None** as start node and traverse One By one 84 | -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/DequeUsingList.md: -------------------------------------------------------------------------------- 1 | ## Implementation of Deque Using List 2 | 3 | 4 | #### Initialize blank Deque Using List 5 | ``` 6 | def __init__(self): 7 | print("Initialize blank Deque Using List") 8 | self.dq=[] 9 | ``` 10 | 11 | #### Add Element at Left End Of Deque 12 | ``` 13 | def AddLeft(self,data): 14 | '''Add Element at Left End Of Deque''' 15 | self.dq.insert(0,data) 16 | ``` 17 | 18 | #### Add Element at Right End Of Deque 19 | ``` 20 | def AddRight(self,data): 21 | '''Add Element at Right End Of Deque''' 22 | self.dq.append(data) 23 | ``` 24 | #### Remove Element From Left End Of Deque 25 | ``` 26 | def PopLeft(self): 27 | '''Remove Element From Left End Of Deque''' 28 | self.dq.pop(0) 29 | ``` 30 | 31 | #### Remove Element From Right End Of Deque 32 | ``` 33 | def PopRight(self): 34 | '''Remove Element From Right End Of Deque''' 35 | self.dq.pop() 36 | ``` 37 | 38 | 39 | Full Example 40 | ```python 41 | class Deque: 42 | def __init__(self): 43 | print("Initialize blank Deque Using List") 44 | self.dq=[] 45 | 46 | def AddLeft(self,data): 47 | '''Add Element at Left End Of Deque''' 48 | self.dq.insert(0,data) 49 | 50 | def AddRight(self,data): 51 | '''Add Element at Right End Of Deque''' 52 | self.dq.append(data) 53 | 54 | def PopLeft(self): 55 | '''Remove Element From Left End Of Deque''' 56 | self.dq.pop(0) 57 | 58 | def PopRight(self): 59 | '''Remove Element From Right End Of Deque''' 60 | self.dq.pop() 61 | 62 | def TopLeft(self): 63 | '''Top Left Element''' 64 | return self.dq[0] 65 | 66 | def TopRight(self): 67 | '''Top Right Element''' 68 | return self.dq[-1] 69 | 70 | def Show(self): 71 | return self.dq 72 | d=Deque() 73 | print("\nBlank Deque") 74 | print(d.Show()) 75 | 76 | #Add Element 5 77 | d.AddRight(5) 78 | 79 | #print deque 80 | data=d.Show() 81 | 82 | print("\nDeque After Adding 5") 83 | print(data) 84 | 85 | 86 | #Add Element At the Right End 87 | #Add 7 88 | d.AddRight(7) 89 | 90 | #Add 9 91 | d.AddRight(9) 92 | 93 | print("\nDeque After Adding 7 and 9 at Right end") 94 | print(data) 95 | 96 | 97 | #Add 6 element at Left Side End 98 | d.AddLeft(6) 99 | 100 | print("\nDeque After Adding 6 at Left End") 101 | print(data) 102 | #----------------------------TOP ELEMENT------------------------------ 103 | print("\nTop Element At Right End") 104 | right=d.TopRight() 105 | print(right) 106 | 107 | 108 | print("\nTop Element At Left End") 109 | left=d.TopLeft() 110 | print(left) 111 | #----------------------------Remove Element--------------------------- 112 | 113 | #Remove 6 From Right End 114 | d.PopRight() 115 | 116 | print("\nDeque After Remoing Element from Right End") 117 | print(data) 118 | 119 | #Remove 6 From Left End 120 | d.PopLeft() 121 | 122 | print("\nDeque After Remoing Element from Left End") 123 | print(data) 124 | ``` 125 | 126 | Output 127 | ``` 128 | Initialize blank Deque Using List 129 | 130 | Blank Deque 131 | [] 132 | 133 | Deque After Adding 5 134 | [5] 135 | 136 | Deque After Adding 7 and 9 at Right end 137 | [5, 7, 9] 138 | 139 | Deque After Adding 6 at Left End 140 | [6, 5, 7, 9] 141 | 142 | Top Element At Right End 143 | 9 144 | 145 | Top Element At Left End 146 | 6 147 | 148 | Deque After Remoing Element from Right End 149 | [6, 5, 7] 150 | 151 | Deque After Remoing Element from Left End 152 | [5, 7] 153 | ``` 154 | -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/IMG_20190823_143918.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/IMG_20190823_143918.jpg -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/QueueImplementationUsingList.md: -------------------------------------------------------------------------------- 1 | ## Queue Implementation using list 2 | 3 | 4 | ### Introduction 5 | - You can Implement Queue Using defualt Data Structure list 6 | - Create A simple Class with any Name 7 | - Initialize Queue in Constructor 8 | ```python 9 | def _init_(self): 10 | self.queue=[] 11 | ``` 12 | - Append Element At the End of Queue 13 | ```python 14 | #Add element at rear part 15 | def Put(self,data): 16 | self.queue.append(data) 17 | ``` 18 | - Remove element Which is Inserted First 19 | ```python 20 | #Remove Element From Front Part 21 | def Pop(self): 22 | if self.queue==[]: 23 | return "Empty Queue" 24 | else: 25 | return self.queue.pop(0) 26 | ``` 27 | - Get Rear Element 28 | ```python 29 | #Get Last Element 30 | def GetRear(self): 31 | if self.queue==[]: 32 | return "Empty Queue" 33 | else: 34 | return self.queue[0] 35 | ``` 36 | 37 | - Get Front Element 38 | ```python 39 | #Get First ELment 40 | def GetFront(self): 41 | if self.queue==[]: 42 | return "Empty Queue" 43 | else: 44 | return self.queue[-1] 45 | ``` 46 | 47 | Example: 48 | ```python 49 | #Queue using List 50 | class Queue: 51 | #Initialize Empty Queue 52 | def __init__(self): 53 | self.queue=[] 54 | 55 | #Add element at rear part 56 | def Put(self,data): 57 | self.queue.append(data) 58 | 59 | #Remove Element From Front Part 60 | def Pop(self): 61 | if self.queue==[]: 62 | return "Empty Queue" 63 | else: 64 | self.queue.pop(0) 65 | 66 | #Get First ELment 67 | def GetFront(self): 68 | if self.queue==[]: 69 | return "Empty Queue" 70 | else: 71 | return self.queue[-1] 72 | 73 | #Get Last Element 74 | def GetRear(self): 75 | if self.queue==[]: 76 | return "Empty Queue" 77 | else: 78 | return self.queue[0] 79 | 80 | 81 | #Initilize Queue Object 82 | q=Queue() 83 | 84 | #Insert 6 Into Queue 85 | q.Put(6) 86 | print("6 element is Inserted") 87 | 88 | #Insert 7 89 | q.Put(7) 90 | print("7 element is Inserted") 91 | 92 | #Insert 8 93 | q.Put(8) 94 | print("8 element is Inserted") 95 | 96 | #Print Get Front Element 97 | print("Element At Front") 98 | print(q.GetFront()) 99 | 100 | print("Element At Rear") 101 | #Get Last Element 102 | print(q.GetRear()) 103 | 104 | 105 | #Pop Last Element 106 | q.Pop() 107 | 108 | #Now Print Last Element 109 | print("After Popping Rear Element") 110 | print(q.GetRear()) 111 | ``` 112 | 113 | 114 | 115 | output: 116 | ``` 117 | 6 element is Inserted 118 | 7 element is Inserted 119 | 8 element is Inserted 120 | Element At Front 121 | 8 122 | Element At Rear 123 | 6 124 | After Popping Rear Element 125 | 7 126 | ``` 127 | -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/RemoveNodeInLinkedList.md: -------------------------------------------------------------------------------- 1 | ## Remove Node From Linked List 2 | 3 | - Return "No Element" if the linked list is Empty 4 | ``` 5 | if n is None: 6 | print("\n No Element in List") 7 | return 8 | ``` 9 | - If the linked list contains element iterate linked list using while loop 10 | ``` 11 | while n is not None: 12 | n=n.link 13 | ``` 14 | - and at every loop compare node data value with required node (For Deletion) 15 | ``` 16 | n.data==data 17 | ``` 18 | - If Node Found break the loop 19 | ``` 20 | if n.data==data: 21 | break 22 | ``` 23 | - And Assign Data of that node of next node data and link of that node to be next of next node 24 | ``` 25 | n.data=n.link.data 26 | n.link=n.link.link 27 | ``` 28 | 29 | Function: 30 | ```python 31 | def RemoveNode(self,data): 32 | #initialize the Head Node (start_node) 33 | n=self.start_node 34 | 35 | #If No element Present in the linked list 36 | if n is None: 37 | print("\n No Element in List") 38 | return 39 | #Iterate through Whole List 40 | while n is not None: 41 | # if Node data found break the loop 42 | if n.data==data: 43 | break 44 | n=n.link 45 | 46 | #If Element is not found in the list 47 | if n is None: 48 | print("Element Node Not Found in Linked List") 49 | else: 50 | #if node found assign node data to data of next node 51 | n.data=n.link.data 52 | 53 | #change that node pointer to next of next node pointer 54 | n.link=n.link.link 55 | ``` 56 | Full Example: 57 | ```python 58 | class Node: 59 | def __init__(self,data): 60 | self.data=data 61 | self.link=None 62 | class SingleList: 63 | def __init__(self): 64 | self.start_node=None 65 | def Push(self,data): 66 | n_node=Node(data) 67 | n_node.link=self.start_node 68 | self.start_node=n_node 69 | return 70 | def Traverse(self): 71 | n=self.start_node 72 | while n is not None: 73 | print(n.data,end="->") 74 | n=n.link 75 | 76 | def RemoveNode(self,data): 77 | #initialize the Head Node (start_node) 78 | n=self.start_node 79 | 80 | #If No element Present in the linked list 81 | if n is None: 82 | print("\n No Element in List") 83 | return 84 | #Iterate through Whole List 85 | while n is not None: 86 | # if Node data found break the loop 87 | if n.data==data: 88 | break 89 | n=n.link 90 | 91 | #If Element is not found in the list 92 | if n is None: 93 | print("Element Node Not Found in Linked List") 94 | else: 95 | #if node found assign node data to data of next node 96 | n.data=n.link.data 97 | 98 | #change that node pointer to next of next node pointer 99 | n.link=n.link.link 100 | 101 | #Simple Initialize the single linked list 102 | s1=SingleList() 103 | 104 | #Add Node 5,12,18 105 | s1.Push(5) 106 | s1.Push(12) 107 | s1.Push(18) 108 | 109 | #Print Normal Linked List 110 | print("\nNormal Linked List") 111 | s1.Traverse() 112 | 113 | #Remove 12 Node from Given Linked list 114 | s1.RemoveNode(12) 115 | 116 | #Print Normal Linked List 117 | print("\n\nLinked List After Removing 12 Node") 118 | s1.Traverse() 119 | ``` 120 | 121 | Output: 122 | ```python 123 | Normal Linked List 124 | 18 -> 12 -> 5 -> 125 | 126 | Linked List After Removing 12 Node 127 | 18 -> 5 -> 128 | ``` 129 | -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/UpdateLinkedList.md: -------------------------------------------------------------------------------- 1 | ## Updating The Node Value 2 | 3 | - Return **"No Element"** if linked list is Empty 4 | ``` 5 | if n is None: 6 | print("\n No Element in List") 7 | return 8 | ``` 9 | - If linked list contains element iterate linked list using while loop 10 | ``` 11 | while n is not None: 12 | n=n.link 13 | ``` 14 | - and at every loop compare node data value with required node (For Deletion) 15 | ``` 16 | n.data==data 17 | ``` 18 | - If Node Found break the loop 19 | ``` 20 | if n.data==data: 21 | break 22 | ``` 23 | - And Assign Data of that node of next node data and link of that node to be next of next node 24 | ``` 25 | n.data=Replace_Value 26 | ``` 27 | Function: 28 | ```python 29 | def UpdateNode(self,data,replace): 30 | #initialize the Head Node (start_node) 31 | n=self.start_node 32 | if n is None: 33 | print("\n No Element in List") 34 | return 35 | #Iterate through Whole List 36 | while n is not None: 37 | # if Node data found break the loop 38 | if n.data==data: 39 | break 40 | n=n.link 41 | 42 | #If Element is not found in the list 43 | if n is None: 44 | print("Element Node Not Found in Linked List") 45 | else: 46 | #if node found assign value to that node 47 | n.data=replace 48 | ``` 49 | 50 | Full Example: 51 | ```python 52 | class Node: 53 | def __init__(self,data): 54 | self.data=data 55 | self.link=None 56 | 57 | class SingleList: 58 | def __init__(self): 59 | self.start_node=None 60 | def Push(self,data): 61 | n_node=Node(data) 62 | n_node.link=self.start_node 63 | self.start_node=n_node 64 | return 65 | def Traverse(self): 66 | n=self.start_node 67 | while n is not None: 68 | print(n.data,end="->") 69 | n=n.link 70 | 71 | def UpdateNode(self,data,replace): 72 | #initialize the Head Node (start_node) 73 | n=self.start_node 74 | if n is None: 75 | print("\n No Element in List") 76 | return 77 | #Iterate through Whole List 78 | while n is not None: 79 | # if Node data found break the loop 80 | if n.data==data: 81 | break 82 | n=n.link 83 | 84 | #If Element is not found in the list 85 | if n is None: 86 | print("Element Node Not Found in Linked List") 87 | else: 88 | #if node found assign value to that node 89 | n.data=replace 90 | 91 | 92 | #Simple Initialize the single linked list 93 | s1=SingleList() 94 | 95 | #Add Node 5,12,18 96 | s1.Push(5) 97 | s1.Push(12) 98 | s1.Push(18) 99 | 100 | #Print Normal Linked List 101 | print("\nNormal Linked List") 102 | s1.Traverse() 103 | 104 | #Replace 12 Node with 7 105 | replace=7 106 | s1.UpdateNode(12,replace) 107 | 108 | #Print Normal Linked List 109 | print("\n\nLinked List After Replace 12 Node With 7") 110 | s1.Traverse() 111 | 112 | ``` 113 | 114 | Output: 115 | ``` 116 | Normal Linked List 117 | 18->12->5-> 118 | 119 | Linked List After Replace 12 Node With 7 120 | 18->7->5-> 121 | ``` 122 | -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/array.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/array.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/atEnd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/atEnd.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/dequeue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/dequeue.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/dequeue2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/dequeue2.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/insertatbegining.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/insertatbegining.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/llis2t.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/llis2t.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/llist.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/llist.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/queue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/queue.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/singlelinkedlist.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/singlelinkedlist.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/sinplenode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/sinplenode.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/stack.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/stack.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/stackOperation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/stackOperation.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/traverselinkedkist.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/traverselinkedkist.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/binarytree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/binarytree.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/child.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/child.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/degree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/degree.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/depth.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/depth.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/edge.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/edge.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/height.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/height.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/inorder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/inorder.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/internalcode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/internalcode.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/leaf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/leaf.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/level.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/level.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/node.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/node.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/parent.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/parent.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/postorder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/postorder.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/preorder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/preorder.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/root.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/root.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/siblings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/siblings.png -------------------------------------------------------------------------------- /DataStructureAndAlgorithm/tree/tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/DataStructureAndAlgorithm/tree/tree.png -------------------------------------------------------------------------------- /Data_Structure_In_Python/Dictionary/1.BasicOfDictionary.py: -------------------------------------------------------------------------------- 1 | ##------------------------------------------------------------------------------------------------------ 2 | #Created By:Ravishankar Chavare 3 | #version:python 3.7 4 | #Date:15/03/2019 5 | #File_des:Introduction of Dictionary Data Structure 6 | ##------------------------------------------------------------------------------------------------------ 7 | 8 | ''' 9 | Dictionary: 10 | -Dictionary holds key:value pair which unlike other data types that hold only single element 11 | -Key value is provided in the dictionary to make it more optimized. 12 | -Python Dictionary works similar to real world Dictionary when key element is uniques 13 | ''' 14 | 15 | 16 | #create Simple Dictionary 17 | blankdict=dict() 18 | 19 | 20 | #Dict with element 21 | elemntdict={'name':'jhon','roll':20,'college':'MIT'} 22 | 23 | #simple print dict 24 | print(elementdict) 25 | 26 | 27 | #----------------------------------------------------------------------------------------- 28 | # Accessing Values and keys From dictionary 29 | #----------------------------------------------------------------------------------------- 30 | 31 | #print name from dictionary 32 | name=elemntdict['name'] 33 | print(name) 34 | 35 | #Accessing Only keys from dictionary 36 | keys=elemntdict.keys() 37 | print(key) 38 | 39 | #Accessing Values Only 40 | vals=elemntdict.values() 41 | print(vals) 42 | 43 | #useing For Loop iterate the dictionary 44 | 45 | for key,value in elemntdict.items(): 46 | print(key,value) 47 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/Dictionary/2.AddingRemovingElement.py: -------------------------------------------------------------------------------- 1 | ##------------------------------------------------------------------------------------------------------ 2 | #Created By:Ravishankar Chavare 3 | #version:python 3.7 4 | #Date:15/03/2019 5 | #File_des:Adding And Removing element from Dictionary 6 | ##------------------------------------------------------------------------------------------------------ 7 | 8 | 9 | #------------------------------------------------------------------- 10 | # Adding Another key and Value TO Dictionary 11 | #------------------------------------------------------------------- 12 | simpledict={'name':'jhon','roll':12} 13 | 14 | 15 | #add age =10 in simpledict 16 | simpledict['age']=10 17 | print(simpledict) 18 | 19 | 20 | #adding imageurl='' 21 | simpledict['imageurl']='' 22 | print(simpledict) 23 | 24 | 25 | #------------------------------------------------------------------- 26 | # Removing Value From Dictionary 27 | #------------------------------------------------------------------- 28 | 29 | #use pop method to remove items from dict 30 | 31 | simpledict.pop('roll') 32 | print(simpledict) 33 | 34 | 35 | #------------------------------------------------------------------- 36 | # Deleting And Clearing Dictionary 37 | #------------------------------------------------------------------- 38 | 39 | #For Clearing the Dict (empty) 40 | simpledict.clear() 41 | print(simpledict) 42 | 43 | #use del keyword to delete Dictionary 44 | del simpledict 45 | 46 | 47 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/Dictionary/BasicOperation.md: -------------------------------------------------------------------------------- 1 | ## Basic operation on dictionary 2 | 3 | 4 | ### 1. Add new key-value element in the dictionary 5 | 6 | we can add key and value in a dictionary using the key. 7 | 8 | Syntax: 9 | ```python 10 | dictname[key]=value 11 | ``` 12 | Example: 13 | ```python 14 | mydict={"name":"ravi","age":20} 15 | mydict["bdate"]="26/01/1993" 16 | 17 | print(mydict) 18 | ``` 19 | Output: 20 | ``` 21 | {"name":"ravi","age":20,"bdate":"26/01/1993"} 22 | ``` 23 | 24 | 25 | ### 2. Updating value in dictionary 26 | Syntax: 27 | ```python 28 | dictname[existed key]="new value" 29 | ``` 30 | 31 | Example: 32 | ```python 33 | mydict={"name":"ravi","age":20} 34 | #update name with jhon 35 | 36 | mydict["name"]="jhon" 37 | 38 | print(mydict) 39 | ``` 40 | Output: 41 | ``` 42 | {"name":"jhon","age":20} 43 | ``` 44 | 45 | ### 3. Removing key-value pair from the dictionary 46 | 47 | use built in method **pop()** to remove element from dictionary 48 | 49 | Syntax: 50 | ```python 51 | dictname.pop("keyname") 52 | ``` 53 | 54 | Example: 55 | ```python 56 | mydict={"name":"ravi","age":20} 57 | #remove age 58 | mydict.pop("age") 59 | 60 | print(mydict) 61 | ``` 62 | Output: 63 | ``` 64 | {"name":"ravi"} 65 | ``` 66 | 67 | ### 4. Clear all element of the dictionary 68 | 69 | **clear()** is a built-in method used to empty the dictionary. 70 | 71 | Syntax: 72 | ```python 73 | dictname.clear() 74 | ``` 75 | 76 | Example: 77 | ```python 78 | mydict={"name":"ravi","age":20} 79 | #clear all element 80 | mydict.clear() 81 | 82 | print(mydict) 83 | ``` 84 | Output: 85 | ``` 86 | {} 87 | ``` 88 | 89 | ### 5. Deleting dictionary 90 | **del** keyword used to delete complete dictionary. 91 | 92 | Syntax: 93 | ```python 94 | del dictionary_name 95 | ``` 96 | Example 97 | ```python 98 | mydict={"name":"ravi","age":20} 99 | del mydict 100 | print(mydict) 101 | ``` 102 | Output: 103 | ``` 104 | NameError: name 'mydict' is not defined 105 | ``` 106 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/List/2.LoopOnList.py: -------------------------------------------------------------------------------- 1 | '''you can use for loop''' 2 | country=['india','america','japan','china'] 3 | 4 | '''To get list item one after one use for''' 5 | 6 | for item in country: 7 | print(item) -------------------------------------------------------------------------------- /Data_Structure_In_Python/List/3.Split_List_Using_Missing_denometer.py: -------------------------------------------------------------------------------- 1 | from itertools import * 2 | from operator import itemgetter 3 | 4 | #Your List 5 | a=[2,3,4,7,8,10] 6 | 7 | for k, g in groupby(enumerate(a), lambda (i,x):i-x): 8 | datas=map(itemgetter(1), g) 9 | #Spplitted Lists 10 | print(datas) 11 | 12 | ''' 13 | Output 14 | [2, 3, 4] 15 | [7, 8] 16 | [10] 17 | ''' 18 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/List/ExtendedSlicing.md: -------------------------------------------------------------------------------- 1 | ## Extended Slicing On List 2 | 3 | - Ever since Python 1.4, the slicing syntax has supported an optional third **step** or **stride** argument. 4 | 5 | Syntax: 6 | ```python 7 | Listname[startindex:endindex:step] 8 | ``` 9 | Other valid syntax are 10 | 11 | - start list from 0 index 12 | ```python 13 | #start index field leave it blank 14 | Listname[:endindex:step] 15 | 16 | ``` 17 | - Here start from 0 indexes and end at last element with a given step 18 | ```python 19 | #start index and end index leave it blank 20 | Listname[::step] 21 | ``` 22 | - here start from start index and end at last element with the given step 23 | ```python 24 | # end index leave it blank 25 | Listname[startindex::step] 26 | ``` 27 | 28 | - s[i:j:k] is 29 | **"slice of s from i to j with step k".** When i and are absent, the whole sequence is assumed and thus **s[::k]** means "every k-th item". 30 | 31 | 32 | Examples: 33 | 34 | How to print 2,4,6 35 | ```python 36 | lists=[0,1,2,3,4,5,6,7,8,9] 37 | start=2 38 | end=8 39 | step=2 40 | result=lists[start:end:step] 41 | print(result) 42 | #Result : [2,4,6] 43 | ``` 44 | output: 45 | ``` 46 | [2, 4, 6] 47 | ``` 48 | 49 | - **lists[::n]** is a sequence of each **n-th** item in the entire sequence. 50 | 51 | - [::3] just means that you have not specified any start or end indices for your slice. Since you have specified a step, 3, this will take every third entry of something starting at the first index. 52 | For example: 53 | ```python 54 | lists=[0,1,2,3,4,5,6,7,8,9] 55 | result=lists[::3] 56 | print(result) 57 | ``` 58 | Output: 59 | ``` 60 | [0, 6,9] 61 | ``` 62 | Let's take every 3rd item from second position list 63 | 64 | ```python 65 | lists=[0,1,2,3,4,5,6,7,8,9] 66 | result=lists[2::3] 67 | print(result) 68 | ``` 69 | Output: 70 | ``` 71 | [2,5,8] 72 | ``` 73 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/List/ListComprehension.md: -------------------------------------------------------------------------------- 1 | ## List comprehension 2 | 3 | ### Introduction 4 | - List comprehension Help us to reduce the number of line code. 5 | - List comprehension is generally more compact and faster than normal functions and loops for creating a list. 6 | - List comprehensions are used for creating new lists from other iterables. 7 | - List comprehension is an elegant way to define and create lists based on existing lists. 8 | 9 | Syntax: 10 | ```python 11 | Newlist=[expression(item) for item in list] 12 | ``` 13 | Example: 14 | 15 | Create a list which contains 1 to 10 number 16 | 17 | Using normal for loop 18 | ```python 19 | #initilize empty list 20 | lst=[] 21 | for i in range(1, 11) : 22 | lst.append(i) 23 | print(lst) 24 | ``` 25 | Output: 26 | ``` 27 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 28 | ``` 29 | 30 | Now using list comprehension 31 | ```python 32 | #using List comprehension 33 | lst=[i for i in range(1,11)] 34 | print(lst) 35 | ``` 36 | output: 37 | ``` 38 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 39 | ``` 40 | 41 | ### list comprehension using conditions 42 | 43 | Syntax: 44 | ```python 45 | Newlist=[expression(item) for item in list conditions] 46 | ``` 47 | 48 | Example: 49 | Create a list which contains 50 | 2,4,6,8,10 51 | 52 | Normal for loop 53 | ```python 54 | #blank list 55 | lst=[] 56 | for i in range(11) : 57 | if i%2==0: 58 | lst.append(i) 59 | print(lst) 60 | ``` 61 | Output: 62 | ``` 63 | [0, 2, 4, 6, 8, 10] 64 | ``` 65 | Using List comprehension 66 | ```python 67 | #using List comprehension 68 | lst=[i for i in range(11) if i%2==0] 69 | print(lst) 70 | ``` 71 | Output: 72 | ``` 73 | [0, 2, 4, 6, 8, 10] 74 | ``` 75 | You can achieve above sequence using **range(2,11,2)** also. But we need to understand conditional statement inside list comprehension so we use normal range function. 76 | 77 | 78 | ### If else :bomb: in list comprehension. 79 | Example: 80 | Find out an even or odd number from 1 to 10 81 | 82 | Using normal for loop 83 | ```python 84 | lst=[] 85 | for i in range(1,11): 86 | if i%2==0: 87 | lst.append("Even") 88 | else: 89 | lst.append("odd") 90 | print(lst) 91 | ``` 92 | Output: 93 | ``` 94 | ['odd', 'Even', 'odd', 'Even', 'odd', 'Even', 'odd', 'Even', 'odd', 'Even'] 95 | ``` 96 | 97 | Using list comprehension 98 | ```python 99 | lst=["Even" if i%2==0 else "odd" for i in range(1,11)] 100 | print(lst) 101 | ``` 102 | Output: 103 | ``` 104 | ['odd', 'Even', 'odd', 'Even', 'odd', 'Even', 'odd', 'Even', 'odd', 'Even'] 105 | ``` 106 | 107 | ### Error In List Comprehension 108 | 109 | expression in a list comprehension can only accept single variable of any type(string, list, int, tuple) 110 | the object we can not add element more than one 111 | 112 | Example 113 | ```python 114 | lst=[i,i*2 for i in range(5)] 115 | ``` 116 | Output: 117 | ``` 118 | lst=[i,i*2 for i in range(5)] 119 | ^ 120 | SyntaxError: invalid syntax 121 | ``` 122 | 123 | This will always generate error **Invalid syntax** 124 | Correct way 125 | ```python 126 | #using Tuple 127 | lst=[(i,i*2) for i in range(5)] 128 | print(lst) 129 | #Result:[(0, 0), (1, 2), (2, 4), (3, 6), (4, 8)] 130 | 131 | #Using List 132 | lst=[[i,i*2] for i in range(5)] 133 | print(lst) 134 | #Result:[[0, 0], [1, 2], [2, 4], [3, 6], [4, 8]] 135 | ``` 136 | Output: 137 | ``` 138 | [(0, 0), (1, 2), (2, 4), (3, 6), (4, 8)] 139 | [[0, 0], [1, 2], [2, 4], [3, 6], [4, 8]] 140 | ``` 141 | **Note** every list comprehension can be rewritten in for loop, 142 | but every for loop can’t be rewritten in the form of list comprehension. 143 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/Set/1.BasicOfSet.py: -------------------------------------------------------------------------------- 1 | ##------------------------------------------------------------------------------------------------------ 2 | #Created By:Ravishankar Chavare 3 | #version:python 3.7 4 | #Date:15/03/2019 5 | #File_des:Introduction of Set Data Structure 6 | ##------------------------------------------------------------------------------------------------------ 7 | 8 | 9 | ''' 10 | Set 11 | -A set is a collection which is unordered and unindexed. 12 | -In Python sets are written with curly brackets. 13 | 14 | simple syntax 15 | myset={'value1','value2'} 16 | or 17 | myset=set() #for blank set 18 | 19 | ''' 20 | #Create a Simple set with three elements 21 | simpleset={'first','second','third'} 22 | 23 | #TO get item from set 24 | ''' 25 | Set doesnt contain index value becuase it is unordered list 26 | we can use loop to get item from set or use 'in' to get elements 27 | ''' 28 | #print the set 29 | for i in simpleset: 30 | print(i) 31 | 32 | #Chek item in set 33 | checkitem="first" in simpleset 34 | print(checkitem) 35 | 36 | #To get length of set 37 | length=len(simpleset) 38 | print(length) 39 | 40 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/Set/2.AddingAndRemovingElement.py: -------------------------------------------------------------------------------- 1 | ##------------------------------------------------------------------------------------------------------ 2 | #Created By:Ravishankar Chavare 3 | #version:python 3.7 4 | #Date:15/03/2019 5 | #File_des:Adding And Removing Element From Set 6 | ##------------------------------------------------------------------------------------------------------ 7 | 8 | 9 | #Simple Create a set 10 | myset={1,2,3,4,5,6,7,8,9} 11 | print(myset) 12 | 13 | #NOTE:set contains unique elements 14 | #------------------------------------------------------ 15 | # Adding Element 16 | #----------------------------------------------------- 17 | ''' 18 | To adding element in set there are two way 19 | 1.add: for adding single element at a time 20 | 2.update for adding multiple element into set 21 | ''' 22 | #add a single element to set using add method 23 | myset.add(10) 24 | 25 | print('After adding element10 :',myset) 26 | 27 | #Add multiple element inside in a set 28 | myset.update([11,12,13]) 29 | print('After multiple value Updating:',myset) 30 | 31 | #------------------------------------------------------ 32 | # Removing Element 33 | #----------------------------------------------------- 34 | ''' 35 | To remove an item in a set, use the remove(), or the discard() method. 36 | 37 | 1.remove(): If the item to remove does not exist this will raise error 38 | 2.discard(): If the item to remove does not exist this will done without raising error 39 | 40 | you can also use pop() method to remove last element but in set there is no indexing so which elemnent at last postion is hard to tell 41 | ''' 42 | 43 | #using remove() 44 | myset.remove(10) 45 | print('After removing element 10 :',myset) 46 | 47 | #Using discard() 48 | myset.discarrd(11) 49 | print('After discarding element 11 :',myset) 50 | 51 | #using pop() 52 | myset.pop() 53 | print('after popping one element :',myset) 54 | 55 | #------------------------------------------------------ 56 | # Deleting and Clearing Set 57 | #----------------------------------------------------- 58 | 59 | #1.Clear the set 60 | myset.clear() 61 | 62 | #2.delete the set this will completely remove the set from refrences 63 | del myset 64 | 65 | 66 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/Set/BasicOfSet.md: -------------------------------------------------------------------------------- 1 | ## Set 2 | 3 | ### What is a set in Python? 4 | - A set is a collection that is unordered and unindexed. In Python, sets are written with curly brackets(**{}**). 5 | - Every element is unique and must be immutable (which cannot be changed). but set itself mutable objects 6 | - Sets are unordered, so the items will appear in random order. 7 | 8 | ### How to create a set? 9 | - you can create a set using curly braces or using built-in function **set()**. 10 | 11 | Synatx: 12 | ```python 13 | setname={element} 14 | setname1=set(elements) 15 | ``` 16 | Example: 17 | You can not create a blank set like this 18 | ```python 19 | blankset={} 20 | print(type(blankset)) 21 | ``` 22 | Output: 23 | ``` 24 | 25 | ``` 26 | Create blank Set using built in function 27 | ```python 28 | myset=set() 29 | print(type(myset)) 30 | ``` 31 | Output: 32 | ``` 33 | 34 | ``` 35 | 36 | Create a set with 1,2,3,4 elements 37 | ```python 38 | myset={1,2,3,4} 39 | print(myset) 40 | ``` 41 | Output: 42 | ``` 43 | {1,2,3,4} 44 | ``` 45 | 46 | - Set Can not Contain any mutable object such as list 47 | Example: 48 | ```python 49 | my_set = {1, 2, [3, 4]} 50 | ``` 51 | Output: 52 | ``` 53 | TypeError: unhashable type: 'list' 54 | ``` 55 | 56 | ### Accessing Items From a set 57 | - You can not access Element referring by index because the set is unordered and the item has no index. 58 | - You can use for loop for accessing the element as follows 59 | Example: 60 | ```python 61 | myset={1,2,3,4} 62 | for i in myset: 63 | print(i) 64 | ``` 65 | Output 66 | ``` 67 | 1 68 | 2 69 | 3 70 | 4 71 | ``` 72 | ### Check Element present inset or not 73 | - **in** keyword is used to check the existence of an element in the set 74 | - Return **True** if element exists in a set otherwise Return False 75 | 76 | Example: 77 | ```python 78 | color={'red','green','blue'} 79 | if('red' in color): 80 | print('red is present') 81 | else: 82 | print('red is not found') 83 | ``` 84 | Output: 85 | ``` 86 | red is present 87 | ``` 88 | 89 | ### Get the set length 90 | Example 91 | ```python 92 | color={'red','green','blue'} 93 | length=len(color) 94 | print(length) 95 | ``` 96 | Output: 97 | ``` 98 | 3 99 | ``` 100 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/Set/InsertRemoveitemfromset.md: -------------------------------------------------------------------------------- 1 | ## Insert,Delete Update Element In Set 2 | 3 | 4 | 5 | ## 1.Add Items to Set 6 | To add element inside set there are two built-in function 7 | ``` 8 | 1. add() 9 | 2. update() 10 | ``` 11 | 12 | #### 1.add() 13 | - To add one item to a set use the **add()** method. 14 | - The set **add()** method adds a given element to a set if the element is not present in the set 15 | Syntax: 16 | ```python 17 | setname.add(element) 18 | ``` 19 | 20 | Example: 21 | ```python 22 | color={"red","green","blue"} 23 | 24 | #add new element "black" to set 25 | color.add("black") 26 | print(color) 27 | ``` 28 | Output: 29 | ``` 30 | {"red","green","black","blue"} 31 | ``` 32 | - If the element is alredy present in the set then it will not added again to set , 33 | because set do not contain any duplicate value. 34 | 35 | Example: 36 | ```python 37 | color={"red","green","blue"} 38 | #add new element "blue" to set 39 | color.add("blue") 40 | print(color) 41 | ``` 42 | Output: 43 | ``` 44 | {"red","green","blue"} 45 | ``` 46 | 47 | 48 | #### 2.update() 49 | - Add multiple items to a set, using the **update()** method 50 | Syntax: 51 | ```python 52 | setname.update(iterable object) 53 | ``` 54 | Example: 55 | ```python 56 | color={"red","green","blue"} 57 | #Add "black" and "orange" to set 58 | color.update(["black","orange"]) 59 | print(color) 60 | ``` 61 | Output: 62 | ``` 63 | {'orange', 'red', 'green', 'blue', 'black'} 64 | ``` 65 | 66 | ## 2.Remove Items from set 67 | To remove an element from set there are following built-in function 68 | ``` 69 | 1. remove() 70 | 2. discard() 71 | 3. pop() 72 | ``` 73 | 74 | #### 1.remove() 75 | - **remove()** method removes the element from the set only if the element is present in the set. 76 | - If the element is not present in the set, then an error or exception is raised. 77 | 78 | Example: 79 | ```python 80 | color={"red","green","blue"} 81 | #remove "red" 82 | color.remove("red") 83 | print(color) 84 | ``` 85 | Output: 86 | ``` 87 | {"green","blue"} 88 | ``` 89 | Example: 90 | ```python 91 | color={"red","green","blue"} 92 | #remove "black" 93 | color.remove("black") 94 | ``` 95 | Output: 96 | ``` 97 | KeyError: 'black' 98 | ``` 99 | #### 2.discard() 100 | - **discard()** method removes the element from set only if the element is present in the set. 101 | - If the element is not present in the set, then no error or exception is raised. 102 | 103 | Syntax: 104 | ```python 105 | setname.discard(element) 106 | ``` 107 | Example: 108 | ```python 109 | color={"red","green","blue"} 110 | #remove "black" 111 | color.remove("black") 112 | ``` 113 | Output: 114 | ``` 115 | #Result:KeyError:{"red","green","blue"} 116 | ``` 117 | 118 | #### 3.pop() 119 | - **pop()** removes any orbitary elemnt and return it. 120 | Example: 121 | ```python 122 | color={"red","green","blue"} 123 | color.pop() 124 | print(color) 125 | ``` 126 | Output: 127 | ``` 128 | {'red', 'green'} 129 | ``` 130 | 131 | ## 3.Change Items in set 132 | - Once a set is created, you cannot change its items. 133 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/String/1.BasicOfStrings.py: -------------------------------------------------------------------------------- 1 | #Strings 2 | #String is collection of Alphabets numbers and special charcter 3 | #following are the some defualt string function 4 | stringname=("kjdsfndnfd") 5 | 6 | #stringname[1] gives j string started counting first charter as 0 second as 1 third as 2 in this way 7 | print(stringname[1]) 8 | #j 9 | 10 | 11 | #stringname[-10] gives k that counts from last character and search like d at -1, f at -2,-3... 12 | print(stringname[-10]) 13 | #k 14 | 15 | 16 | #selecting sub sequences from string 17 | #Syantax variablename[starting position:endingposition + 1] 18 | # for example if you want to print sfn from above stringname then where s is at starting position is 3 and n endpostion is 5 add 1 in it then total is 6 19 | print(stringname[3:6]) 20 | #sfn 21 | 22 | 23 | #stringnam[10] gives error index out of range 24 | #print(stringname[10]) 25 | 26 | 27 | #you can use : for multiple use like 28 | # variablename[startingpostion:] in this example if we just add starting postion then then resultant substring contains output from statring postion to last charcter 29 | print(stringname[6:]) 30 | #dnfd 31 | 32 | 33 | 34 | #variablename[:ending postion ] this will give output in such manner from starting to that ending position 35 | print(stringname[:4]) 36 | #kjds 37 | 38 | #variablename[:] this will give who string as output 39 | print(stringname[:]) 40 | #kjdsfndnfd 41 | 42 | 43 | #IMP NOTE 44 | #if you provide out of range ending index it doesent give error it will print full string 45 | print(stringname[:50]) 46 | #kjdsfndnfd 47 | 48 | #if you provide out of range starting index it doesent give error it will print full string 49 | print(stringname[-100:]) 50 | #kjdsfndnfd 51 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/String/2.StringMethods.py: -------------------------------------------------------------------------------- 1 | #Following are the some string methods 2 | 3 | ##1.Split 4 | #if you want to devide a string with white space or commas or some special charcter then split method is used 5 | mystring="india pakistan china america" 6 | 7 | 8 | #split a string with whitespaces 9 | splitstring=mystring.split(' ') 10 | print(splitstring) 11 | ##['india', 'pakistan', 'china', 'america'] 12 | 13 | ##if you want to split that string and store it in different variable 14 | a,b,c,d=mystring.split(' ') 15 | print(a) 16 | print(b) 17 | print(c) 18 | print(d) 19 | 20 | ##india 21 | ##pakistan 22 | ##china 23 | ##america 24 | 25 | 26 | ##2.join 27 | mylist=['india', 'pakistan', 'china', 'america'] 28 | strings=','.join(mylist) 29 | print(strings) 30 | ##india,pakistan,china,america 31 | 32 | 33 | 34 | 35 | ##3.count 36 | lis=[3,5,54,3,3,3,4,5,56,66,3,3,3,23,4,6,6,77,34,345,67,6,78] 37 | #if you want to count how much times the 3 appears in list 38 | print(lis.count(3)) 39 | ##7 40 | 41 | 42 | 43 | 44 | ##4.Replace 45 | stat='kat is good girl' 46 | ##if you want to replace is with was then replace is used 47 | #replace('old word','new word') 48 | newstring=stat.replace('is','was') 49 | print(newstring) 50 | 51 | ##kat was good girl 52 | 53 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/String/3.FindOperatorInString.py: -------------------------------------------------------------------------------- 1 | #To findout postion of word or charcter from given string or paragraph use find operator 2 | 3 | mystring="i love to play cricket and football" 4 | print(mystring.find("o")) 5 | #3 6 | 7 | print(mystring.find("cric")) 8 | #15 9 | 10 | 11 | #if we want to print string from play to onwards then 12 | startingindex=(mystring.find("play")) 13 | print(mystring[startingindex:]) 14 | #play cricket and football 15 | 16 | 17 | 18 | #if we searching a not character or word in a paragraph which is not present in that paragraph or string then result of find operator will be -1 19 | print (mystring.find("hahaha")) 20 | #-1 21 | 22 | 23 | #if we want to findout second occurance of of required string 24 | first=(mystring.find("o")) 25 | second=(mystring.find("o",first+1)) 26 | print(second) 27 | 28 | 29 | #To find all occurences of word 30 | for i,j in enumerate(mystring): 31 | if j=='o': 32 | print(i) 33 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/String/4.StringFromatting.py: -------------------------------------------------------------------------------- 1 | #String Formatting is one good way to joins and combines two or more string with diffrent data 2 | #for string formatting {} is used to blank space to get data from .format() .format(variabless are used) 3 | 4 | a=10 5 | b=20 6 | c=39 7 | 8 | #1.String Formatting 9 | #for example if we want to write a value is 10 then normal way to write is 10 | print('a value is '+str(a)) 11 | 12 | 13 | #using String Formatting 14 | print('a value is {}'.format(a)) 15 | 16 | 17 | #if we want to print a value is 10 and b value is 20 and c value is 39 18 | #normal way 19 | print('a value is '+str(a)+' and b value is '+str(b)+' and c value is '+str(c)) 20 | 21 | #using string Formatting 22 | print('a value is {} and b value is {} and c value is {}'.format(a,b,c)) 23 | 24 | 25 | #You can also give position inside {} block like {1} then this will get value from .format(0position,1position,2postion) 26 | print('a value is {2} and b value is {1} and cvalue is {0}'.format(a,b,c)) 27 | #here {2} get value from format and get value whose position is 2 in formatting 28 | 29 | 30 | 31 | #2.Type Conversion 32 | 33 | #Type conversion int to float 34 | #foolowing example showing int to float 35 | print('a value is {0:f}'.format(a)) 36 | 37 | 38 | #for 2 digit 39 | print('a value is {0:.2f}'.format(a)) 40 | 41 | 42 | 43 | #type conversion double to flot 44 | #bydefault in python the dataatype is double for calculation 45 | print('2/3 answer is {}'.format(2/3)) 46 | 47 | #to convert into float 48 | print('2/3 answer is {0:f}'.format(2/3)) 49 | 50 | 51 | 52 | 53 | #3.#spacing using 'd' 54 | #this is used for giving spacing to integer 55 | print('answer is {0:3d}'.format(2)) 56 | #here the element is 1 digit and we give space for 3 digit means only 2 digit space show 57 | 58 | 59 | #for string we use left chevorn(<) and right chevorn(>) for giving space 60 | print('my name is {}'.format('abhi')) 61 | 62 | #to give space before name we use right chevorn 63 | print('my name is {0:>8}'.format('abhi')) 64 | 65 | 66 | #to give space after name we use right chevorn 67 | print('my name is {0:<8} ....'.format('abhi')) 68 | 69 | 70 | 71 | #4.text at center of Astric (*) 72 | print('{0:*^11s}'.format('rahul')) 73 | 74 | #this will create 11 * but rahul string is 5 chacter so 6 astric(*) will be printed 3 left side and 3 right side if 7 star there then 4 at right side and 3 at left side 75 | 76 | 77 | 78 | #5.String Formatting inside a loop 79 | for i in range(1,11): 80 | print('{0:5d}{1:5d}{2:5d}'.format(i,i**2,i**3)) -------------------------------------------------------------------------------- /Data_Structure_In_Python/Tuple/1.Basic_of_tuple.py: -------------------------------------------------------------------------------- 1 | ##------------------------------------------------------------------------------------------------------ 2 | #Created By:Ravishankar Chavare 3 | #version:python 3.7 4 | #Date:13/03/2019 5 | #File_des:Introduction of Tuple Data Structure 6 | ##------------------------------------------------------------------------------------------------------ 7 | 8 | ''' 9 | -A tuple is a collection which is ordered and unchangeable. 10 | -In Python tuples are written with round brackets. 11 | 12 | ''' 13 | 14 | #Create A blank Tuple 15 | blanktuple=() #you can also use blanktuple=tuple() 16 | print(type(blanktuple))#Print the type of above object 17 | 18 | #Create A tuple with 5 element 19 | elements=(1,2,3,4,5,6,7) 20 | print(elements) #printing the Element 21 | 22 | #Accessing Tuple 23 | 24 | #Accessing first element 25 | firstelement=elements[1] 26 | print(firstelement) 27 | 28 | 29 | #Changing the first element 30 | elements[1]=9 #TypeError: 'tuple' object does not support item assignment 31 | print(elements) 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/Tuple/2.OperationOnTuple.py: -------------------------------------------------------------------------------- 1 | ##--------------------------------------------------------------------------- 2 | #Created By:Ravishankar Chavare 3 | #version:python 3.7 4 | #Date:13/03/2019 5 | #File_des:Some Simple Operation on Tuple 6 | ##---------------------------------------------------------------------------- 7 | 8 | #----------------------------------------------------------------------------- 9 | # Adding Element into Tuple 10 | #----------------------------------------------------------------------------- 11 | 12 | #tuples are immutable, so you can not add new elements 13 | #using merge of tuples with the + operator you can add an element and it will create a new tuple 14 | 15 | tpx=(1,2,3,4,5,6,7) 16 | 17 | #add 9 18 | tpx=tpx+(9,) 19 | print(tpx) 20 | 21 | #Unlike Python lists, tuples does not have methods such as append(), remove(), extend(), insert() and pop() due to its immutable nature. 22 | 23 | 24 | 25 | #Assigning Multiple Values 26 | a = (1,2,3) 27 | (one,two,three) = a 28 | print(one) 29 | 30 | 31 | #------------------------------------------------ 32 | #For Removing Element From Tuple 33 | #----------------------------------------------- 34 | #because of immutable structure we can not directly remove element from tuple here we can use list 35 | converted_list=list(tpx) 36 | 37 | #now we can use pop(),remove(), method to remove element 38 | #Remove 1 from tuple 39 | converted_list.remove(1) 40 | 41 | #after removing element convert list to tuple 42 | 43 | final_tuple=tuple(converted_list) 44 | 45 | 46 | #print(tuple) 47 | print(final_tuple) 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/Tuple/BasicOfTuple.md: -------------------------------------------------------------------------------- 1 | ## Tuple 2 | 3 | ### Basic Of Tuple 4 | - A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. 5 | - A tuple is a collection that is ordered and unchangeable. In Python, tuples are written with round brackets. 6 | - Tuples are used for grouping data. Each element or value that is inside of a tuple is called an item. 7 | 8 | Syntax: 9 | ```python 10 | tuplename=(elem1,elem2,elem3...) 11 | ``` 12 | 13 | Example: 14 | ```python 15 | color=("red","blue","green") 16 | print(color) 17 | ``` 18 | 19 | Output: 20 | ``` 21 | ('red', 'blue', 'green') 22 | ``` 23 | 24 | - Create A blank Tuple 25 | ```python 26 | blanktuple=() 27 | #you can also use 28 | blanktuple=tuple() 29 | 30 | #Print the type of above object 31 | print(type(blanktuple)) 32 | ``` 33 | Output: 34 | ``` 35 | 36 | ``` 37 | 38 | To write a tuple containing a single value you have to include a comma, even though there is only one value 39 | 40 | Example: 41 | ```python 42 | tupl1=(4,) 43 | print(tupl1) 44 | ``` 45 | Output: 46 | ``` 47 | (4,) 48 | ``` 49 | 50 | - Create A tuple with 7 element 51 | ```python 52 | elements=(1,2,3,4,5,6,7) 53 | #printing the Element 54 | print(elements) 55 | ``` 56 | Output: 57 | ``` 58 | (1,2,3,4,5,6,7) 59 | ``` 60 | 61 | 62 | 63 | ### Access Tuple Items 64 | 65 | - As an ordered sequence of elements, each item in a tuple can be called individually, through indexing. 66 | - Each item corresponds to an index number, which is an integer value, starting with the index number 0. 67 | - You can access tuple items by referring to the index number, inside square brackets 68 | 69 | Syntax: 70 | ```python 71 | tuplenmae[index] 72 | ``` 73 | Example: 74 | ```python 75 | mytuple=(2,4,5,67) 76 | print("Tuple Element") 77 | print(mytuple) 78 | 79 | #get 5 element 80 | res=mytuple [2] 81 | print("Element at index 2") 82 | print(res) 83 | #Result:5 84 | ``` 85 | Output: 86 | ``` 87 | Tuple Element 88 | (2, 4, 5, 67) 89 | Element at index 2 90 | 5 91 | ``` 92 | 93 | ### Access Multiple elements from a tuple 94 | We can use indexing to call out a few items from the tuple. Slices allow us to call multiple values by creating a range of index numbers separated by a colon [x:y]. 95 | 96 | we can use slicing to accessing elements from the tuple. 97 | 98 | Synatx: 99 | ```python 100 | tuplename[startpostion:endposition] 101 | ``` 102 | 103 | Example: 104 | ```python 105 | mytuple=(1,3,4,5,6,7,8,9) 106 | res=mytuple[2:7] 107 | print(res) 108 | ``` 109 | Output: 110 | ``` 111 | (4,5,6,7,8,9) 112 | ``` 113 | 114 | 115 | ### Extended slicing 116 | - The syntax for this construction is **tuple[x:y:z]**, with z referring to stride. Let’s make a larger list, then slice it, 117 | 118 | Example: 119 | ```python 120 | numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) 121 | print(numbers[1:11:2]) 122 | ``` 123 | Output: 124 | ``` 125 | (1, 3, 5, 7, 9) 126 | ``` 127 | - We can omit the first two parameters and use stride alone as a parameter with the syntax **tuple[::z]** 128 | 129 | Example: 130 | ```python 131 | numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) 132 | print(numbers[::3]) 133 | ``` 134 | Output: 135 | ``` 136 | (0, 3, 6, 9, 12) 137 | ``` 138 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/Tuple/FunctionOnTuple.md: -------------------------------------------------------------------------------- 1 | ## Built-in Function For tuple 2 | There are the number of built-in functions are available to process tuple 3 | 4 | ### 1.length 5 | - **len()** function is used to return number of elements inside in tuple. 6 | 7 | Syntax: 8 | ```python 9 | len(tuplename) 10 | ``` 11 | Example: 12 | ```python 13 | mytuple=(1,2,3,5,4,8,4) 14 | 15 | #length of tuple 16 | res=len(mytuple) 17 | 18 | print("Length Of Tuple") 19 | print(res) 20 | ``` 21 | Output: 22 | ``` 23 | 7 24 | ``` 25 | 26 | ### 2.max() 27 | - The **max()** method returns the largest element in an iterable or largest of two or more parameters. 28 | Syntax: 29 | ```python 30 | max(iterable, *iterables[,key, default]) 31 | max(arg1, arg2, *args[, key]) 32 | ``` 33 | 34 | Example: 35 | ```python 36 | mytuple=(1,2,3,5,4,8,4) 37 | #Get Maximum High Element 38 | res=max(mytuple) 39 | print("Max Element") 40 | print(res) 41 | ``` 42 | Output: 43 | ``` 44 | Max Element 45 | 8 46 | ``` 47 | 48 | ### 3.min() 49 | - The **min()** method returns the smallest element in an iterable or largest of two or more parameters. 50 | Syntax: 51 | ```python 52 | min(iterable, *iterables[,key, default]) 53 | min(arg1, arg2, *args[, key]) 54 | ``` 55 | 56 | Example: 57 | ```python 58 | mytuple=(1,2,3,5,4,8,4) 59 | 60 | #Get Minimum Amount 61 | res=min(mytuple) 62 | print("Min Element") 63 | 64 | print(res) 65 | ``` 66 | Output: 67 | ``` 68 | 1 69 | ``` 70 | 71 | ### 4.any() 72 | - Return True if any element of the iterable is true 73 | - If the iterable is empty, return False. 74 | 75 | Examples: 76 | ```python 77 | # all values are true 78 | tupl1 = (5, 8, 9, 4) 79 | print(any(tupl1)) 80 | #Result:True 81 | 82 | # all values are false 83 | tupl2 = (0, False) 84 | print(any(tupl2)) 85 | #Result:False 86 | 87 | # one value is false, others are true 88 | tupl3 = (0, 8, 18, 5) 89 | print(any(tupl3)) 90 | #Result:True 91 | 92 | # one value is true, others are false 93 | tupl4 = (55, 0, False) 94 | print(any(tupl4)) 95 | #Result:True 96 | 97 | # empty iterable 98 | tupl5 = () 99 | print(any(tupl5)) 100 | #Result:False 101 | ``` 102 | Output: 103 | ``` 104 | True 105 | False 106 | True 107 | True 108 | False 109 | ``` 110 | 111 | ### 5.all() 112 | - Return True if all elements of the iterable are true (or if the iterable is empty) 113 | 114 | 115 | Examples: 116 | ``` 117 | # all values are true 118 | tupl1 = (5, 8, 9, 4) 119 | print(any(tupl1)) 120 | #Result:True 121 | 122 | # all values are false 123 | tupl2 = (0, False) 124 | print(any(tupl2)) 125 | #Result:False 126 | 127 | # one value is false, others are true 128 | tupl3 = (0, 8, 18, 5) 129 | print(any(tupl3)) 130 | #Result:False 131 | 132 | # one value is true, others are false 133 | tupl4 = (55, 0, False) 134 | print(any(tupl4)) 135 | #Result:False 136 | 137 | # empty iterable 138 | tupl5 = () 139 | print(any(tupl5)) 140 | #Result:True 141 | ``` 142 | Output: 143 | ``` 144 | True 145 | False 146 | True 147 | True 148 | False 149 | ``` 150 | -------------------------------------------------------------------------------- /Data_Structure_In_Python/Tuple/OperationOnTuple.md: -------------------------------------------------------------------------------- 1 | ## Operation on Tuple 2 | 3 | ### 1.Concatenating 2 tuples 4 | 5 | Example: 6 | ```python 7 | tupl1=(1, 3) 8 | tupl2=("red","green") 9 | 10 | tupl3=tupl1+tupl2 11 | print(tupl3) 12 | ``` 13 | Output: 14 | ``` 15 | (1, 3,"red", "green") 16 | ``` 17 | 18 | ### 2.Nested tuple 19 | 20 | Example: 21 | ```python 22 | tupl1=(1, 3) 23 | tupl2=["red","green"] 24 | 25 | tupl3=(tupl1,tupl2) 26 | print(tupl3) 27 | ``` 28 | Output: 29 | ``` 30 | ((1, 3),["red", "green"]) 31 | ``` 32 | 33 | ### 3. Change Tuple value 34 | 35 | - unlike a list, a tuple is immutable objects. This means that the element of a tuple can not be changed once it has been assigned. 36 | - but if a tuple contains any mutable object such as a list then this object can be changeable. 37 | 38 | For Example: 39 | ```python 40 | mytple=(1,2,3,4,5,["red", "green"]) 41 | # change 2 element with 9 42 | mytple[1]=9 43 | print(mytple) 44 | ```` 45 | Output: 46 | ``` 47 | Error tuple object does not support item assignments 48 | ``` 49 | 50 | But in the same example, you want to replace **"red"** With **"black"** 51 | 52 | Example: 53 | ```python 54 | mytple=(1,2,3,4,5,["red", "green"]) 55 | 56 | # change "red" element with "black" 57 | mytple[5][1]="black" 58 | 59 | print(mytple) 60 | ``` 61 | Output: 62 | ``` 63 | (1,2,3,4,5,["black", "green"]) 64 | ``` 65 | 66 | ### 4. Deleting Tuple 67 | - A tuple is an immutable object so we can delete the individual item from the tuple. 68 | - The entire tuple will be deleted or removed using a del keyword. 69 | 70 | Syntax: 71 | ```python 72 | del tuplename 73 | ``` 74 | Example: 75 | ```python 76 | mytple=(1,2,3,4,5,["red", "green"]) 77 | # delete tuple 78 | 79 | del mytple 80 | print(mytple) 81 | ``` 82 | Output 83 | ``` 84 | NameError: name 'mytple' is not defined 85 | ``` 86 | 87 | 88 | ### 5. Counting Frequency of Element 89 | Get the frequency of particular element appears in the tuple. 90 | 91 | Synatx: 92 | ```python 93 | tuplename.count(element) 94 | ``` 95 | Example: 96 | ```python 97 | tpl=(3,4,68,3,5,3) 98 | res=tpl.count(3) 99 | print(res) 100 | ``` 101 | Output: 102 | ``` 103 | 3 104 | ``` 105 | 106 | ### 6. Find Position index of element. 107 | 108 | Get the first index of the specified value. 109 | 110 | Syntax: 111 | ```python 112 | tuplename.index(value) 113 | ``` 114 | Example: 115 | ```python 116 | tpl=(3,4,68,3,5,3,4) 117 | res=tpl.index(4) 118 | print(res) 119 | ``` 120 | Output: 121 | ``` 122 | 1 123 | ``` 124 | 125 | ### 7.Check element is present in tuple or not 126 | 127 | - **'in'** keyword is used to check whether the element is present in tuple or not 128 | - if the element is present this will return boolean value True otherwise False 129 | 130 | Syntax: 131 | ```python 132 | Element in tuplename 133 | ``` 134 | Example: 135 | ```python 136 | tpl=(3,4,68) 137 | # check 4 is present or not 138 | if 4 in tpl: 139 | print("present") 140 | else: 141 | print("Not present") 142 | ``` 143 | Output: 144 | ``` 145 | present 146 | ``` 147 | -------------------------------------------------------------------------------- /ErrorHandling/1.BasicOFErrorHandling.py: -------------------------------------------------------------------------------- 1 | ''' 2 | -ErrorHandling in python is similar to other programming languages 3 | -Why we Need Error Handler in our programs#Asume that you have written a program contains methods functions and some logic you are 4 | taking some input from user if that user enter some unethical data then your program create error and 5 | all other code from error will not run 6 | So recover from this problem we are using error handling mechanism to give user warning or 7 | info whats wrong in input and executes other remainng code 8 | ''' 9 | 10 | #Error Handling uses following 4 Keywords 11 | 12 | #1.try:try to identify error 13 | #2.except:if try capture any error then except block will run(here except work like catch block in other programing langueg) 14 | #3.else:if try doesnt capture any error then else block will run 15 | #4.finally:this block will run in both situation when the errors occurs or error not occures 16 | 17 | #Simple Example 18 | 19 | x=input('Enter first number:') 20 | y=input('Enter second number:') 21 | try: 22 | if(int(x)>int(y)): 23 | print('first number is greator') 24 | elif(x==y): 25 | print('both number are same') 26 | else: 27 | print('Second number is greator') 28 | except: 29 | print('Enter numeric number') 30 | else: 31 | print('Two number compared successfully') 32 | finally: 33 | print('Program Excuted successfully') 34 | -------------------------------------------------------------------------------- /ErrorHandling/2.ErrorHandlingusingInfinteloop.py: -------------------------------------------------------------------------------- 1 | #we alredy know how to handle error 2 | #in this example we using while loop to take correct input from user 3 | #the while loop runs untill user enter both correct number 4 | 5 | x=input('Enter First Number: ') 6 | y=input('Enter Second Number: ') 7 | 8 | while True: 9 | try: 10 | if int(x)>int(y): 11 | print(str(x)+' is greator number') 12 | else: 13 | print(str(y)+' is greator number') 14 | except: 15 | print('You did not entered numeric value') 16 | print('try again ') 17 | x=input('Enter First Number: ') 18 | y=input('Enter Second Number: ') 19 | continue 20 | else: 21 | print('two number compared successfully') 22 | break 23 | -------------------------------------------------------------------------------- /FileHandeling/FileMethods.md: -------------------------------------------------------------------------------- 1 | ## File Methods 2 | 3 | ### File Methods 4 | 5 | ### 1.flush() 6 | 7 | - **flush()** method is used for flushes the internal buffer. 8 | - While writing the file operating system store the content of the file in the buffer 9 | and buffer content should be written into a file using  10 | - flush() method  11 | - when the buffer is full 12 | - python automatically flushes the files when closing them. 13 | but when we want to flush the data before closing them then the python built-in function .*flush()* is used 14 | 15 | Syntax: 16 | ```python 17 | fileobj.flush() 18 | ``` 19 | Example: 20 | ```python 21 | #initialize file 22 | fileobj=open("mydata.txt","w") 23 | 24 | #Write content to file 25 | fileobj.write("New Content Added") 26 | 27 | #flush the Content buffer to file 28 | fileobj.flush() 29 | ``` 30 | 31 | ### 2.fileno() 32 | - fileno returns the integer file descriptor that is used by the implementation to request i/o operation 33 | - the file descriptor is simply indexed into a file descriptor table 34 | - for each process in the operating system, there is one block PCB(process control block)  35 | - one of the parts of PCB keep track context of the process which is array structure called file descriptor 36 | 37 | Syntax: 38 | ```python 39 | fileobj.fileno() 40 | ``` 41 | 42 | Example: 43 | ```python 44 | #initialize file 45 | fileobj=open("mydata.txt","w") 46 | 47 | #get file descriptor index value 48 | index_val=fileobj.fileno() 49 | print(index_val) 50 | ``` 51 | Output: 52 | ``` 53 | 3 54 | ``` 55 | 56 | ### 3.isatty() 57 | - **isatty()** return True if a file is connected with terminal device(tty) 58 | 59 | Syntax: 60 | ```python 61 | fileobj.isatty() 62 | ``` 63 | 64 | Example: 65 | ```python 66 | #initialize file 67 | fileobj=open("mydata.txt","w") 68 | 69 | #Check whether file is connected with tty or not 70 | val=fileobj.isatty() 71 | print(val) 72 | ``` 73 | Output: 74 | ``` 75 | False 76 | ``` 77 | 78 | 79 | ### 4.seek() 80 | - set the file cursor current position 81 | 82 | Syntax: 83 | ```python 84 | fileobj.seek(position) 85 | ``` 86 | File **myfile.txt** contains 87 | ``` 88 | Hi, I am writing simple python programm. 89 | ``` 90 | 91 | Example: 92 | ```python 93 | #initilize the file 94 | file=open("myfile.txt","r") 95 | 96 | #this will set file reading cursor to 6 th position 97 | position=file.seek(6) 98 | 99 | #read content 100 | content=file.read() 101 | print(content) 102 | ``` 103 | Output: 104 | ``` 105 | am writing simple python programm. 106 | ``` 107 | 108 | You use 0 as a position to set file reading cursor to the first position at the starting of file 109 | 110 | ### 5.tell() 111 | - this method tell the current exact file cursor position in integer 112 | 113 | Syntax: 114 | ```python 115 | Fileobj.tell() 116 | ``` 117 | 118 | File **myfile.txt** contains 119 | ``` 120 | Hi, I am writing simple python programm. 121 | ``` 122 | 123 | Example: 124 | ```python 125 | #initilize the file 126 | file=open("myfile.txt","r") 127 | 128 | #read first 5 characters 129 | data=file.read(5) 130 | 131 | #now get the current position of file cursor 132 | pos=file.tell() 133 | ``` 134 | Output: 135 | ``` 136 | 5 137 | ``` 138 | 139 | 140 | 141 | ## Reading File methods 142 | **1.read()** 143 | - read the bytes from the file. 144 | 145 | **2.readline()** 146 | - read the single line from file 147 | 148 | **3.readlines()** 149 | - read all lines in file and return list object. 150 | 151 | 152 | ## Writing File methods 153 | **1.write()** 154 | - used to write content to the file 155 | 156 | **2.writelines()** 157 | - used to write multiple lines to the file list structure is used. 158 | -------------------------------------------------------------------------------- /FileHandeling/WriteContetToFile.md: -------------------------------------------------------------------------------- 1 | ## Writing File 2 | 3 | 4 | ### Write Contents 5 | 6 | For writing content to a file, there are two scenarios 7 | 8 | #### 1.write on existing file. 9 | for writing content to a file use following two modes in **open()** function 10 | 11 | **Modes for writing file** 12 | 13 | #### 1. a 14 | This will append the content at the end of the file. 15 | 16 | #### 2. w  17 | This will overwrite any existing content to a file. 18 | 19 | **write()** function is used to writing the content to a file 20 | 21 | Syntax: 22 | ```python 23 | fileobj=open(filename,"a/w") 24 | fileobj.write("this is new line ") 25 | ``` 26 | 27 | 28 | File **data.txt** contains 29 | ``` 30 | Hi, 31 | I am from file 32 | ``` 33 | Example: 34 | ```python 35 | #initialize file 36 | fileobj=open("data.txt","w") 37 | 38 | #add new text "I am new text" 39 | fileobj.write("I am new text") 40 | ``` 41 | 42 | this will overwrite already content and add new content 43 | Now **data.txt** contains 44 | ``` 45 | I am new text 46 | ``` 47 | 48 | Example of appending content 49 | File **data.txt** contains 50 | ``` 51 | Hi, 52 | I am from file 53 | ``` 54 | 55 | Example: 56 | ```python 57 | #initialize file 58 | fileobj=open("data.txt","a") 59 | 60 | #add new text "I am new text" 61 | fileobj.write("I am new text") 62 | ``` 63 | 64 | this will append content 65 | Now **data.txt** contains 66 | ``` 67 | Hi, 68 | I am from fileI am new text 69 | ``` 70 | 71 | ### 2.write on new file after file creating. 72 | 73 | To create a new file in Python, use the **open()** method, with one of the following parameters: 74 | 75 | **1.x** 76 | - Exclusive create. 77 | - will create a file, returns an error if the file exists. 78 | 79 | **1.a** 80 | - Append mode. 81 | - will create a file if the specified file does not exist. 82 | 83 | **1.w** 84 | - Write mode. 85 | - will create a file if the specified file does not exist. 86 | 87 | You can use the above modes to create an empty file using **open()** methods 88 | 89 | Example: 90 | Consider there is no file named **mydata.txt** inside current directory. 91 | ```python 92 | fil=open("mydata.txt","x") 93 | ``` 94 | 95 | Here new empty file is created 96 | 97 | 98 | 99 | ### How to write multiline to file 100 | 101 | - The method **writelines()** writes a sequence of strings to the file. 102 | - The sequence can be any iterable object producing strings, typically a list of strings. 103 | 104 | Syntax: 105 | ```python 106 | fileobj.writelines(iterable object) 107 | ``` 108 | 109 | Example: 110 | 111 | File **mydata.txt** contains 112 | ``` 113 | Hi 114 | ``` 115 | Example: 116 | ```python 117 | #initialize file for writing purpose 118 | fil=open("mydata.txt","w") 119 | 120 | #lines to write to file 121 | lines=['hello','hi'] 122 | 123 | #write lines 124 | fil.writelines(lines) 125 | ``` 126 | 127 | If you check the content of file **mydata.txt** 128 | ``` 129 | hello 130 | hi 131 | ``` 132 | ### Write content to file with "with" statement 133 | 134 | Example: 135 | ```python 136 | #content lines to add 137 | lines=['hello','hi'] 138 | 139 | #with statement for open 140 | with open("mydata.txt","w") as fil: 141 | fil.writelines(lines) 142 | 143 | ``` 144 | -------------------------------------------------------------------------------- /Function/1.BasicOfFunction.py: -------------------------------------------------------------------------------- 1 | #function procedure when we need to do some task then the best way to reuse our code 2 | # so function can help 3 | #Function or procedure syntax def functionname(variabl1,variable2..): 4 | # return calculation 5 | #to define a function def keyword is used 6 | 7 | #addition function 8 | def addition(a,b): 9 | return a+b 10 | 11 | def substraction(a,b): 12 | return a-b 13 | 14 | def multiply(a,b): 15 | return a*b 16 | 17 | print("Addtion is ") 18 | print(addition(19,8)) #calling a function 19 | 20 | print("Substraction is ") 21 | print(substraction(19,8)) #calling substraction function 22 | 23 | print("Multiplication is ") 24 | print(multiply(19,8)) #calling multiplication function 25 | 26 | x=input("Enter First Number:") 27 | y=input("Enter Second Number:") 28 | z=(addition(int(x),int(y))) #sending user input function 29 | print("Your Answer") 30 | print(z) -------------------------------------------------------------------------------- /Function/2.ExampleOfFunction.py: -------------------------------------------------------------------------------- 1 | #create a function who will take input as a string and search string and respond substring from string from searched string postion 2 | def positionfinder(search,target): 3 | first=(search.find(target)) 4 | second=(search.find(target,first+1)) 5 | return second 6 | 7 | 8 | mystring=("I like computer engineering and i am learning now") 9 | y=(positionfinder)(mystring,"i") 10 | print(mystring[y:]) 11 | -------------------------------------------------------------------------------- /Function/3.LambdaFunction.py: -------------------------------------------------------------------------------- 1 | ##------------------------------------------------------------------------------------------------------ 2 | #Created By:Ravishankar Chavare 3 | #version:python 3.7 4 | #Date:17/03/2019 5 | #File_des:Introduction of Lambda Function 6 | ##------------------------------------------------------------------------------------------------------ 7 | 8 | ''' 9 | lambda function is a small anonymous function. 10 | A lambda function can take any number of arguments, 11 | but can only have one expression. 12 | 13 | Why Use Lambda Functions? 14 | anonymous function is a function that is defined without a name. 15 | While normal functions are defined using the def keyword, 16 | 17 | Syntax: 18 | lambda arguments : expression 19 | 20 | 21 | Example: 22 | x = lambda a : a + 10 23 | print(x(5)) 24 | 25 | ''' 26 | #create a lambda function which accept single elemnt and Return its Square 27 | square=lambda num1:num1**2 28 | print(square(2)) 29 | 30 | 31 | #Create a lambda function to accept two numbers and return addion of both Number 32 | add=lambda a,b:a+b 33 | print(add(5,4)) 34 | 35 | #Use Of lambda with list and Map 36 | #multiply with each element from list with 2 37 | #map syntax map(function,iterableobject) 38 | li = [5, 3, 2, 7, 4, 632, 737] 39 | result_list = list(map(lambda x: x*2 , li)) 40 | print(result_list) 41 | 42 | 43 | #lambda function inside in a function 44 | def Func1(n): 45 | return lambda a:a*n 46 | 47 | l=Func1(4) 48 | print(l(2)) 49 | #in above program n is 4 and a is 2 wchich passed to lambda Function 50 | 51 | -------------------------------------------------------------------------------- /Function/BasicOfFunction.md: -------------------------------------------------------------------------------- 1 | ## Function 2 | 3 | ### Function in Python 4 | - A function is a block of organized, reusable code that is used to perform a single, related action 5 | - A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. 6 | - The function is a set of programmatic statements that take some input, do some specific calculation and computation 7 | and produce expected output and return it. 8 | - Create a function and add some commonly repeated code inside it. that instead of writing the same code again and again for different inputs, we can call the function 9 | 10 | ### How To Define a function 11 | 12 | - Function blocks begin with the keyword **def** followed by the function name and parentheses **()** 13 | - if Any input parameter placed with parentheses. 14 | - The code block within every function starts with a colon **(:)** and is indented. 15 | - for returning value from the function you can use the return keyword 16 | ```python 17 | return "element to return" 18 | ``` 19 | - for calling the defined function we can use function-name with parentheses 20 | 21 | Syntax: 22 | ```python 23 | def functionname(parameters): 24 | #Add main computation code here 25 | ``` 26 | Example: 27 | ```python 28 | def sum(a,b): 29 | return a+b 30 | ``` 31 | 32 | ### How to Call a function 33 | - Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt 34 | - Call a function after the only declaration of function.if you called a function before its declaration python interpreter gives an error(name 'function' is not defined) 35 | Example: 36 | ```python 37 | a=5 38 | b=7 39 | print(sums(a,b)) 40 | def sums(a,b): 41 | return a+b 42 | ``` 43 | Output: 44 | ``` 45 | NameError: name 'sums' is not defined 46 | ``` 47 | 48 | The correct way to Write a function 49 | 50 | Example: 51 | ```python 52 | a=5 53 | b=7 54 | def sums(a,b): 55 | return a+b 56 | print(sums(a,b)) 57 | ``` 58 | Output: 59 | ``` 60 | 12 61 | ``` 62 | -------------------------------------------------------------------------------- /Function/Lambdafunction.md: -------------------------------------------------------------------------------- 1 | ## Lambda Function 2 | 3 | ### Lambda Function 4 | - A Python lambda is just a Python function. It is a simple special type of function that has limited capabilities 5 | - Lambda function is a small anonymous function. 6 | - lambda function can have any number of arguments but only one expression, which is evaluated and returned. 7 | - Normally we use the **def** keyword to define a function with a name. The *lambda* keyword is used to create anonymous functions. 8 | - Lambda functions can accept zero or more arguments but only one expression. 9 | 10 | ### Why Use Lambda Functions? 11 | 12 | The anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword. we don't need to write a return keyword for returning the value from the lambda function. 13 | 14 | 15 | Syntax: 16 | ```python 17 | lambda arguments: expression 18 | ``` 19 | 20 | Example: 21 | ```python 22 | x = lambda a : a + 10 23 | print(x(5)) 24 | ``` 25 | Output: 26 | ``` 27 | 15 28 | ``` 29 | 30 | ### Lambda function with multiple arguments 31 | 32 | if you want to define a lambda function that accepts more than one argument, you can separate the input arguments by commas. 33 | 34 | Syntax: 35 | ```python 36 | lambda var1,var2,var3: computation of input variable 37 | ``` 38 | Example: 39 | Create a lambda function for addition of two input integer number 40 | ```python 41 | add=lambda a,b:a+b 42 | 43 | #pass 2 and 4 number 44 | res=add(2,4) 45 | print(res) 46 | ``` 47 | 48 | Output: 49 | ``` 50 | 6 51 | ``` 52 | 53 | ### Is this possible to write multiline lambda Function 54 | No, because lambda function is only a single line one time use function so you can not create a multiline lambda function. 55 | Lambda function can be used with python built-in function such as filter(), map, list, etc.... 56 | 57 | 58 | -------------------------------------------------------------------------------- /IDLETricks/1.shortcuts.txt: -------------------------------------------------------------------------------- 1 | 1.Tab Completion 2 | Start to type in some code, and then press the 'TAB' key. 3 | IDLE will offer suggestions to help you complete your statement. 4 | 5 | 2.Recall Code Statement 6 | Press Alt-P to recall the previous code statement entered into 7 | IDLE or press Alt-N to move to the next code statement 8 | 9 | 3.Edit Recalled Code 10 | Once you recall your code statement, you can edit it and 11 | move around the statement using the arrow keys. It’s 12 | possible to edit any statement that you’ve previously 13 | entered, even code statements that span multiple lines. 14 | 15 | 4.Adjust Idle Prefrence 16 | just Click on Options and click on configure idle 17 | there 18 | 1.Font/tab:here select one appropriate font according to your need you also select the size of text 19 | 2.highlight:select hilighting theme 20 | 3.keys:here you can add your own shortcuts keys 21 | 4.General:You can change the window size -------------------------------------------------------------------------------- /Logging/1.BasicOfLogging.py: -------------------------------------------------------------------------------- 1 | ##------------------------------------------------------------------------------------------------------ 2 | #Created By:Ravishankar Chavare 3 | #version:python 3.7 4 | #Date:13/03/2019 5 | #File_des:Introduction of Logging 6 | #Offical Documentation:https://docs.python.org/2/library/logging.html 7 | ##------------------------------------------------------------------------------------------------------ 8 | 9 | 10 | 11 | ''' 12 | Logging is a very useful tool in a programmer’s toolbox. 13 | It can help you develop a better understanding of the flow of a program 14 | and discover scenarios that you might not even have thought of while developing. 15 | 16 | Python provides a logging system as a part of its standard library, so you can quickly add logging to your application 17 | 18 | Import logging module in python as follow 19 | import logging as log 20 | ''' 21 | #importing logging module 22 | import logging as log 23 | 24 | ''' 25 | Following Are some By Defualt Logging Levels with thier numeric values 26 | CRITICAL 50 27 | ERROR 40 28 | WARNING 30 29 | INFO 20 30 | DEBUG 10 31 | NOTSET 0 32 | ''' 33 | 34 | #Simple Log Message print on shell 35 | 36 | log.debug("This is debug messgae") 37 | log.info("This is info message ") 38 | log.warning("THis is warning Message") 39 | log.error("This is Error Message") 40 | log.critical("This is Critical Message") 41 | 42 | ''' 43 | When you will run above code then only warning ,error,critical log will run 44 | because python bydefualt logging level set to 30 45 | you can check python logging level using log.root.level 46 | ''' 47 | loglevel=log.root.level 48 | print(loglevel) 49 | 50 | 51 | #logging module shows log from given log to upwards means if we set loglevel =20 52 | #then ppython show info,warning,error,critical logging 53 | 54 | #how to change Logging 55 | 56 | log.root.level=20 #you must ned to set this when loging imported to apply to all file 57 | print(log.root.level) #here you will get 20 as logger value if you give log now then from 20 to onwards log will show 58 | #After Setting logger value to 20 59 | log.debug("This is debug messgae") 60 | log.info("This is info message ") 61 | log.warning("THis is warning Message") 62 | log.error("This is Error Message") 63 | log.critical("This is Critical Message") -------------------------------------------------------------------------------- /Logging/2.WriteLogToFile.py: -------------------------------------------------------------------------------- 1 | ##------------------------------------------------------------------------------------------------------ 2 | #Created By:Ravishankar Chavare 3 | #version:python 3.7 4 | #Date:13/03/2019 5 | #File_des:Introduction of Logging 6 | #Offical Documentation:https://docs.python.org/2/library/logging.html 7 | ##------------------------------------------------------------------------------------------------------ 8 | 9 | import logging as log 10 | 11 | #To configure logging use log.basicconfig(parametere) for initilization 12 | ''' 13 | some of the commonly used paramter for basicconfig 14 | 1.level: The root logger will be set to the specified severity level. 15 | 2.filename: This specifies the file. 16 | 3.filemode: If filename is given, the file is opened in this mode. The default is a, which means append. 17 | 4.format: This is the format of the log message. 18 | ''' 19 | #Configure loggging 20 | loger=log.getLogger(__name__) 21 | log.basicConfig(filename='simplelog.log',level=log.INFO,format='[%(asctime)s-%(levelname)s]-%(message)s') 22 | 23 | loger.info("Simple logMessage") 24 | loger.debug("This is debug Message") 25 | loger.error("this is Error Log") 26 | 27 | #Foloowing are the some log records attributes format 28 | ''' 29 | %(asctime)s :-Asctime 30 | %(created)f :-created 31 | %(filename)s :-filename where log generated 32 | %(funcName)s :Function name 33 | %(levelname)s :-level name 34 | %(message)s :-logger passing messgae 35 | %(pathname)s :-Full pathname of the source file where the logging call was issued (if available). 36 | %(process)d :-if process id is Avialable 37 | ''' 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /Logging/simplelog.log: -------------------------------------------------------------------------------- 1 | [2019-03-13 20:10:23,174-INFO]-Simple logMessage 2 | [2019-03-13 20:10:23,174-ERROR]-this is Error Log 3 | [2019-03-13 20:15:08,619-INFO]-Simple logMessage 4 | [2019-03-13 20:15:08,619-ERROR]-this is Error Log 5 | -------------------------------------------------------------------------------- /Loops/1.ForLoop.py: -------------------------------------------------------------------------------- 1 | # for loop is used for looping purpose 2 | 3 | # for loop contains three parameter 4 | # 1.starting number 5 | # 2.Stop number+1 6 | # 3.difference or step number(is optional if not given then it will increament by 1) 7 | 8 | #to write out for logic 9 | #for variable in (list,varaible,tuple,dictionaries,string or any iterable object here): 10 | # //remaing code for for 11 | 12 | #For Example print 1 to 10 numbers 13 | 14 | for i in range(1,11): 15 | print(i) 16 | 17 | 18 | #in above example 1 is starting number and 11 is ending number means print number between 1 and 11 is 1,2,3,4,5,6,7,8,9,10 19 | 20 | 21 | #result of code 22 | # 1 23 | # 2 24 | # 3 25 | # 4 26 | # 5 27 | # 6 28 | # 7 29 | # 8 30 | # 9 31 | # 10 -------------------------------------------------------------------------------- /Loops/2.AdavancedForLoop.py: -------------------------------------------------------------------------------- 1 | # For Simple example this will print series of 5 starting from 5 and end at 50 with difference 5 and addition of output numbers 2 | # for x in range(5,50,5): 3 | # print(x) 4 | 5 | def series(start, stop, step): 6 | result = 0 7 | for x in range(start, stop + 1, step): 8 | print(x) 9 | result = result + x 10 | print("The Addition of " + str(start) + " series is " + str(result)) 11 | 12 | 13 | start = int(input("Enter Starting number:")) 14 | step = int(input("Enter difference:")) 15 | terms = int(input("Enter number of terms:")) 16 | 17 | # to find out last number using terms number 18 | stop = start + (terms - 1) * step 19 | 20 | series(start, stop, step) 21 | -------------------------------------------------------------------------------- /Loops/3.ForLoopOnList.py: -------------------------------------------------------------------------------- 1 | city=['Aurangabad','Pune','Beed','Latur','Mumbai','Bathinda','Kolkata','Delhi'] 2 | print('*********NOrmal List*********') 3 | for cities in city: 4 | print(cities) 5 | 6 | #For All uppercase Charatcter 7 | print('*********Capital List*********') 8 | 9 | for cities in city: 10 | print(cities.upper()) 11 | 12 | 13 | #For Concatination with list 14 | print('*********Concanited List*********') 15 | 16 | for cities in city: 17 | print(cities + " is good") 18 | 19 | 20 | #Print Those Cities from list Whose first charcter is B 21 | print('*********Cities Starting With letter b for converting to Lower*********') 22 | 23 | for cities in city: 24 | if(cities[0].lower()=="b"): 25 | print(cities) 26 | -------------------------------------------------------------------------------- /Loops/4.WhileLoop.py: -------------------------------------------------------------------------------- 1 | #simlar to for loop while loop is used for iterbale object 2 | #while loop run block of code untill condtion is true when condition is false it will terminate execution of code block 3 | 4 | #Syntax 5 | # while condition: 6 | # code of while block 7 | 8 | 9 | # simple example to print 1 to 10 numbers using while loop 10 | num=0 11 | while num<11: 12 | print(num) 13 | num=num+1 14 | 15 | 16 | #while block run until num is less than 11 means 0 to 10 numbers printed -------------------------------------------------------------------------------- /Loops/5.InfinteWhileLoop.py: -------------------------------------------------------------------------------- 1 | # to create a infinte loop in condion give such condtion which is always true then that block of code infintely runs 2 | 3 | #Example 1 4 | i=1 5 | while(i!=10): 6 | i=i+2 7 | print(i) 8 | 9 | #here we provide condition i!=10 which is always give output as true then this will run infinte times 10 | 11 | #Example 2 12 | 13 | # while True: 14 | # print('HI') 15 | 16 | #in this example write True in condition 17 | -------------------------------------------------------------------------------- /MachineLearning/BasicIntroduction.md: -------------------------------------------------------------------------------- 1 | ## Basic Introduction 2 | 3 | Some Important Phases or fields 4 | ``` 5 | 1. AI :- Artificial Intelligence 6 | 2. ML :- Machine Learning 7 | 3. DL :- Deep Learning 8 | 4. DS :- Data Science 9 | ``` 10 | 11 | Short Description of above different areas 12 | ![Areas](https://github.com/chavarera/PythonScript/blob/master/MachineLearning/img/field.png) 13 | 14 | ### 1. AI(Artificial Intelligence) 15 | - Artificial intelligence is a branch of computer science that aims to create intelligent machines that enable machines to think like a normal human 16 | - Sometimes it also called machine intelligence. 17 | 18 | #### Application of AI 19 | ``` 20 | - Image Recognition 21 | - Chatbots 22 | - Natural Language Generation 23 | - Speech Recognition 24 | - Sentimental Analysis 25 | - Self Driving Cars 26 | - Robotics 27 | - Computer Vision 28 | ``` 29 | ### 2. ML(Machine Learning) 30 | 31 | - Machine Learning is the simple application of artificial intelligence that provides machines the ability to automatically learn and improve from experience without being 32 | explicitly programmed. 33 | - Machine learning is closely related to computational statistics, which focuses on making predictions using computers. 34 | - Machine Learning enables machines or computer to make data-driven decisions rather than explicitly programming. 35 | 36 | #### Types Of Machine Learning 37 | 38 | 1. Supervised Learning 39 | 2. Unsupervised Learning 40 | 41 | #### Application of ML 42 | ``` 43 | - Social Media 44 | - Fraud Detection 45 | - Google Translate 46 | - Medical Diagnosis 47 | - Classifiers 48 | - Stats Tool to learn from data 49 | ``` 50 | 51 | ### 3. DL(Deep Learning) 52 | - Deep Learning is the part of *Machine Learning* in *Artificial Intelligence*. 53 | - Deep Learning also called as *Deep Neural Learning* or *Deep Neural Network* 54 | - Deep Learning networks rely on layers of the ANN (artificial neural networks). 55 | 56 | ### Application Of DL 57 | ``` 58 | - Automatic speech recognition. 59 | - Visual art processing. 60 | - Customer relationship management. 61 | - Recommendation systems. 62 | ``` 63 | 64 | ### 4. DS(Data Science) 65 | - Data Science is about Extraction, Preparation, Analysis, Visualization, and Maintenance of information 66 | - Data Science is a completely different area than (AI, ML) But it Intersects all these areas. 67 | - Understanding and Extraction of useful data is one function of Data science. 68 | 69 | Applications OF DS 70 | ``` 71 | - Internet Search. 72 | - Targeted Advertising. 73 | - Visualization. 74 | - Banking(Big Data and Data Science have enabled banks to keep up with the competition) 75 | ``` 76 | 77 | 78 | Python support following some important Libraries that are helpfull in (AI, ML, DL, DS) 79 | 80 | ``` 81 | Numpy 82 | Pandas 83 | Matplotlib 84 | Scipy 85 | Scikit-learn 86 | Theano 87 | TensorFlow 88 | Keras 89 | PyTorch 90 | And Other Many More... 91 | ``` 92 | -------------------------------------------------------------------------------- /MachineLearning/JupyterNotebook/img/RunCell.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/MachineLearning/JupyterNotebook/img/RunCell.gif -------------------------------------------------------------------------------- /MachineLearning/JupyterNotebook/img/basics.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/MachineLearning/JupyterNotebook/img/basics.png -------------------------------------------------------------------------------- /MachineLearning/JupyterNotebook/img/img: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /MachineLearning/JupyterNotebook/img/new.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/MachineLearning/JupyterNotebook/img/new.png -------------------------------------------------------------------------------- /MachineLearning/JupyterNotebook/img/newfile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/MachineLearning/JupyterNotebook/img/newfile.png -------------------------------------------------------------------------------- /MachineLearning/JupyterNotebook/img/open.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/MachineLearning/JupyterNotebook/img/open.png -------------------------------------------------------------------------------- /MachineLearning/JupyterNotebook/img/opened.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/MachineLearning/JupyterNotebook/img/opened.png -------------------------------------------------------------------------------- /MachineLearning/JupyterNotebook/img/path.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/MachineLearning/JupyterNotebook/img/path.png -------------------------------------------------------------------------------- /MachineLearning/JupyterNotebook/img/pip.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/MachineLearning/JupyterNotebook/img/pip.png -------------------------------------------------------------------------------- /MachineLearning/JupyterNotebook/img/run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/MachineLearning/JupyterNotebook/img/run.png -------------------------------------------------------------------------------- /MachineLearning/Numpy/1.BasicOfNumpy.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Created By:Raishankar Chavare 3 | Version:python 3.7 4 | To Install numpy 5 | 6 | open command prompt and type:pip install numpy 7 | 8 | To import numpy use:import numpy as np 9 | ''' 10 | 11 | import numpy as np 12 | ''' Simple 1 d array using numpy''' 13 | 14 | #to create simply numpy array from a normal array use 15 | simple_array=[1,4,2,3,5,4,5,4,5,4,8,4,58,4,8,18] 16 | 17 | #simple 1d Array 18 | numpy_array=np.array(simple_array) 19 | 20 | #To Print Simple Numpy Array 21 | print('Simple Numpy Array:' , numpy_array) 22 | 23 | 24 | #dtype, the data type of the array 25 | print(numpy_array.dtype) 26 | 27 | #itemsize f the array 28 | print(numpy_array.itemsize) 29 | 30 | #To get the Shape of numpy array 31 | print('1d Array Shape:' , numpy_array.shape) #The first paramter is the row and second one is empty because of 1d array 32 | 33 | #To findout the max and min number from numpy arry use 34 | print('Maximum Number :', numpy_array.max())#For Max 35 | print('Minimum Number', numpy_array.min())#For Min 36 | 37 | #To findout The Index of max number in array user argmax and for min number use argmin 38 | print('') 39 | 40 | 41 | 42 | #To reshaping the 1d array to multidimensssional array use reshape method 43 | mult_array=numpy_array.reshape(4,4) 44 | 45 | #Note Before reshaping the array check the element count neither low nor high 46 | 47 | #print the ndimenssional aaray 48 | print('Multidimenssional Array:\n',mult_array) 49 | 50 | 51 | #this will print out the data into the tabular format 52 | ##[[ 1 4 2 3] 53 | ## [ 5 4 5 4] 54 | ## [ 5 4 8 4] 55 | ## [58 4 8 10]] 56 | 57 | 58 | #shape of multidimenssional array (row,column) 59 | print('Shape of Multidimenssional Array:',mult_array.shape) 60 | 61 | 62 | ''' numpy array operation ''' 63 | 64 | #Create a 1s array 65 | array_1s=np.ones(5) 66 | print('1s array',array_1s) 67 | 68 | arrays_2s=np.ones((2,2)) 69 | print(arrays_2s) 70 | 71 | 72 | #create numpy Array using arange function 73 | array_using_range=np.arange(10) 74 | print(array_using_range) 75 | 76 | 77 | #arange with interval np.arange(start,end,interval) 78 | arange_int=np.arange(0,20,2) 79 | print('nparange with interval: ',arange_int) 80 | 81 | 82 | 83 | 84 | #linspace create 10 points from 0 to 5 85 | linspace=np.linspace(0,5,10) #np.linspace(start,end,number of output or points) 86 | print('10 points from 0 to 5 :\n',linspace) 87 | 88 | 89 | 90 | #How to create 2 dimensional square matrix use np.eye(length) 91 | square_matrix=np.eye(4) #Creating identity matrix 92 | print(square_matrix) 93 | 94 | 95 | 96 | #How to create numpy array using rand 97 | #give single elemnt as parameter for 1d array and use 2 parameter for multidimenssional array 98 | random_array=np.random.rand(4) 99 | multi_dimenssion=np.random.rand(4,4) 100 | print(random_array) 101 | print(multi_dimenssion) 102 | 103 | 104 | #To get the random integer from 1 to 100 105 | print(np.random.randint(1,100)) 106 | 107 | #To Get the 10 random numbers from 1 to 100 108 | print(np.random.randint(1,100,10)) 109 | -------------------------------------------------------------------------------- /MachineLearning/Numpy/2.Indexing_Selection_in_Numpy.py: -------------------------------------------------------------------------------- 1 | ''' 2 | created By:Ravishankar Chavare 3 | version python 3.7 4 | How to use indexing and selection on numpy array 5 | 1.brackets 6 | 2.slicing 7 | 8 | ''' 9 | import numpy as np 10 | 11 | numpy_array=np.arange(1,15) 12 | # this will create [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14] 13 | #to access 7 element from array use 7 as index use brackets for indexing 14 | 15 | element_at_7th=numpy_array[7] 16 | print('element_at_7th :',element_at_7th) 17 | 18 | 19 | #to print element 1 to 4 need to use slicing : 20 | #use :arrayname[startindexincluding:end index exlcuding] 21 | slice_element=numpy_array[0:4] #or u can normally use numpy_array[:4] 22 | 23 | print(slice_element) 24 | 25 | 26 | #If you want to set starting 3 element value to 100 27 | 28 | numpy_array[0:3]=100 29 | 30 | print(numpy_array) 31 | 32 | 33 | 34 | #if you get slice from a numpy_array and modify it actually it will also modify to main array 35 | 36 | main_array=np.arange(20) 37 | print("main array", main_array) 38 | 39 | slice_of_array=main_array[0:5] 40 | 41 | print("slice of array",slice_of_array) 42 | 43 | slice_of_array[:]=5 44 | print("slice of array after modification",slice_of_array) 45 | 46 | #Here main array values also changed because slicing array refrence the array 47 | print("main array after slice changed", main_array) 48 | 49 | 50 | 51 | #To Solve above problem use array copy method to create the exact copy of array 52 | num_array=np.arange(10) 53 | 54 | copy_array=num_array[0:3].copy() 55 | print(copy_array) 56 | 57 | copy_array[:]=1 58 | 59 | print("Sliced array ",copy_array) 60 | print("num_array :",num_array) 61 | 62 | 63 | #To Print 2d arraay 64 | array_2d=np.array([[5,6,7],[12,10,15],[16,14,45]]) 65 | 66 | print(array_2d) 67 | 68 | '''To accessing element from 2d array there are general two ways 69 | 1.Single bracket Arrary_name[row,coloumn] 70 | 2.double bracket array_name[row][coloumn] 71 | 72 | [[ 5 6 7] 73 | [12 10 15] 74 | [16 14 45]] 75 | 76 | ''' 77 | 78 | #1To Access 10 element use following indexing method like arrayname[1][1] 79 | print(array_2d[1][1]) 80 | 81 | #another method to acess 10 is: array[row,coloumn] 82 | 83 | print(array_2d[1,1]) 84 | 85 | 86 | 87 | #To grabing multiple elment from array usi slicing in numpy array 88 | 89 | #To Accessing 5,6,12,10 90 | print(array_2d[:2,1:]) 91 | 92 | 93 | #------------------------------------------------------------------------- 94 | #Conditional selection on numpy array 95 | 96 | simpl_array=np.arange(2,100) 97 | 98 | #Now find out the elment which are less than 10 from above numpy Array 99 | 100 | #just create a simple array to store the value 101 | lessthan10_array=simpl_array[simpl_array<10] 102 | 103 | print(lessthan10_array) 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | -------------------------------------------------------------------------------- /MachineLearning/Numpy/3.Operation_on_numpy_array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Created By:Ravishankar Chavare 3 | version:Python Version 3.7 4 | ''' 5 | 6 | import numpy as np 7 | 8 | first_array=np.arange(0,5) 9 | 10 | print("First Array: ",first_array) 11 | 12 | 13 | #Addition operation on array 14 | 15 | addtion_array=first_array+first_array 16 | 17 | print("Addition of two numpy array",addtion_array) 18 | 19 | 20 | #Perform a Scalar operation means add 100 in each element of test_array 21 | test_array=np.arange(0,10) 22 | scalar_array=test_array+100 23 | print("Scalar array Operation(add 100 to each array element) : ",scalar_array) 24 | 25 | 26 | #when 0/0 in normal python it will shows error but in numpy array operation it will give nan value and a single warning 27 | 28 | print(first_array/first_array) 29 | 30 | #when ement/0 it will give infinity 31 | print(first_array/0) 32 | 33 | 34 | #square of first arry 35 | 36 | print("Square of First Array: ",first_array**2) 37 | 38 | 39 | #To print square root of first_arra element 40 | print('Square root of first array:',np.sqrt(first_array)) 41 | 42 | 43 | #To get Expontial of array element 44 | print(np.exp(first_array)) 45 | 46 | 47 | #To Find out max elemnt from array 48 | 49 | print("Max element from first Array: ",np.max(first_array)) 50 | 51 | #to find min 52 | print("min element from first Array: ",np.min(first_array)) 53 | 54 | 55 | #To find Out log or sin values of elemenyt 56 | print("Sin values of first Array: ",np.sin(first_array)) 57 | -------------------------------------------------------------------------------- /MachineLearning/Numpy/BasicNumpy.md: -------------------------------------------------------------------------------- 1 | ## Numpy 2 | 3 | ![Numpy](https://numpy.org/_static/numpy_logo.png) 4 | 5 | ### Introduction 6 | - Numpy is an abbreviated form of **Numerical Python** or **Numeric Python**. 7 | - It is the most basic yet powerful package for scientific computing and data manipulation in Python. 8 | - It supports large, multidimensional arrays and matrices. 9 | - It is generally used for Data Analysis and is a part of scientific python. 10 | - It is an extension module for Python, mostly written in C. 11 | 12 | Official Website:https://numpy.org/ 13 | 14 | ### Why Numpy? 15 | - Numpy support N-dimensional array. 16 | - It consumes less memory. 17 | - NumPy array is faster than Python List 18 | - We can create an n-dimensional array in python using numpy.array(). 19 | - Numpy array provide multidimensional slicing on an array 20 | - Easy for matrix computation 21 | - In Python Array is not present where list store different types of elements but numpy helps to behave like a normal array to store similar data types. 22 | - the list need looping to perform scalar operations 23 | 24 | Normal List 25 | ``` 26 | lst=[1,2,3,4] 27 | #Add 5 to every element 28 | res=[elem+5 for elem in lst] 29 | print(res) 30 | #Result: 31 | ``` 32 | Output: 33 | ``` 34 | [6, 7, 8, 9] 35 | ``` 36 | 37 | Using Numpy Array 38 | ```python 39 | import numpy as np 40 | lst=np.array([1,2,3,4]) 41 | res=lst+5 42 | print(res) 43 | ``` 44 | Output: 45 | ``` 46 | [6 7 8 9] 47 | ``` 48 | 49 | - Consumes Less Memory as Compared to Python List 50 | Python List Memory Consumes 51 | ```python 52 | import sys 53 | lst=list(range(0,100)) 54 | #Add 5 to every element 55 | res=sys.getsizeof(lst) 56 | print(res) 57 | ``` 58 | Output: 59 | ``` 60 | 1008 61 | ``` 62 | 63 | Numpy Array Memory Consumes 64 | ```python 65 | import sys 66 | import numpy as np 67 | lst=np.array(range(0,100)) 68 | res=sys.getsizeof(res) 69 | print(res) 70 | ``` 71 | Output: 72 | ``` 73 | 28 74 | ``` 75 | 76 | 77 | ### Install Numpy Array 78 | - Open command prompt in windows machine and type following command 79 | ```python 80 | pip install numpy 81 | ``` 82 | - After Completion of Installation open Jupyter Notebook or python shell to test whether numpy is properly install or not. 83 | - Type 84 | 85 | ```python 86 | import numpy 87 | ``` 88 | and hit Enter if it does not give any error then your numpy is installed properly(Do not try on Normal command Prompt use python shell or any idle). 89 | 90 | 91 | ### import Numpy in Your Program 92 | write down following line for importing Numpy 93 | ```python 94 | import numpy 95 | ``` 96 | or Rename Numpy in Import as follows 97 | ```python 98 | import numpy as np 99 | ``` 100 | 101 | 102 | ### Create Simple Numpy Array 103 | 104 | - To Create a simple numpy array use *array()* function. 105 | 106 | Syntax: 107 | ```python 108 | import numpy as np 109 | Numpy_array=np.array() 110 | ``` 111 | 112 | Example: 113 | ```python 114 | import numpy as np 115 | np_array=np.array([1,2,3,4,5]) 116 | 117 | #print Type of Array 118 | print(type(np_array)) 119 | 120 | #print numpy array 121 | print(np_array) 122 | ``` 123 | Output: 124 | ``` 125 | 126 | [1 2 3 4 5] 127 | ``` 128 | ![numpy](https://github.com/chavarera/PythonScript/blob/master/MachineLearning/Numpy/img/numpyarray.png) 129 | -------------------------------------------------------------------------------- /MachineLearning/Numpy/img/np1d.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/MachineLearning/Numpy/img/np1d.png -------------------------------------------------------------------------------- /MachineLearning/Numpy/img/np2d.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/MachineLearning/Numpy/img/np2d.png -------------------------------------------------------------------------------- /MachineLearning/Numpy/img/np3d.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/MachineLearning/Numpy/img/np3d.png -------------------------------------------------------------------------------- /MachineLearning/Numpy/img/numpyarray.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/MachineLearning/Numpy/img/numpyarray.png -------------------------------------------------------------------------------- /MachineLearning/Pandas/1.BasicofPandas.py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://www.listendata.com/2017/12/python-pandas-tutorial.html 3 | 4 | What is Pandas: 5 | Pandas Module is commonly used for data manipulation and data anlysis purpose. 6 | It is a very powerful and versatile package which makes data cleaning 7 | and wrangling much easier and pleasant. 8 | 9 | Why Pandas: 10 | -Reading Data from diffrent sources like csv,xlsx,Databases and Others 11 | -pandas is an open source, BSD-licensed library providing high-performance, easy-to- 12 | use data structures and data analysis tools for the Python programming language. 13 | -iterate over the rows of datasets 14 | -Exporting Data to CSV or Excel Format 15 | -Easy handling of missing data 16 | -Flexible reshaping and pivoting of data sets 17 | 18 | What type of data can be handled using pandas: 19 | -Tabular data with heterogeneously-typed columns 20 | -ordered and unordered 21 | -Any other form of observational / statistical data sets 22 | 23 | Installing Pandas: 24 | using pip 25 | Open Command Prompt and type 26 | >pip install pandas 27 | 28 | wait some time to get install pandas in your system 29 | 30 | 31 | Importing Pandas: 32 | import pandas as pd 33 | ''' 34 | #importing pandas 35 | import pandas as pd 36 | 37 | 38 | #importing Dataset from csv 39 | data=pd.read_csv('users.csv') 40 | 41 | 42 | #Get Coloumns name 43 | print(data.columns) 44 | 45 | '''get first 2 Coloumns name''' 46 | print(data.columns[:2]) #indexing in python start from 0 47 | 48 | 49 | #varibale Type in pandas data 50 | '''To Know the Variable Type 51 | object-string or character 52 | int64-numeric values without decimals 53 | ''' 54 | print(data.dtypes)#object 55 | print(data['ZIP'].dtypes)#int64 56 | 57 | #changes the variable type of an object 58 | data['ZIP']=data['ZIP'].astype(float) 59 | print(data['ZIP'].dtypes) #float 60 | 61 | #To get the no of rows and coloumns 62 | print(data.shape)#(3,15) 63 | 64 | 65 | #To views 5 rows 66 | ''' 67 | By default head( ) shows first 5 rows. 68 | If we want to see a specific number of rows we can mention it in the parenthesis like data.head(5) shows 5 rows data. 69 | Similarly tail( ) function shows last 5 rows by default. 70 | ''' 71 | print(data.head())#return 5 rows from starting 72 | print(data.head(2))#return 2 rows from starting 73 | print(data.tail())#return 5 rows from ending 74 | print(data.tail(2))#return 2 rows from ending 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /MachineLearning/Pandas/4.ConditionalSelectionPandas.py: -------------------------------------------------------------------------------- 1 | ##------------------------------------------------------------------------------------------------------ 2 | # 3 | #Created By:Ravishankar Chavare 4 | #version:python 3.7 5 | #Date:24/12/18 6 | #File_des:Condtional Indexing and some advanced Selection 7 | #Offical Documentation: 8 | ##------------------------------------------------------------------------------------------------------ 9 | import numpy as np 10 | import pandas as pd 11 | from numpy.random import randn 12 | 13 | 14 | ##--------------------------------------------------------------------------------------------------------------------------------- 15 | # Selection And Indexing In pandas dataframe 16 | ##--------------------------------------------------------------------------------------------------------------------------------- 17 | 18 | #Create Data Frame using Random int numbers 19 | mat=randn(6,5) #6*5 matrix of random number 20 | rows=['A','B','C','D','E','F'] #index 21 | coloumns=['V','W','X','Y','Z'] #coloumns 22 | df=pd.DataFrame(mat,rows,coloumns) 23 | 24 | 25 | 26 | #To Apply Conditional Selection on whole dataframe Entire DataFrame 27 | #object dataframe>0 will find out all element from dataframe if his value is greator than 0 28 | print("Simple Condtional Selection df>0 \n",df>0) #but this will give only df with true or false value just pass such condition to df t get actual result 29 | 30 | #THis will give you dataframe object with value greator than 0 and if value is less than zero or missing df will return NaN instead of blank 31 | print("\n\nSimple Condtional Selection df[df>2] \n",df[df>0]) 32 | 33 | 34 | #To Apply Condtional selection on the coloumns 35 | #Find out rows if B coloumn value is less than 0 36 | 37 | print(df['W']<0) #this will return true or false value 38 | print(df[df['W']<0]) #this will return entrie data frame if w COloumn element is not less than 0 39 | 40 | 41 | #For Multiple Conditions use & to add more condtions 42 | #print dataframe if w coloumns elements are less than 0 and y coloumns with greator than 1 43 | 44 | dataf=df[(df['W']<0) & (df['Y']>0)] #Python by defualt and,or conditional not working use & for and ,| for or operation 45 | 46 | print(dataf) 47 | 48 | 49 | ##--------------------------------------------------------------------------------------------------------------------------------- 50 | # Set And Reset Index Of data frame 51 | ##--------------------------------------------------------------------------------------------------------------------------------- 52 | 53 | 54 | #To reseting the Index 55 | print(df.reset_index()) #This Will temporary removes the added index and give by defualt index 56 | #this will reset an inde to an coloumn and you will get numeric index 57 | 58 | 59 | #To settting new index 60 | new_index=['ab','bc','cd','ef','gh','hi'] 61 | df['new_index']=new_index # this will added a new coloumn name with new_index now you can set it as index 62 | df.set_index("new_index") 63 | df.set_index("new_index") # this will temporary add the new index to add permanant index use inplace=True 64 | print(df.set_index("new_index")) 65 | 66 | -------------------------------------------------------------------------------- /MachineLearning/Pandas/5.SingleDataFramePlotUSingMatplotlib.py: -------------------------------------------------------------------------------- 1 | ##-------------------------------- 2 | ##Created By:Ravishankar Chavare 3 | ##version:python 3.7 4 | ##Date:11/03/19 5 | ##File_des:Simple DataFrame Plotting 6 | ##-------------------------------- 7 | 8 | #-----------------------------------IMPORT Packages--------------------------------------------------- 9 | import pandas as pd #import Pandas 10 | import matplotlib.pyplot as plt #For Ploting the Plot 11 | from matplotlib import style #assiging the Style to plot 12 | 13 | 14 | #Here use any Style Format which are alredy designed 15 | #for Custom style visit here https://matplotlib.org/users/style_sheets.html 16 | style.use("ggplot") 17 | 18 | 19 | #Simple Data Frame Create 20 | df=pd.DataFrame({'day':[1,2,3,4,5],'visitor':[200,230,100,210,250],'BounceRate':[10,28,1,2,4]}) 21 | 22 | #Set Index as Day 23 | df.set_index("day",inplace=True) 24 | 25 | 26 | #Now plot the Datframe using datframe.plot() 27 | df.plot() 28 | 29 | #Set the title to plotted Graph 30 | plt.title("VisitorCount") 31 | 32 | #Now Show The plot using plt.show() 33 | plt.show() 34 | 35 | -------------------------------------------------------------------------------- /MachineLearning/Pandas/6.ChangingIndexAndHeaders.py: -------------------------------------------------------------------------------- 1 | ##-------------------------------- 2 | ##Created By:Ravishankar Chavare 3 | ##version:python 3.7 4 | ##Date:11/03/19 5 | ##File_des:Changing Index and Header (DataFrame) 6 | ##-------------------------------- 7 | 8 | #-----------------------------------IMPORT Packages--------------------------------------------------- 9 | import pandas as pd #import Pandas 10 | 11 | #Simple Data Frame Create 12 | df=pd.DataFrame({'day':[1,2,3,4,5],'visitor':[200,230,100,210,250],'BounceRate':[10,28,1,2,4]}) 13 | 14 | #To Changing Index just use df.set_index("keyName",inplace=True) 15 | df.set_index("day",inplace=True) 16 | 17 | #To Change The Header rename visitor header with Users 18 | df=df.rename(columns={"visitor":"Users"}) 19 | 20 | #Now Print The Simple Changed Index and Headers 21 | print(df) 22 | -------------------------------------------------------------------------------- /MachineLearning/Pandas/7.ImportAndExportFiles.py: -------------------------------------------------------------------------------- 1 | ##-------------------------------- 2 | ##Created By:Ravishankar Chavare 3 | ##version:python 3.7 4 | ##Date:11/03/19 5 | ##File_des:Reading a Data File And Exporting it into RequiredFormat 6 | ##-------------------------------- 7 | 8 | #-----------------------------------IMPORT Packages--------------------------------------------------- 9 | import pandas as pd #import Pandas 10 | 11 | ''' 12 | Using Pandas You can import variety of data files for analysing or manipulation you can use same for exporting 13 | dataframes to different Forms 14 | read_clipboard 15 | read_csv 16 | read_excel 17 | read_feather 18 | read_fwf 19 | read_gbq 20 | read_hdf 21 | read_html 22 | read_json 23 | read_msgpack 24 | read_parquet 25 | read_pickle 26 | read_sas 27 | read_sql 28 | read_sql_query 29 | read_sql_table 30 | read_stata 31 | read_table 32 | 33 | ''' 34 | #You can Get the list of data files or structures supoorting by pandas for import and Export using follwing simple Example 35 | formats=[val for val in dir(pd) if 'read' in val] 36 | print(formats) 37 | 38 | 39 | #For Reading files or datastructur simple use pd.read_datastructure(path) 40 | 41 | 42 | #for Reading csv File 43 | csvfile=pd.read_csv("zipcodes.csv") 44 | 45 | 46 | #Now Export the File into html 47 | csvfile.to_html("zipcodesoutputfile.html") 48 | -------------------------------------------------------------------------------- /MachineLearning/img/field.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chavarera/PythonScript/bbbb6aff2cffe08afe80eb74e2826971c9e2496d/MachineLearning/img/field.png -------------------------------------------------------------------------------- /Module/CustomModule.md: -------------------------------------------------------------------------------- 1 | ## Custom Module 2 | 3 | - Custom module is any python file that contains python statement and definations, 4 | - You can Create custom module as a normal file and place within that folder 5 | 6 | create simple module named with **Calculation.py** 7 | ```python 8 | def Addition(a,b): 9 | '''Addition() function accept two integer 10 | and return Additon of two variables''' 11 | return a+b 12 | 13 | def Multiplication(a,b): 14 | '''Multiplication() function accept two integer 15 | and return Multiplication of two variables''' 16 | return a*b 17 | 18 | def Substraction(a,b): 19 | '''Substraction() function accept two integer 20 | and return Substraction of two variables''' 21 | return a-b 22 | 23 | #variable of Module 24 | var1= {"name": "John"} 25 | ``` 26 | 27 | 28 | import this module in your program using 29 | ```python 30 | import as 31 | ``` 32 | 33 | To access functions of Calculation module using cal module 34 | ```python 35 | ObjectName.(paramter) 36 | ``` 37 | 38 | To access variable name from module 39 | ```python 40 | ObjectName.variableName 41 | ``` 42 | 43 | *Example* 44 | ```python 45 | #import Calculation module 46 | import Calculation 47 | 48 | #get Documentation of module 49 | print(help(Calculation)) 50 | 51 | #Call Addition function From Calculation Module 52 | add=Calculation.Addition(5,4) 53 | print(add) 54 | #Result:9 55 | 56 | 57 | #Call Multiplication Function from Calculation.py 58 | mul=Calculation.Multiplication(4,8) 59 | print(mul) 60 | #Result:32 61 | 62 | 63 | #get The variable from module 64 | var=Calculation.var1['name'] 65 | print(var) 66 | #Result:jhon 67 | 68 | 69 | #list out customcuntion 70 | print(dir(Calculation)) 71 | ''' 72 | ['Addition', 'Multiplication', 'Substraction', 73 | '__builtins__', '__cached__', '__doc__', 74 | '__file__', '__loader__', '__name__', 75 | '__package__', '__spec__', 'var1'] 76 | ``` 77 | Output 78 | ``` 79 | Help on module Calculation: 80 | 81 | NAME 82 | Calculation 83 | 84 | FUNCTIONS 85 | Addition(a, b) 86 | Addition() function accept two integer 87 | and return Additon of two variables 88 | 89 | Multiplication(a, b) 90 | Multiplication() function accept two integer 91 | and return Multiplication of two variables 92 | 93 | Substraction(a, b) 94 | Substraction() function accept two integer 95 | and return Substraction of two variables 96 | 97 | DATA 98 | var1 = {'name': 'John'} 99 | 100 | FILE 101 | /tmp/sessions/e874d61211858ec0/Calculation.py 102 | 103 | 104 | None 105 | 9 106 | 32 107 | John 108 | ['Addition', 'Multiplication', 'Substraction', 109 | '__builtins__', '__cached__', '__doc__', '__file__', 110 | '__loader__', '__name__', '__package__', '__spec__', 'var1'] 111 | ``` 112 | -------------------------------------------------------------------------------- /Module/os/AccessFileNames.md: -------------------------------------------------------------------------------- 1 | ## File Name Accessing 2 | 3 | ### Functions For Reading FileNames and Directory 4 | 5 | following are some function used to accessing filename and directory using os module in python 6 | ``` 7 | 1. scandir() 8 | 2. listdir() 9 | 3. walk() 10 | ``` 11 | 12 | #### 1.scandir() 13 | 14 | - Iterator of DirEntry objects for given path 15 | - When you not pass a path parameter defualt **path='.'** is passed to scandir() function which is current working path. 16 | - To get the help documentation of **os.scandir()** use **help()** functiona and pass the os.scandir() as object 17 | ``` 18 | help(os.scandir) 19 | ``` 20 | 21 | Syntax: 22 | ```python 23 | os.scandir(path) 24 | ``` 25 | 26 | Example: 27 | ```python 28 | #import required module 29 | import os 30 | 31 | #os.scandir() return as iterator object 32 | directory_data=os.scandir() 33 | 34 | #print type of directory_data 35 | print(type(directory_data)) 36 | #Result: 37 | 38 | 39 | #iterate scandir object 40 | for d in directory_data: 41 | print(d) 42 | ``` 43 | Output: 44 | ``` 45 | 46 | 47 | 48 | 49 | ``` 50 | 51 | #### 2.listdir() 52 | 53 | - Return a list containing the names of the files in the directory. The filenames returned will be str. 54 | - If the path is None, uses the path='.' 55 | 56 | Syntax: 57 | ```python 58 | os.listdir('path of directory') 59 | ``` 60 | 61 | Example: 62 | ```python 63 | #import required module 64 | import os 65 | 66 | #Get the current working path as a path to scan files and directory 67 | path=os.getcwd() 68 | 69 | #Get List of filenames avialable inside path 70 | files=os.listdir(path) 71 | print(files) 72 | ``` 73 | Output: 74 | ``` 75 | ['main.py', 'test.py', 'folderName'] 76 | ``` 77 | 78 | 79 | #### 3.walk() 80 | 81 | - **walk()** is a Directory tree generator. 82 | - For each directory in the directory tree rooted at the top (including top itself, but excluding '.' and '..') 83 | - **walk()** Returns the 3 different tuple for 84 | ``` 85 | dirpath, dirnames, filenames 86 | ``` 87 | 88 | **dirpath**: This is a string path to the directory. 89 | 90 | **dirnames**: Is the list of the subdirectories inside the dirpath. (excluding '.' and '..') 91 | 92 | **filename**: Is the list of the name of the nondirectory files in dirpath 93 | 94 | **Note**: that the filenames in the lists are just names, with no path components. 95 | you can get the full path of file name using 96 | ``` 97 | os.path.join(dirpath,filenames) 98 | ``` 99 | 100 | Syntax: 101 | ```python 102 | os.walk('path of Root Directory') 103 | ``` 104 | 105 | Example: 106 | ```python 107 | #import required module 108 | import os 109 | 110 | #Get Current directory path 111 | path=os.getcwd() 112 | 113 | #os.walk(path) return iteraable object 114 | for dirpath, dirnames, filenames in os.walk(path): 115 | 116 | print("*Directory path*") 117 | print(dirpath) 118 | 119 | print("\n***List of Directory*") 120 | print(dirnames) 121 | 122 | print("\n***List of files*") 123 | print(filenames) 124 | ``` 125 | Output: 126 | ``` 127 | *Directory path* 128 | /Demo/Python 129 | 130 | *List of Directory* 131 | [] 132 | 133 | *List of files* 134 | ['main.py', 'test.py', 'folderName'] 135 | 136 | *Directory path* 137 | /Demo/Python1 138 | 139 | *List of Directory* 140 | [] 141 | 142 | *List of files* 143 | ['help.txt'] 144 | ``` 145 | -------------------------------------------------------------------------------- /Module/wikipedia/1.BasicOfWikipedia.py: -------------------------------------------------------------------------------- 1 | ''' 2 | created by:Ravishankar Chavare 3 | 4 | To install wikipedia use pypi open command prompt and type 5 | 6 | pip install wikipedia 7 | 8 | 9 | To import into python program use 10 | 11 | import wikipedia 12 | ''' 13 | 14 | import wikipedia 15 | 16 | 17 | #To search a simple query on wikipedia 18 | #use wikipedia.search("keyword") 19 | 20 | searched_data=wikipedia.search("India") 21 | 22 | print(searched_data) 23 | ''' 24 | output according to keyword 25 | ['India', 'Irreligion in India', 'East India Company', 'Constitution of India', 26 | 'Government of India', 'Christianity in India', 'Savdhaan India', 'Star India', 27 | 'States and union territories of India', 'Retailing in India'] 28 | ''' 29 | 30 | 31 | #get fewer or more results by using the results kwarg: 32 | #Example wikipedia.search("keyword", results=count) 33 | 34 | print(wikipedia.search("India",results=3)) 35 | 36 | 37 | #To get the short description of keyword use summary method like 38 | #wikipedia.summary("keyword") 39 | 40 | info_india=wikipedia.summary("india") 41 | print(info_india) 42 | 43 | 44 | 45 | 46 | 47 | #Some Basic Exception Handeling IF You searched a keyword which is not available 48 | #then it will generate exception with some suggested keyword use wikipedia.exceptions.DisambiguationError exceptions for getting options 49 | try: 50 | mercury=wikipedia.summary("Mercury") 51 | except wikipedia.exceptions.DisambiguationError as e: 52 | ask_user=str(input("Given keyword not found we found some keyword regarding your search do you want y/n")) 53 | 54 | if(ask_user=='y'): 55 | print(len(e.options)); 56 | print(e.options) 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /Module/wikipedia/2.WikipediaPageParsing.py: -------------------------------------------------------------------------------- 1 | ''' 2 | created by:Ravishankar Chavare 3 | 4 | We alredy Learn Basic of wikipedia keywords and short description now we are here to learn the full 5 | page parsing of wikipedia 6 | ''' 7 | import wikipedia 8 | 9 | #To get full page details and data use wikipedia.page("keyword") 10 | 11 | simple_page=wikipedia.page("India"); 12 | 13 | #now simple_page is wikipedia object you can extact data from it 14 | 15 | #1.Get The Title Of page 16 | title=simple_page.title 17 | print("Title of Page: ",title) 18 | 19 | 20 | #2.Get The url of wikipedia Page 21 | url=simple_page.url 22 | print("url of searched page : ",url) 23 | 24 | 25 | #3.To Get the Content Of Page 26 | content=simple_page.content 27 | print("Content: ",content) 28 | 29 | 30 | #4.To Get the Image of page 31 | 32 | image_url=simple_page.images #This will Collect All Images url into list 33 | 34 | #To print simple first image url You can use 35 | print("First Image Url:",image_url[0]) 36 | 37 | 38 | 39 | ''' 40 | To change the language of the Wikipedia you are accessing, 41 | use wikipedia.set_lang. Remember to search 42 | for page titles in the language that you have set, not English!: 43 | ''' 44 | 45 | #To set Language as english 46 | wikipedia.set_lang("en") 47 | print(wikipedia.summary("india")) 48 | 49 | 50 | #To Get Available languages list 51 | languages=wikipedia.languages() 52 | 53 | #To Check That Language is avilable in wikipedia or not 54 | print('en' in wikipedia.languages()) #this will give true or false 55 | 56 | 57 | 58 | 59 | ''' 60 | for more tutorial Visit 61 | https://wikipedia.readthedocs.io/en/latest/quickstart.html 62 | 63 | ''' 64 | 65 | -------------------------------------------------------------------------------- /Regex/1.BasicOfRegularExpression.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A regular expression is a special sequence of 3 | characters that helps you match or find other strings 4 | or sets of strings, using a specialized syntax 5 | held in a pattern. Regular expressions are widely used in UNIX world. 6 | ''' 7 | 8 | ''' 9 | IDENTIFIRES:- 10 | 11 | \d any number 12 | \D anything except a number 13 | 14 | \s space 15 | \S anything except a space 16 | 17 | \w any charcter 18 | \W anything except a character 19 | 20 | . any character but except new line 21 | \b white space arround words 22 | \. a period(this will find out . in given string) 23 | 24 | 25 | 26 | MODIFIRES:- 27 | 28 | {2,6} describing about numbers expecting result 2-6 29 | + Match 1 or More 30 | ? Match 0 or 1 31 | * Match 0 or more 32 | $ Match the end of string 33 | ^ Matching the begining of string 34 | | either or (Example {1,3} | {6-9}) 35 | [] range or variance example [1-5],[A-Z] 36 | {x} expecting "x" amount 37 | 38 | 39 | White Spaces 40 | \n new line 41 | \t tab 42 | \e escape 43 | \s space 44 | \f from feed 45 | \r return 46 | 47 | 48 | Note: 49 | We can use diffrent solution for solving same problem 50 | ''' 51 | 52 | 53 | import re #importing regular expression module 54 | 55 | 56 | mystring=''' 57 | hi Akash is 67 years old, 58 | and Ajay is 28 years old, Raj is 109''' 59 | 60 | #find ages 61 | ''' 62 | re is module name 63 | findall is method 64 | r is for regular expression 65 | \d finding digit 66 | {1,3} modifier to find 1 or 2 or 3 digit number 67 | 68 | For Example 69 | data='100 is number 5 where abcd@gmail.com is email. 54854584' 70 | To find Exact 3 digit group use {3} after the \d 71 | rex='\d{3}' 72 | searchall=findall(rex,data) 73 | output=['100','548','545'] 74 | 75 | To find 1,2,3, digit number use {1,3} 76 | rex='\d{1,3}' 77 | searchall=findall(rex,data) 78 | output=['100','5','548','545','84'] 79 | ''' 80 | ages=re.findall(r'\d{1,3}',mystring) 81 | print(ages) 82 | 83 | # this will give output : ['67', '28', '109'] 84 | 85 | 86 | # Now Find out name 87 | names=re.findall(r'[A-Z][a-z]*',mystring) 88 | print(names) 89 | 90 | #this will give output :['Akash', 'Ajay', 'Raj'] 91 | 92 | 93 | # save this output in dictonary 94 | mydict={} 95 | index=0 96 | for name in names: 97 | mydict[name]=ages[index] 98 | index=index+1 99 | print(mydict) 100 | -------------------------------------------------------------------------------- /Regex/2.SomeTextManipulation.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Regular expressions are case sensitive 3 | so [A-Z] will give result from uppercase A-Z letter 4 | [a-z] will give result from lowercase letter a-z 5 | 6 | ''' 7 | import re 8 | mystring=" my name is ravi visit my website https://protutr.com" 9 | 10 | #Matching Simple Text 11 | output=re.findall(r'my',mystring) 12 | print(output) 13 | 14 | # this will just serach simple 'my' text inside the input string and give output 15 | #output:['my', 'my'] 16 | 17 | 18 | #Matching A Character 19 | '''Multiple . s may be used, either together (one after the other—using .. 20 | will match any two characters next to each other) or in different locations 21 | in the pattern''' 22 | 23 | mytext=''' 24 | abc1.txt 25 | abcd.txt 26 | abc2.txt 27 | ax.txt 28 | abc.txt 29 | antk.txt 30 | tbc.txt 31 | abc3.txt 32 | ''' 33 | 34 | '''find all text starting with abc and followed by another character''' 35 | outputdata=re.findall(r'abc.',mytext) 36 | print(outputdata) 37 | #output ['abc1', 'abcd', 'abc2','abc.', 'abc3'] 38 | # . matches any character, alphabetic characters, digits, and even . itself: 39 | #if you want to find out all text preceding any character and followed any charcter and in this middle b 40 | print(re.findall(r'.b.',mytext)) #output ['abc', 'abc', 'abc', 'abc', 'tbc', 'abc'] 41 | 42 | 43 | -------------------------------------------------------------------------------- /Regex/3.MatchingSetOfCharacter.py: -------------------------------------------------------------------------------- 1 | '''In regular expressions a set of 2 | characters is defined using the metacharacters [ and ]. [ and ] define a 3 | character set, everything between them is part of the set, and any one of 4 | the set members must match (but not all) 5 | ''' 6 | import re 7 | inputstring=''' 8 | abc1.txt 9 | abcd.txt 10 | abc2.txt 11 | abc3.txt 12 | ca1.xls 13 | na1.xls 14 | na2.xls 15 | sa1.xls 16 | ca1.xls 17 | ''' 18 | 19 | #Find out text whose name start with n or c and followed by 'a' followed by any character 20 | #and then .xls 21 | outputstring=re.findall(r'[nc]a..xls',inputstring) 22 | print(outputstring) 23 | 24 | #output :['ca1.xls', 'na1.xls', 'na2.xls', 'ca1.xls'] 25 | ''' 26 | Describing ["nc]a..xls" Regular Expression 27 | 28 | [nc] start with n or c 29 | a second letter must be a 30 | . third letter anything 31 | . fourth letter also anything 32 | xls and then xls 33 | 34 | ''' 35 | 36 | 37 | 38 | 39 | #Example 2 Findout output string using character set range 40 | output=re.findall(r'[nc]a[0-1].xls',inputstring) 41 | print(output) 42 | #output :['ca1.xls', 'na1.xls', 'ca1.xls'] 43 | ''' 44 | [0-1] this is charcter set range from 0 to 1 you can specify it according to your need 45 | ''' 46 | -------------------------------------------------------------------------------- /Regex/4.EscapingMetacharcters.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Metacharacters are characters that have special meaning within regular 3 | expressions. The period (.) ,brackets [] are metacharacters; 4 | 5 | To escape a special metacharacter use \ before that metacharacter 6 | 7 | ''' 8 | import re 9 | inputstring=''' 10 | a=[] 11 | b=['.',1,5] 12 | ''' 13 | 14 | #Find out the occurence of [] in input string and print 15 | #outputstring=re.findall(r'[]',inputstring) this is the wrong solution 16 | outputstring=re.findall(r'\[\]',inputstring) 17 | print(outputstring) 18 | 19 | #here [] is escaped using \ charcter as \[\] 20 | -------------------------------------------------------------------------------- /Regex/5.FindSingleAndMultipleOccurence.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Use of search method in Regular expression 3 | 4 | 1:single First match 5 | re.search() to find the first match for a pattern. 6 | 7 | 2:Multiple Match 8 | findall() finds *all* the matches and returns them as a list of strings, with each string representing one match. 9 | 10 | ''' 11 | 12 | import re #import re module 13 | 14 | 15 | #input data 16 | inputstring=''' 17 | Hello i am Chavare Ravishakar working as data Engineeer . 18 | I am 18 year Old and my email id is ravisha.nkarc@t-outlook.biz 19 | and personal email is demo@email.com, testdemo@gmail.com,charm565@gmail.com 4gamd@dfhj3.com 20 | ''' 21 | 22 | 23 | 24 | #Simple Search the First occurence of an given pattern 25 | match=re.search(r'[\w.-]+@[\w.-]+',inputstring) 26 | print('**Using re.search() **') 27 | if match: 28 | print(match.group()) 29 | else: 30 | print('No match Found') 31 | 32 | 33 | 34 | 35 | #To Find multiple Occurence of given pattern use re.findall() 36 | '''findall() is probably the single most powerful function in the re module''' 37 | print('\n** Using re.findall() **') 38 | 39 | emails=re.findall(r'[\w.-]+@[\w.-]+',inputstring) 40 | for e in emails: 41 | print(e) 42 | 43 | 44 | 45 | ''' 46 | Output:- 47 | 48 | **Using Search ** 49 | ravisha.nkarc@t-outlook.biz 50 | 51 | ** Using re.findall() ** 52 | ravisha.nkarc@t-outlook.biz 53 | demo@email.com 54 | testdemo@gmail.com 55 | charm565@gmail.com 56 | 4gamd@dfhj3.com 57 | ''' 58 | -------------------------------------------------------------------------------- /Regex/6.Findallonfileinput.py: -------------------------------------------------------------------------------- 1 | ''' 2 | For file you need to habbit to itterate all data through loop and call findall() method from loop 3 | or easist way 4 | 5 | Instead, let findall() do the iteration for you -- much better! 6 | Just feed the whole file text into findall() 7 | and let it return a list of all the matches in a single step 8 | ''' 9 | 10 | import re 11 | import os 12 | readfile=open('inputfile.txt','r') 13 | emails=re.findall(r'[\w.-]+@[\w.-]+',readfile.read()) 14 | for e in emails: 15 | print(e) 16 | -------------------------------------------------------------------------------- /Regex/BasicOfRegex.md: -------------------------------------------------------------------------------- 1 | ## Regex 2 | 3 | #### Introduction 4 | 5 | - **Regex** is a short form of Regular Expression. 6 | - a regular expression is denoted as RE (REs, regexes or regex pattern) are imported through re module. 7 | - the regular expression in programing language is used to describing the string search pattern. 8 | - A regular expression is a special sequence of characters that helps you match or find other strings 9 | or sets of strings, using a specialized syntax held in a pattern. 10 | - the regular expression could tell a program to search for specific text from the string and then to print out the result accordingly. 11 | - Regular expression supports various things like Modifiers, Identifiers, and White space characters. 12 | 13 | #### How To Import regular expression in python? 14 | - **re** is a built-in module in python to perform the regular expression 15 | ```python 16 | import re 17 | ``` 18 | 19 | Basic of re functions 20 | ``` 21 | 1. findall() 22 | 2. search() 23 | 3. split() 24 | 4. sub() 25 | ``` 26 | 27 | Some Basic pattern requirements 28 | 29 | ### IDENTIFIERS:- 30 | ``` 31 | \d any number 32 | \D anything except a number 33 | \s space 34 | \S anything except space 35 | \w any character 36 | \W anything except a character 37 | . any character but except new line 38 | \b white space around words 39 | \. a period(this will find out . in the given string) 40 | ``` 41 | 42 | ### MODIFIRES:- 43 | ``` 44 | {2,6} describing about numbers expecting result 2-6 45 | + Match 1 or More 46 | ? Match 0 or 1 47 | * Match 0 or more 48 | $ Match the end of string 49 | ^ Matching the begining of string 50 | | either or (Example {1,3} | {6-9}) 51 | [] range or variance example [1-5],[A-Z] 52 | {x} expecting "x" amount 53 | ``` 54 | 55 | ### White Spaces 56 | ``` 57 | \n newline 58 | \t tab 59 | \e escape 60 | \s space 61 | \f form feed 62 | \r return 63 | ``` 64 | 65 | **Note**: We can use a different solution for solving the same problem 66 | -------------------------------------------------------------------------------- /Regex/EscapingMetacharacters.md: -------------------------------------------------------------------------------- 1 | ## Escaping Metacharacters 2 | 3 | Escaping Metacharacters in regular Expression 4 | 5 | ### Metacharacters 6 | - Metacharacters are characters that have special meaning within regular expressions. 7 | - The period (.), brackets [] are some examples of metacharacters. 8 | - To escape a special metacharacter use \ before that metacharacter. 9 | 10 | Syntax: 11 | ```python 12 | pattern=r'\metacharacters' 13 | ``` 14 | 15 | Example normal : 16 | ```python 17 | #import required module 18 | import re 19 | 20 | #input string 21 | input_string="a=[hi] this is simple" 22 | 23 | # find out the text inside the [] 24 | #pattern=r'[\w+]' Wrong pattern 25 | 26 | pattern=r'[\w+]' 27 | result=re.findall(pattern,input_string) 28 | print(result) 29 | ``` 30 | Output: 31 | ``` 32 | ['a', 'h', 'i', 't', 'h', 'i', 's', 'i', 's', 's', 'i', 'm', 'p', 'l', 'e'] 33 | ``` 34 | 35 | Example Using escape metacharacters 36 | ```python 37 | #import required module 38 | import re 39 | 40 | 41 | input_string="a=[hi] this is simple" 42 | 43 | # find out the text inside the [] 44 | #pattern=r'[\w+]' Wrong pattern 45 | 46 | pattern=r'\[\w+\]' 47 | result=re.findall(pattern,input_string) 48 | print(result) 49 | 50 | #here [] is escaped using \ character as \[\] 51 | ``` 52 | Output: 53 | ``` 54 | ['[hi]'] 55 | ``` 56 | 57 | Example 3: 58 | 59 | Find out. occurrence in a given string 60 | ``` 61 | input_string='this is simple.python easy is a programming language.' 62 | ``` 63 | 64 | ```python 65 | import re 66 | 67 | input_string='this is simple.python easy is a programming language.' 68 | 69 | pattern=r'\.' 70 | result=re.findall(pattern,input_string) 71 | print(result) 72 | ``` 73 | Output: 74 | ``` 75 | ['.', '.'] 76 | 77 | ``` 78 | -------------------------------------------------------------------------------- /Regex/inputfile.txt: -------------------------------------------------------------------------------- 1 | Hello this data is from file 2 | Hello i am Chavare Ravishakar working as data Engineeer . 3 | I am 18 year Old and my email id is ravisha.nkarc@t-outlook.biz 4 | and personal email is demo@email.com, testdemo@gmail.com,charm565@gmail.com 4gamd@dfhj3.com 5 | -------------------------------------------------------------------------------- /Threading/0.MultiprocessingAndMultithreadingDifference.py: -------------------------------------------------------------------------------- 1 | ##------------------------------------------------------------------------------------------------------ 2 | #Created By:Ravishankar Chavare 3 | #version:python 3.7 4 | #Date:10/04/2019 5 | #File_des:Difference Between Multiprocessing and Multithreading 6 | ##------------------------------------------------------------------------------------------------------ 7 | ''' 8 | Multiprocessing and Multithreading both adds performance to the system. 9 | 10 | -Multiprocessing is adding more number of or CPUs/processors to the system which 11 | increases the computing speed of the system. 12 | 13 | -Multithreading is allowing a process to create more threads which increase the 14 | responsiveness of the system 15 | 16 | In Python, because of GIL (Global Interpreter Lock) a single python process cannot run threads 17 | in parallel (utilize multiple cores). 18 | It can however run them concurrently (context switch during I/O bound operations) 19 | ''' 20 | 21 | #--------------------------------------------------------------------------------------------------# 22 | # MultiProcessing 23 | #--------------------------------------------------------------------------------------------------# 24 | ''' 25 | Pros:- 26 | -Multiprocessing achieves true parallelism and is used for CPU-bound tasks 27 | -Multiprocessing adds CPUs to increase computing power. 28 | -Multiple processes are executed concurrently. 29 | -Separate memory space. 30 | -Avoids GIL limitations for cPython(Global Interpreter Lock for accessing Same Memory Location) 31 | -Child processes are interruptible/killable 32 | -multiprocessing module is used in Python 33 | 34 | Cons:- 35 | 36 | -Larger memory footprint 37 | Memory footprint refers to the amount of main memory that a program uses or references while running. 38 | 39 | ''' 40 | 41 | #--------------------------------------------------------------------------------------------------# 42 | # MultiThreading 43 | #--------------------------------------------------------------------------------------------------# 44 | ''' 45 | Pros:- 46 | 47 | -Multithreading is concurrent and is used for IO-bound tasks 48 | -Multithreading creates multiple threads of a single process to increase computing power. 49 | -Multiple threads of a single process are executed concurrently. 50 | -Shared memory - makes access to state from another context easier 51 | -Allows you to easily make responsive UIs 52 | -Lightweight - low memory footprint 53 | 54 | Cons:- 55 | 56 | -Complex debugging and testing processes 57 | -Increased potential for deadlock occurrence(When Memory Leak) 58 | ''' 59 | -------------------------------------------------------------------------------- /Threading/1.BasicOfThreading.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Threading 3 | 4 | Threading library in Python. Multiple threads live in the same process in the same space, 5 | each thread will do a specific task, have its own code, own stack memory, instruction pointer, and share heap memory. 6 | If a thread has a memory leak it can damage the other threads and parent process 7 | 8 | MultiThreading 9 | Multithreading is defined as the ability of a processor to execute multiple threads concurrently. 10 | 11 | In Python threading Module used to achieve Above Things 12 | 13 | The fact that Python on the CPython interpreter does not support true multi-core execution via multithreading. 14 | However, Python DOES have a Threading library. 15 | So what is the benefit of using the library if we (supposedly) cannot make use of multiple cores? 16 | 17 | Many programs, particularly those relating to network programming or data input/output (I/O) are often network-bound or I/O bound. 18 | This means that the Python interpreter is awaiting the result of a function call that is manipulating data from a "remote" source such as a network address or hard disk. 19 | Such access is far slower than reading from local memory or a CPU-cache. 20 | Hence, one means of speeding up such code if many data sources are being accessed is to generate a thread for each data item needing to be accessed. 21 | 22 | ''' 23 | #import threading 24 | import threading 25 | 26 | #function to multiply a single number with 10000 27 | def Func1(num): 28 | cal=num*10000 29 | print("\nI am From Func1 {}".format(cal)) 30 | 31 | #function to print given num*num 32 | def Func2(num): 33 | print("\nI am from Func2".format(num * num)) 34 | 35 | #main Program start from here 36 | if __name__ == "__main__": 37 | 38 | #Create A Thread 39 | #Syntax threading.Thread(target=,args=) 40 | t1 = threading.Thread(target=Func1, args=(10,)) 41 | t2=threading.Thread(target=Func2,args=(11,)) 42 | 43 | 44 | #After Thread creation we need to start that particular thread using threadobject.start() 45 | t1.start() 46 | t2.start() 47 | 48 | ''' 49 | join() method which allows one thread to wait until another thread completes its execution. 50 | If t is a Thread object whose thread is currently executing, 51 | then t.join() will make sure that t is terminated before the next instruction is executed by the program. 52 | ''' 53 | t1.join() 54 | t2.join() 55 | print("\nDone") 56 | -------------------------------------------------------------------------------- /Threading/2.GetReturnValueFromThread.py: -------------------------------------------------------------------------------- 1 | ##------------------------------------------------------------------------------------------------------ 2 | #Created By:Ravishankar Chavare 3 | #version:python 3.7 4 | #Date:10/04/2019 5 | #File_des:How to get Return value from running Thread 6 | ##------------------------------------------------------------------------------------------------------ 7 | 8 | 9 | ''' 10 | To get Return value From thread function we can use queue 11 | 12 | The queue module implements multi-producer, multi-consumer queues. 13 | It is especially useful in threaded programming when information must be exchanged safely between multiple threads 14 | ''' 15 | import queue #import queue 16 | from threading import Thread #import Threading 17 | 18 | #Simple Function retrun the value 19 | def foo(val): 20 | print('I am From Foo Function and val={0}'.format(val)) 21 | return val*val 22 | 23 | #Create a Blank Queue for adding thread 24 | que = queue.Queue() 25 | 26 | #Create a anonymous function using lambda that will call foo() and and add that calling method to queue 27 | #for further processing 28 | fn=lambda q,arg1:q.put(foo(arg1)) 29 | 30 | #Now Normal Create A Thread using Threading.Thread(target=anomous function,args=(que,elements)) 31 | t = Thread(target=fn, args=(que, 5)) 32 | 33 | #Start That Thread 34 | t.start() 35 | 36 | #WAit Untill to Thread Execution 37 | t.join() 38 | 39 | #Now Main Part to get the result from foo Function call que.get() to get the return value 40 | result = que.get() 41 | 42 | #Print The Result Which is stored using que.get() 43 | print(result) 44 | -------------------------------------------------------------------------------- /UsefulStuffs/Email/1.SimpleEmailSend.py: -------------------------------------------------------------------------------- 1 | #To send Email From Python file you need to import smtplib 2 | import smtplib 3 | 4 | #then create connection objects 5 | conn=smtplib.SMTP('smtp.gmail.com',587) 6 | #here SMTP() function takes two input 7 | #1.smtp.gmail.com--this is email address of gmail you can findout other adress on google 8 | #2.587--this is port number of smtp.gmail.com 9 | 10 | 11 | #now say hello to smtp.gmail.com server 12 | conn.ehlo() 13 | 14 | 15 | #To send email using encryption then 16 | conn.starttls() 17 | 18 | #now login your gmail account using login() 19 | conn.login('username','password') 20 | 21 | #Now send email using sendmail(fromadress,toadress,message) 22 | conn.sendmail('fromaddress','toaddress','message') 23 | #this will send a email to toaddress with blank subjects 24 | 25 | #send email with subject 26 | conn.sendmail('fromaddress','toaddress','Sub :subject \n\n message here') 27 | 28 | 29 | #After sending email we need to close connection object 30 | conn.quit() -------------------------------------------------------------------------------- /UsefulStuffs/Email/2.AdvancedEmailSender.py: -------------------------------------------------------------------------------- 1 | import webbrowser,smtplib 2 | import getpass #this module help to user password witout echo anything this work only in shell (when you run your program from command prompt or direct shell) 3 | def get_Email(): 4 | 5 | services=['yahoo','gmail','outlook','hotmail'] 6 | while True: 7 | mail_id=input('Email : ') 8 | if '@' in mail_id and '.com' in mail_id: 9 | symbol_pos=mail_id.find('@') 10 | dotcom_pos=mail_id.find('.com') 11 | sp=mail_id[symbol_pos+1:dotcom_pos] 12 | if sp in services: 13 | return mail_id,sp 14 | break 15 | else: 16 | print('We dont provide service for '+ sp) 17 | print('We provide services for gmail, yahoo, outlook, hotmail') 18 | print('Try Again...') 19 | continue 20 | else: 21 | print('Invalid email Try again :') 22 | continue 23 | 24 | def set_SMTP_Domain(sp): 25 | if sp=='gmail': 26 | return 'smtp.gmail.com' 27 | elif sp=='yahoo': 28 | return 'smtp.mail.yahoo.com' 29 | elif sp=='outlook' or sp=='hotmail': 30 | return 'smtp-mail.outlook.com' 31 | print('Sending Email Program') 32 | user_mail,sp=get_Email() 33 | password=getpass.getpass("Password: ") 34 | while True: 35 | try: 36 | smtp_domain=set_SMTP_Domain(sp) 37 | conn=smtplib.SMTP(smtp_domain,587) 38 | conn.ehlo() 39 | conn.starttls() 40 | conn.login(user_mail,password) 41 | except: 42 | if sp=='gmail': 43 | print('Login Unsucessfull there may be possible two reason ') 44 | print('1.You typed wrong username or password') 45 | print('2.allow lesssecure apps in google') 46 | print('want to lesssecureapps allow in gmail yes or no') 47 | op=input() 48 | if(op=='yes'): 49 | webbrowser.open('https://myaccount.google.com/lesssecureapps') 50 | else: 51 | print('https://myaccount.google.com/lesssecureapps go here and mannually and sllow it') 52 | print('please retype username and password again') 53 | user_mail,sp=get_Email() 54 | password=getpass.getpass("Password: ") 55 | continue 56 | else: 57 | print('login unsucessfull') 58 | print('please retype username and password again') 59 | user_mail,sp=get_Email() 60 | password=getpass.getpass("Password: ") 61 | continue 62 | else: 63 | print('login susssessfull ') 64 | break 65 | print('Enter Receiver Email:') 66 | receiver_mail,sp=get_Email() 67 | subject=input('Subject : ') 68 | message=input('Message : ') 69 | conn.sendmail(user_mail,receiver_mail,'Subject : '+str(subject) + '\n\n' + str(message)) 70 | print('Email Sent Successfully') 71 | conn.quit() 72 | -------------------------------------------------------------------------------- /UsefulStuffs/SystemInformer/NetworkInfo.py: -------------------------------------------------------------------------------- 1 | import socket 2 | from collections import OrderedDict 3 | from uuid import getnode as get_mac 4 | class NetworkInfo: 5 | allid={} 6 | allid=OrderedDict() 7 | def networkinfo(self): 8 | self.mac = get_mac() 9 | self.macid=':'.join(("%012X" % self.mac)[i:i+2] for i in range(0, 12, 2)) 10 | self.ip=socket.gethostbyname(socket.gethostname()) 11 | self.allid['Ipv4']=self.ip 12 | self.allid['Mac_Address']=self.macid 13 | return self.allid 14 | 15 | 16 | -------------------------------------------------------------------------------- /UsefulStuffs/SystemInformer/OsInfo.py: -------------------------------------------------------------------------------- 1 | import os 2 | import platform 3 | from collections import OrderedDict 4 | 5 | class OsInfo: 6 | osinfo={} 7 | osinfo=OrderedDict() 8 | def Osinfo(self): 9 | self.osinfo['Os_name']=platform.system()#os name 10 | self.osinfo['Os_full_name']='{} {}'.format(platform.system(),platform.release()) 11 | self.osinfo['Network_name']=platform.node()# computer network name 12 | self.osinfo['Release_name']= platform.release()#Release Name 13 | self.osinfo['Version']= platform.version() 14 | self.osinfo['Machine']=platform.machine()#Print the machine hardware name 15 | self.osinfo['Processor']=platform.processor()#Print the processor type 16 | return self.osinfo 17 | -------------------------------------------------------------------------------- /UsefulStuffs/SystemInformer/Readme.txt: -------------------------------------------------------------------------------- 1 | Download this to your local system 2 | install requirements using pip 3 | >pip install -r requirements.txt 4 | 5 | 6 | After Installing requirements run the main.py file 7 | -------------------------------------------------------------------------------- /UsefulStuffs/SystemInformer/SoftwareInfo.py: -------------------------------------------------------------------------------- 1 | import win32com.client 2 | class SoftwareInfo: 3 | def softwareinfo(self): 4 | 5 | strComputer = "." 6 | softs={} 7 | objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") 8 | objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2") 9 | colItems = objSWbemServices.ExecQuery("Select * from Win32_Product") 10 | softwares=[] 11 | for objItem in colItems: 12 | softwares.append(objItem.Caption) 13 | if(len(softwares)==0): 14 | return False 15 | else: 16 | softs['count']=len(softwares) 17 | softs['lists']=softwares 18 | return softs 19 | -------------------------------------------------------------------------------- /UsefulStuffs/SystemInformer/SystemDrives.py: -------------------------------------------------------------------------------- 1 | import re 2 | import os 3 | import string 4 | class SystemDrives: 5 | drives=[] 6 | def GetDrives(self): 7 | for d in string.ascii_uppercase: 8 | if os.path.exists('{}:'.format(d)): 9 | self.drives.append(d) 10 | if(len(self.drives)==0): 11 | return False 12 | else: 13 | return self.drives 14 | -------------------------------------------------------------------------------- /UsefulStuffs/SystemInformer/main.py: -------------------------------------------------------------------------------- 1 | import SystemDrives as sd 2 | import OsInfo as oi 3 | import NetworkInfo as ni 4 | import SoftwareInfo as si 5 | 6 | print('{:*^65s}'.format('Operating System Information')) 7 | o1=oi.OsInfo() 8 | for i in o1.Osinfo().items(): 9 | print('{}:{}'.format(i[0],i[1])) 10 | 11 | print('\n\n{:*^65s}'.format('Drives On System')) 12 | s1=sd.SystemDrives() 13 | for s in s1.GetDrives(): 14 | print('{}'.format(s)) 15 | 16 | print('\n\n{:*^65s}'.format('Network Information')) 17 | n1=ni.NetworkInfo() 18 | for i in n1.networkinfo().items(): 19 | print('{}:{}'.format(i[0],i[1])) 20 | 21 | 22 | print('\n\n{:*^65s}'.format('Installed Software')) 23 | s1=si.SoftwareInfo() 24 | i=1 25 | print('{} Softwares installed'.format(s1.softwareinfo()['count'])) 26 | for s in s1.softwareinfo()['lists']: 27 | print(s) 28 | 29 | 30 | -------------------------------------------------------------------------------- /UsefulStuffs/SystemInformer/requirements.txt: -------------------------------------------------------------------------------- 1 | pypiwin32==223 2 | pywin32==223 3 | -------------------------------------------------------------------------------- /UserInput/1.UserInput.py: -------------------------------------------------------------------------------- 1 | #For Getting user input we used keyword input() function 2 | #for example if you want to ask user name then 3 | #in python 2. version we need to get number using input() and strings using raw_input() 4 | #Now in Python 3. version input() can handle string and number both 5 | username=input('Enter user name:') #this will ask user on terminal on same line 6 | 7 | print('Enter Username:') 8 | uname=input() #this will ask input on new line 9 | 10 | 11 | 12 | print(username) 13 | print(uname) 14 | -------------------------------------------------------------------------------- /UserInput/2.UserInputExamples.py: -------------------------------------------------------------------------------- 1 | #Create a program user can enter any number then return the addition of that number 2 | #example user enter 1234 then addition is 1+2+3+4=10 3 | x=input('Enter the Number:') 4 | print(x) 5 | length=len(x) 6 | result=0 7 | i=0 8 | 9 | while(i