Sunday, March 5, 2017

Python Cheat sheet

Recently I started to learn Python and found it very interesting and easy as well. I stated to learn python from level 0 and now I learned core Python in 10 days. Studied mostly from, and is official website of Python. Here I am sharing my digital Cheat Sheet on python which I have studied till now. Still I am continuing this. I will share the further notes soon.

Please provide comments and queries if you have.
---------------------------------------------- Python Notes ---------------------------------------------------------
Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum in the Netherlands as a successor of a language called ABC.
According to the principal author (Guido van Rossum), he chose the name "Python" because he is a big fan of the British comedy movie - 'Monty Python's Flying Circus'.

Salient features of Python:-
*  Python is a case sensitive programming language.
*  It supports functional and structured programming methods as well as OOP.
*  It can be used as a scripting language or can be compiled to byte-code for building large applications.
*  It provides very high-level dynamic data types and supports dynamic type checking.
*  It supports automatic garbage collection.
*  It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Type Conversion:-
str(x) − Converts object x to a string representation.
float(x) − Converts x to a floating-point number.
tuple(s) − Converts s to a tuple.
list(s) − Converts s to a list.
set(s) − Converts s to a set.
dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples.
chr(x) − Converts an integer to a character.
hex(x) − Converts an integer to a hexadecimal string.
oct(x) − Converts an integer to an octal string.
round(x) - Round a float number to integer either to base or to floor according to float value.

isalnum() − Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
isdigit() − Returns true if string contains only digits and false otherwise.
islower() − Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
isupper() − Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
lower() − Converts all uppercase letters in string to lowercase.
upper() − Converts all lowercase letters in string to uppercase.
swapcase() − Inverts case for all letters in string.
capitalize() − Capitalizes first letter of string.
title() − Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.
istitle() − Returns true if string is properly "titlecased" and false otherwise.
isspace() − Returns true if string contains only whitespace characters and false otherwise.
lstrip() − Removes all leading whitespace in string.
rstrip() - Removes all the whitespace after the string.
strip([chars]) − Performs both lstrip() and rstrip() on string.
len(string) − Returns the length of the string.
random() − returns a random float r, such that 0 is less than or equal to r and r is less than 1.
str.rjust(width,'fillchar') -- print the string right justified.
str.rjust(width) -- we can use it simply like this.  -- center justified
str.ljust() -- left justified

cmp(list1, list2) − Compares elements of both lists.
len(list) − Gives the total length of the list.
max(list) − Returns item from the list with max value. --all elements must be of same data type
min(list) − Returns item from the list with min value.  -- all elements must be of same data type
list.index(obj) − Returns the lowest index in list that obj appears.
list.insert(index, obj) − Inserts object obj into list at offset index.
list.append(obj) - Append obj in the list.
list.remove(obj) − Removes object obj from list.
list.reverse() − Reverses objects of list in place i.e. first index value goes to last and last to first.
example:- list=['abc', 454, 2.23, 'john', 70.2]  then output of list.reverse() is [70.2, 'john', 2.23, 454, 'abc']
list.sort([func]) − Sorts objects of list, use compare func if given.
list.pop(obj=list[-1]) − Removes and returns last object or obj from list.

**help(print) -- it displays help regarding parameter passed
**dir(<argument>) -- it displays help, what are function we can use with the argument

What is IDLE?
IDE - Integrated Development Environment.
IDLE - is IDE for Python.

We can use commands like -- 3+4,8-4,6/2,(2*4)+3/2 in python shell.
printing string in- >>> "Hello" or 'Hello' , x='dog'
Python remembers all the variables until is not restarted or deleted.
delete variable command: del <variable name/s>

Variable naming convention is same as C/C++. It contains letters,numbers and underscore.
Reserved identifiers in Python-

Variable tyes in Python
1. integer(int) (All integer type is long int)
2. float
3. Comples
4. string(str)
5. boolean(bool)
6. list
7. Tuple
8. Dictionaries
str = 'Hello World!'

print (str)               # Prints complete stringprint -- Hello World!
(str[0])                  # Prints first character of the stringprint -- H
(str[2:5])               # Prints characters starting from 3rd to 5th print -- llo
(str[2:])                 # Prints string starting from 3rd characterprint -- llo World!
(str * 2)                 # Prints string two timesprint -- Hello World!Hello World!
(str + "TEST")        # Prints concatenated string -- Hello World!TEST

The main differences between lists and tuples are −
* Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.
Example :- list1= ['abcd', 786, 2.23, 'john', 70.2]  ::: tuple1=('abcd', 786, 2.23, 'john', 70.2)

Dictionary defined in curly braces while value can be assigned and accessed by square braces [] .
dict1 = {'name': 'john','code':6734, 'dept': 'sales'}
dict1['one'] = 'Hello'
dict1[2] = 10

e.g. -
print (dict1['one'])              # Prints value for 'one' key
print (dict1[2])                   # Prints value for 2 key
print (dict1)                  # Prints complete dictionary
print (dict1.keys())        # Prints all the keys
print (dict1.values())     # Prints all the values

Operator types in Python:-
1. mathematical   2. Relational   3. Logical    4. Bitwise
5. Membership (in,not in)  e.g. 2 in [3,2,6]  Result:: True
6. Identity  (is,is not)   e.g. a is b -- Result will be True or False

Arithmatic operator othe then C++ --
//  -- Floor division >>>9//2  will give o/p 4 not 4.5 but 9/2 -> 4.5

** Exponent e.g. x**y means x to the power y.

Operator Precedence - **>~>unary operator(-,+)>*>/>%>//
print(type(x))   --- this gives the type of the variable x
<class 'int'>

<class 'float'>

-------------- bool ------------------------

x=False  -- not false or FALSE

y=True  --  not true or TRUE

-------------- input/print -----------------

Get input from keyboard --- input()

input function always returns string irrespective of input provided.

age = int(input())  -- we neet to convert string into int. Input always return the data type string.
name=input("What is your name:")  -- It prints the string (What is your name:") and store the value entered by user in the variable name.


------------- data type conversion ----------

num=input()      --- Here num is string.

number=int(num)  --- Here num is converted to integer from string type.
---------- BIFs - Built in Functions --------------
isinstance() - it returns type of the variable. E.g.- isinstance(3,int) -> True
------------------ List -----------------------
How to create list-




There are two ways to access the elements of list-

1. Positive Indexing

     Index increases from 0 to n

2. Negative Indexing

     It goes from right to left. Last elemet have index -1, second lost having index of -2 and so on.
     e.g. - my_list[-1]  -- it will print True

Python have two Modules-
  1. Standard Module -- it comes installed with python. example - math module
  2. External Module -- We need to install this from external.

>>> import math
>>> math.sqrt(9)

Which of the following statements would generate the string 'fun'?
print('Python is fun'[-3:])
print('Python is fun'[-3:-1])
print('Python is fun'[-3:0]) -- this prints nothing.

--------------- If condition and Inline if --------------
if x>=0:
     print("Positive number")
     print("Negative number")

inline if condition:-
print("Positive number" if x>=0 else "Negative Number")  --above 4 line code is written in one line.

if x>10:
elif x==10;

-------------- looping condition --------------------
1. for loop
lst = ["","",""]
for mail in lst:
     if "gmail" in mail:
for x in range(1,10):

for i,j in zip(lst1,lst2):

2. while loop
password = ''
while password != 'python123':
    password = input("Enter password: ")
    if password == 'python123':
        print("You are logged in!")
        print("Please try again.")

----------- File Handling --------------------
open() returns a file object, and is most commonly used with two arguments: open(filename, mode).

Different modes to open a text file-
r = read only, File pointer is placed at the beginning of the file.         
r+ = read + over-write, file pointer is placed at the beginning of the file.       
w = write only,  If the file does not exists it creates a new file.    
w+ = read + write     It deletes the file content when opened and then used to write on the file.
a = append,    
a+=read + append (Pointer is at last of file)
b = binary mode -- read a file and prints 'size' number of starting character in the file. --  will read entire file in one shot and will will return an empty string ('').
f.readline() -- it reads a single line from the file. it adds '\n' in the end of string and if the end of the file is reached the it returns a blank line.
f.write(string) -- writes the contents of string to the file, returning the number of characters written.
f.tell() -- returns an integer giving the file object’s current position., from_what) -- takes the file current position to offset in reference to from_what position. If from_what position is not provided then it takes default 0. --

with statement
when file is opened with 'with' statement, the file.close() part is taken care by the with statement itself. It is always best practice to use the with statement while opening the file.
with open('example.txt','a+') as file:
     file.write("Hello Mukesh")

We need not to write the file.close(), it is taken care by the with statement itself.

Writing your own ATOI() function in C++

Checkout the below program written to convert numbers in string to integer. In C++ there is a function atoi() to convert number in character to integer. Here I am writing my own function to to do this.

//atoi() function creation.
using namespace std;
bool isNumeric(char x)
    return(('0'<= x && x <='9')?true:false);    
int myAtoi(char* str)
    int neg = 1, res = 0, i = 0;
    if(str[0] == '-'){    
        {    res = res*10 + str[i]-'0'; i++; }

int main()
    char str[]="-90jyh8";
    int val = myAtoi(str);
    return 1;