diff --git a/README.md b/README.md index 32a5375..2265755 100644 --- a/README.md +++ b/README.md @@ -2,57 +2,57 @@ # Table of Content - -* [Main](#main) -* [Basic and necessary commands needed to execute a well-defined python code at the command line.](#basic-and-necessary-commands-needed-to-execute-a-well-defined-python-code-at-the-command-line) - * [Opening a python shell.](#opening-a-python-shell) - * [Installing a package](#installing-a-package) - * [Running a python script](#running-a-python-script) - * [Calculating the time of execution](#calculating-the-time-of-execution) - * [Importing a py script](#importing-a-py-script) -* [Getting started with the language](#getting-started-with-the-language) - * [Basic I/O](#basic-io) - * [Variables and Constants](#variables-and-constants) - * [Conditional Statements](#conditional-statements) - * [Iterative statements](#iterative-statements) - * [String formatting](#string-formatting) -* [Function](#function) - * [Function Call](#function-call) - * [Function as Object](#function-as-object) - * [Nested Function](#nested-function) - * [Lambda](#lambda) -* [Data Structures](#data-structures) - * [Lists](#lists) - * [Dictionaries](#dictionaries) - * [Tuple](#tuple) - * [Changing Tuple Values](#changing-tuple-values) - * [Creating tuple with one item](#creating-tuple-with-one-item) - * [Deleting a tuple](#deleting-a-tuple) -* [Pandas](#pandas) -* [NLTK](#nltk) -* [Errors and Exceptions](#errors-and-exceptions) - * [Exceptions](#exceptions) -* [Python Snippets](#python-snippets) - * [Anagrams](#anagrams) - * [Memory](#memory) - * [Print a string N times](#print-a-string-n-times) - * [Chunk](#chunk) - * [Get vowels](#get-vowels) - * [Length of Last Word in a string](#length-of-last-word-in-a-string) - * [Valid Palindrome](#valid-palindrome) - * [Check Lowercase](#check-lowercase) - * [Count Negatives in a sorted Matrix](#count-negatives-in-a-sorted-matrix) - * [Write to file](#write-to-file) - * [Median of given array](#median-of-given-array) - * [Even or Odd](#even-or-odd) - * [Palindrome](#palindrome) +- [Main](#main) +- [Basic and necessary commands needed to execute a well-defined python code at the command line.](#basic-and-necessary-commands-needed-to-execute-a-well-defined-python-code-at-the-command-line) + - [Opening a python shell.](#opening-a-python-shell) + - [Installing a package](#installing-a-package) + - [Running a python script](#running-a-python-script) + - [Calculating the time of execution](#calculating-the-time-of-execution) + - [Importing a py script](#importing-a-py-script) +- [Getting started with the language](#getting-started-with-the-language) + - [Basic I/O](#basic-io) + - [Variables and Constants](#variables-and-constants) + - [Conditional Statements](#conditional-statements) + - [Iterative statements](#iterative-statements) + - [String formatting](#string-formatting) +- [Function](#function) + - [Function Call](#function-call) + - [Function as Object](#function-as-object) + - [Nested Function](#nested-function) + - [Lambda](#lambda) +- [Data Structures](#data-structures) + - [Lists](#lists) + - [Dictionaries](#dictionaries) + - [Tuple](#tuple) + - [Changing Tuple Values](#changing-tuple-values) + - [Creating tuple with one item](#creating-tuple-with-one-item) + - [Deleting a tuple](#deleting-a-tuple) +- [Pandas](#pandas) + - [Data Structures in Pandas](#data-structures-in-pandas) +- [NLTK](#nltk) +- [Errors and Exceptions](#errors-and-exceptions) + - [Exceptions](#exceptions) +- [Python Snippets](#python-snippets) + - [Anagrams](#anagrams) + - [Memory](#memory) + - [Print a string N times](#print-a-string-n-times) + - [Chunk](#chunk) + - [Get vowels](#get-vowels) + - [Length of Last Word in a string](#length-of-last-word-in-a-string) + - [Valid Palindrome](#valid-palindrome) + - [Check Lowercase](#check-lowercase) + - [Count Negatives in a sorted Matrix](#count-negatives-in-a-sorted-matrix) + - [Write to file](#write-to-file) + - [Median of given array](#median-of-given-array) + - [Even or Odd](#even-or-odd) + - [Palindrome](#palindrome) - ## Main + ```python if __name__ == '__main__': # If file is not imported, this will be executed main() @@ -61,26 +61,31 @@ if __name__ == '__main__': # If file is not imported, this will be executed ## Basic and necessary commands needed to execute a well-defined python code at the command line. ### Opening a python shell. + ```python -$ python3 +$ python3 ``` ### Installing a package + ```python -$ pip3 install +$ pip3 install ``` ### Running a python script + ```python -$ python3 .py +$ python3 .py ``` ### Calculating the time of execution -```python -$ time python3 .py + +```python +$ time python3 .py ``` ### Importing a py script + ```python import ``` @@ -88,30 +93,38 @@ import ## Getting started with the language ### Basic I/O -+ Input + +- Input + ```python input("Input: ") ``` -+ Output -Python automatically points the cursor to a new line. -We need not specify explicitly. + +- Output + Python automatically points the cursor to a new line. + We need not specify explicitly. + ```python print("Output") ``` ### Variables and Constants -In python, we need not specify the datatype of a variable. + +In python, we need not specify the datatype of a variable. The interpreter interprets the value and assigns a suitabe datatype for that. + ```python number = 0 org = "GitHub" ``` ### Conditional Statements + In python, we do not write a block of code in a pair of paranthesis. We write it after `:` followed by an indentation in the next line. The conditional statements include `if`, `if-else`, `nested if` and so on... + ```python x,y = 0,1 if x < y: @@ -119,21 +132,25 @@ if x < y: else: print("x is not less than y") ``` + Note that the colon (:) following is required. Similarly, the `nested if` also works. - ### Iterative statements -As other programming languages, we have -+ `for loop` +As other programming languages, we have + +- `for loop` + ```python for i in range(5): print(i) ``` + The `range` function starts off with 0 till the number(excluded). -+ `while loop` +- `while loop` + ```python i=0 while(i < 10): @@ -142,10 +159,11 @@ while(i < 10): ``` ### String formatting + There are a few ways to format a string in Python. -+ Using the `%` operator -Strings can be formatted using the % operator: +- Using the `%` operator + Strings can be formatted using the % operator: ```python >>> foo = 'world' @@ -170,7 +188,7 @@ You can also do variable subsitutions with a dictionary: 'I am Mike and I am from Canada' ``` -+ `.format()` +- `.format()` Introduced in Python 3, but is available in Python 2.7+ @@ -186,9 +204,9 @@ Similar to the above, subsitutions can be referred by name: 'Hi Bob, your total is $5.5' ``` -+ f-Strings +- f-Strings -Available in Python 3.6+. Works similar to the above, but is more powerful as arbitrary Python expressions can be embedded: +Available in Python 3.6+. Works similar to the above, but is more powerful as arbitrary Python expressions can be embedded: ```python >>> a = 5 @@ -198,9 +216,11 @@ Available in Python 3.6+. Works similar to the above, but is more powerful as ar ``` ## Function + Function is a block of code which runs when it is called. Functions are declared using the `def` keyword. Function name must be a valid identifier. Function arguments can be literal values, variables (valid identifiers), and expressions. + ```python def sum(a, b) : return a + b @@ -214,7 +234,9 @@ def getPerson(name, age) : ``` ### Function Call + Functions can be called by passing the arguments according to the declaration. + ```python a = 20 b = 50 @@ -231,11 +253,13 @@ print( "Person - {}" . format( p ) ) # Person - {'name': 'Joe', 'age': 75} ``` ### Function as Object + All data in a Python is represented by objects. There’s nothing particularly special about functions. They’re also just objects. + ```python def yell(text): # Define function yell return text.upper() + '!' - + >>> bark = yell # Declare an object "bark" that contains the function "yell" >>> bark('woof') # You could now execute the "yell" function object by calling bark @@ -243,26 +267,32 @@ def yell(text): # Define function yell ``` ### Nested Function + Functions can be defined inside other functions. These are often called nested functions or inner functions. + ```python def speak(text): # Define function speak def wisper(t): # Function wisper does not exist outside speak return t.lower() + '...' return wisper(text) - - + + >>> speak('Hello, World') 'hello, world...' ``` ## Lambda + The lambda keyword in Python provides a shortcut for declaring small anonymous functions. + ```python >>> add = lambda x, y: x + y >>> add(5, 3) 8 ``` + You could declare the same add function with the def keyword, but it would be slightly more verbose: + ```python def add(x, y): return x + y @@ -273,6 +303,7 @@ def add(x, y): ## Data Structures ### Lists + ```python # These are all inplace operations returns a None value @@ -292,27 +323,33 @@ def add(x, y): .index() # Returns the index of the given element .count() # Returns the number of occurrences of the element ``` + ### Dictionaries + key-value pairs. + ```python = {'Google':100, 'Facebook':80, 'Apple':90} ['Amazon'] = 85 # Adding a key along with the value -# Accessing the dictionary +# Accessing the dictionary for key in : print("{key} -> {x}".format(key=key, x=[key])) - + .keys() # Print all the keys .values() # Print all the values len() # Find the length of the dictionary .pop() # Removes the item with the specified key name .copy() # Make a copy of a dictionary ``` + A dictionary can also contain many dictionaries, this is called nested dictionaries. ### Tuple + A tuple is a collection which is ordered, indexed and unchangeable. In Python tuples are written with round brackets. + ```python this_tuple = ('books', 'pen', 'paper') # Defined a tuple @@ -321,9 +358,11 @@ print(this_tuple[2]) # paper ``` #### Changing Tuple Values + Tuples are immutable, which means they cant to changed once they are created. If a value inside tuple needs to be changed, the tuple must be converted to a list. Newly created list can be converted back to tuple after updating changes. + ```python desk_tuple = ("pen stand", "plant", "marker") desk_list = list(desk_tuple) @@ -334,10 +373,12 @@ print(desk_tuple[2]) # highlighter ``` #### Creating tuple with one item + To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple. + ```python this_tuple = ("Python",) -print(type(this_tuple)) # tuple +print(type(this_tuple)) # tuple # NOT a tuple this_tuple = ("Python") @@ -345,17 +386,22 @@ print(type(this_tuple)) # str ``` #### Deleting a tuple + Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely: + ```python -this_tuple = ('books', 'pen', 'paper') +this_tuple = ('books', 'pen', 'paper') del this_tuple print(this_tuple) # ERROR: this_tuple is not defined ## Third party libraries ``` + ## Pandas + ```shell $ sudo pip3 install pandas # Installing pandas module in Ubuntu ``` + ```python import pandas as pd @@ -364,10 +410,46 @@ import pandas as pd .info() # Gives some information like, row and column datatypes, non-null count, and memory usage .describe() # Provides some descriptive statistics about the numerical rows in the dataframe ``` + +### Data Structures in Pandas + +In Pandas, total of three data structures are used + +- Series +- DataFrame +- Panel + +```python +#Series +sr = pd.Series([100, 200, 300, 400], +index=["red", "green", "yello", "black"]) +print(sr) +print(sr.values) +print(sr.index) + +#A series class has a structure that allows you to give values in one-dimensional arrays an index that corresponds to each value. +``` + +```python +#DataFrame +values = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +index = ['one', 'two', 'three'] +columns = ['A', 'B', 'C'] + +df = pd.DataFrame(values, index=index, columns=columns) +print(df) +print(df.index) +print(df.columns) +print(df.values) +#DataFrame passes a two-dimensional list as a parameter. Compared to a series, a data frame is added up to columns, consisting of columns, indexes, and values. +``` + ## NLTK + ```shell $ sudo pip3 install nltk # Installing nltk module in Ubuntu ``` + ```python import nltk @@ -377,23 +459,25 @@ nltk.download('averaged_perceptron_tagger') ``` ## Errors and Exceptions + Program stops working on error Python raises exceptions when it encounter error. To avoid this, `try-catch` blocks are used. ### Exceptions + No syntax errors found, program starts execution. Errors detected during execution are called exceptions. Use try: except: finally: to catch and handle the exceptions. Use try: except: finally: to avoid program termination on exceptions. Use try: except: else: instead of try: except: finally: for alternate flows. -Multiple except can be use to catch the exceptions. +Multiple except can be use to catch the exceptions. ```python a = 10 * (1/0) # Throws division by zero exception and terminate the program # Traceback (most recent call last): - File "", line 1, in + File "", line 1, in a = 10 * (1/0) # ZeroDivisionError: division by zero @@ -427,50 +511,66 @@ else: Caught divide by zero - while getting a Execute on error - b must be non-zero value Execute Always - normal and exceptional flow -``` +``` ## Python Snippets ### Anagrams + An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + ```python from collections import Counter def anagram(first, second): return Counter(first) == Counter(second) anagram("abcd3", "3acdb") # True ``` + ### Memory + This snippet can be used to check the memory usage of an object. + ```python -import sys +import sys -variable = 30 +variable = 30 print(sys.getsizeof(variable)) # 24 ``` + ### Print a string N times + This snippet can be used to print a string n times without having to use loops to do it. + ```python n = 2 s ="Programming" print(s * n) # ProgrammingProgramming ``` + ### Chunk + This method chunks a list into smaller lists of a specified size. + ```python def chunk(list, size): return [list[i:i+size] for i in range(0,len(list), size)] ``` + ### Get vowels + This method gets vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) found in a string. + ```python def get_vowels(string): - return [each for each in string if each in 'aeiou'] + return [each for each in string if each in 'aeiou'] get_vowels('foobar') # ['o', 'o', 'a'] get_vowels('gym') # [] ``` ### Length of Last Word in a string + This method gets the length of last word in a given string. + ```python def lengthOfLastWord(self, s: str) -> int: if(s.split()): @@ -479,15 +579,21 @@ def lengthOfLastWord(self, s: str) -> int: return len(last) return 0 ``` + ### Valid Palindrome + This method returns a bool value specifying whether a string is palindromic or not. + ```python def isPalindrome(self, s: str) -> bool: s = [ x.lower() for x in s if x.isalnum() ] return s == s[::-1] ``` + ### Check Lowercase + This method checks if a string is in lower case or not. + ```python def toLowerCase(self, str): """ @@ -496,8 +602,11 @@ def toLowerCase(self, str): """ return str.lower() ``` + ### Count Negatives in a sorted Matrix + This method returns the count of negative numbers in a sorted matrix. + ```python def countNegatives(self, grid: List[List[int]]) -> int: count = 0 @@ -509,7 +618,9 @@ def countNegatives(self, grid: List[List[int]]) -> int: ``` ### Write to file -This method takes in the ``name of file`` and ``content`` then write the content into the file. If the file doesn't exist then it creates the file. + +This method takes in the `name of file` and `content` then write the content into the file. If the file doesn't exist then it creates the file. + ```python def write_to_file(filename, content): try: @@ -520,25 +631,34 @@ def write_to_file(filename, content): print("Failed to write to file with error: ") print(e) ``` + ### Median of given array + This method returns the median of the given list/array as an output. + ```python import statistics def median(arr): print(statistics.median(arr)) ``` + ### Even or Odd + This function determines the given number is even or odd. + ```python def find_Evenodd(num): - + if(num%2==0): print(num," Is an even") else: print(num," is an odd") ``` + ### Palindrome + This function returns "yes" if given string is a palindrome, else "no". Palindrome is a string whose reverse is the string itself. + ```python def isPalindrome(s): if (s == s[::-1]):