Monday, December 28, 2015

['Python Cheat Sheet' , 'Quick Reference', 'Note to Myself', 1]

python cheat sheet 
==================
Definitions : 
Empty String : guca='' or guca=""
empty list   : guca = []
empty dict   : guca = {}
empty tuple  : guca = ()
empty set    : guca = set ()




1. Convert int to list of string 
num=12345
arr = list(str(num))
2.Convert list of string to list of ints 
arr = list(map(int,arr))
3.Convert list to set 
    l1 = f.splitlines()
    s1 = set(list(map(int,l1)))
    another example: 
    first_list = [1,2,3,4]
    my_set=set(first_list)
4. Convert set to list 
        first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)

5. random number generation 
import random 
random.randint(1, 10)  # Integer from 1 to 10, endpoints included
random.randrange(0, 101, 2)  # Even integer from 0 to 100

items = [1, 2, 3, 4, 5, 6, 7]
random.shuffle(items)   # shuffle the items in the list
random.sample([1, 2, 3, 4, 5],  3)  # Choose 3 elements
6. Split, reverse and join 
>>> buf="cisco is a good place"
>>> list_buf = buf.split()
>>> print(list_buf)
['cisco', 'is', 'a', 'good', 'place']
>>> list_buf.reverse()
>>> print(list_buf)
['place', 'good', 'a', 'is', 'cisco']
>>> op=" ".join(list_buf)
>>> print(op)
place good a is cisco
>>>

7.List creation with list expression 
>>> my_list = [x**2 for x in range(10)]  # list of square of the num in given range
>>> my_list
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 

8. list comprehension : 
The idea of a list comprehension is to make code more compact to            accomplish tasks involving lists.
Converting year_of_birth to age 
years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]
    ages = [2015 - year for year in years_of_birth]

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

s3 = set(a).intersection(set(b))
print("Using the sets" ,s3)

l1 = [x for x in a for y in b if x==y]
print("using list comprehension", l1)

list_comprehension_output = [ ]

Another Note : 
Here is the list filtering syntax:
[mapping−expression for element in source−list if filter−expression]

This is an extension of the list comprehensions that you know and love. The first two thirds are the same; the last part,
starting with the if, is the filter expression. A filter expression can be any expression that evaluates true or false
(which in Python can be almost anything). Any element for which the filter expression evaluates true will be included
in the mapping. All other elements are ignored, so they are never put through the mapping expression and are not
included in the output list.



9. Adding the element to the dictionary 
>>> my_dict={'xyz': 100, 'def': 23, 'zxt': 400}
>>> my_dict['bcn']=400
>>> my_dict.update({'abc':200})
>>> my_dict
{'bcn': 400, 'xyz': 100, 'def': 23, 'zxt': 400, 'abc': 200}

10. Sorting the dict based on items

import operator
my_dict={'abc':32, 'def':23, 'xyz':100}
sorted_d = sorted(my_dict.items(), key=operator.itemgetter(1))
sorted_d = sorted(my_dict.items(),
 key=operator.itemgetter(1),
 reverse=True) 

11. Adding or merging two dictionary

def add_dict(l):
final_dict = {}
for dic in l:
final_dict.update(dic)
return final_dict

d1={1:10,2:20}
d2={3:30, 4:40}
d3 ={5:50, 6:60}
l1 =[d1,d2,d3]

new_dict = add_dict(l1)
print(new_dict)

12. Where does the python looks for it's imports ?
By default the current directory and if it is not found, it looks at below path
>>> import sys
>>> sys.path
Python will look through these directories (in this order) for a .py file matching the module name, being imported.

13. Negative indexing in python:
If the negative index is confusing to you, 
think of it this way: guca[−n] == guca[len(guca) − n]. 
So in this list, guca[−3] == guca[5 − 3] == guca[2].

14. Lists - The working horses of python:
Declare the emplty list : guca = []
Declare the list with some elements : guca =[1,2,3, "cisco", "hello"]
Add element to the list = guca.append(10)
Add element at a position : guca.add(3, "new")
concatinate two lists : guca.extend(["another", "list"])

15. The difference between append and extend
    >>> guca=[1,2,3]
>>> guca
[1, 2, 3]
>>> guca.append([4,5,6])
>>> guca
[1, 2, 3, [4, 5, 6]]  # Note this becomes list within a list
>>> #extend now
>>> guca=[1,2,3]
>>> guca
[1, 2, 3]
>>> guca.extend([4,5,6])
>>> guca
[1, 2, 3, 4, 5, 6]

16. Search operations on the lists : 
>>> guca.index(4)   # Returns the index of the item looking for
3
>>> guca.append(3)
>>> guca
[1, 2, 3, 4, 5, 6, 3]
>>> guca.index(3)  # Note .. the first found occurance's index is returned.
2
>>> 10 in guca  # Check if 10 is in list ..Note: Returns Boolean
False
>>> 4 in guca
True
>>> guca.index(200)  # Note : Catch the exception, if you want ur program to continue.
Traceback (most recent call last):
 File "", line 1, in
guca.index(200)
ValueError: 200 is not in list

17.Removing from the lists : 
>>> guca.remove(4)
>>> guca
[1, 2, 3, 5, 6, 3]
>>> guca.remove(3)  # Remove the first occurance
>>> guca
[1, 2, 5, 6, 3]
>>> guca.append(5)
>>> guca
[1, 2, 5, 6, 3, 5]
>>> guca.pop(5)  # Pop returns the elements being removed and notice it is indexing from -1
5
>>> guca
[1, 2, 5, 6, 3]

18. List operators usage 
>>> guca
[1, 2, 5, 6, 3]
>>> guca+[7,8]   # same as extend ..but extend is faster and in-place. This returns the new list
[1, 2, 5, 6, 3, 7, 8]
>>> new_list=[1,2]*3  # Repeat the same list for specified number of times
>>> new_list
[1, 2, 1, 2, 1, 2]
>>> 

19. Tuples : Immutable and enclosed within the pair of paranthesis .. otherwise pretty much like a list :)
>>> guca_tup=('hi', 2016, 'happy') #declaring the tuple
>>> guca_tup
('hi', 2016, 'happy')
>>> guca_tup[0],guca_tup[-1] # positive and negative indexing is possible
('hi', 'happy')
>>> guca_tup[1:2] #slicing is possible
(2016,)

20. Notes on Tuples:
can't add elements to a tuple. Tuples have no append or extend method.
can't remove elements from a tuple. Tuples have no remove or pop method.
can't find elements in a tuple. Tuples have no index method.
However, use "in" to see if an element exists in the tuple. ex: 2016 in guca_tup 

Use case : Tuples are faster than lists. If you're defining a constant set of values to iterate through use tuples. 
Since tuples are immutable, can be used as keys of the dictionary.

21. Converting tuple into list:
>>> guca_tup
('hi', 2016, 'happy')
>>> 
>>> guca_list = list(guca_tup)
>>> guca_list
['hi', 2016, 'happy']

22. Bringing the power of enum to python in a pythonic way: 
    >>> range(8)
[0, 1, 2, 3, 4, 5, 6,7]
>>> (NONE, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(8)

23. string Formatting : 
>>> #string formatting
>>> name='cisco'
>>> place = 'SJ'
>>> "%s=%s" %(name,place) # Notice it is tuple
'cisco=SJ'
>>> print("%s is in %s", %(name,place)) # Note to all C programmers about the comma before format specifier
SyntaxError: invalid syntax
>>> print("%s is in %s" %(name,place))
cisco is in SJ
>>> print(name+"is in" + place)
ciscois inSJ
>>> guca_number=10
>>> print("number = %d" %(guca_number)) # integers works the same way as string with their format specifier specified.
number = 10

24. The facts about string formatting: 
Trying to concatenate a string with a non−string raises an exception. 
Unlike string formatting, string concatenation works only when everything is already a string

25. Formatting numbers:
>>> print "Today's stock price: %f" % 50.4625
50.462500
>>> print "Today's stock price: %.2f" % 50.4625  # Truncate the output to two decimals
50.46
>>> print "Change since yesterday: %+.2f" % 1.5  # Notice the + sign in output.
+1.50

26. import module 2 ways : 
>>> import os   # import os as object and call every method using os. 
>>> os.getpid()
2620
>>> os.getppid()
10176
>>> getpid()  # Notice u can call getpid() as it does not belong to your local namespace
Traceback (most recent call last):
 File "", line 1, in
getpid()
NameError: name 'getpid' is not defined
>>> from os import getpid    # from import makes the methods local to ur module namespace
>>> getpid()
2620

27. Know about repr  - Return the string representation of any given input object 
__repr__ is a special method that is called when you call repr(instance). The repr function
is a built−in function that returns a string representation of an object. It works on any object, not just
class instances. You're already intimately familiar with repr and you don't even know it. In the
interactive window, when you type just a variable name and press the ENTER key, Python uses repr
to display the variable's value. Go create a dictionary d with some data and then print repr(d) to
see for yourself.

No comments: