Notes

How to get the directory of current project?
workpath = os.path.dirname(os.path.abspath(__file__))
__file__ will give your filename
abspath will give : /path/to/your/file/filename.py

#itertools
How to print the cartesian product of two lists: list-a and list-b?
print(*itertools.product(a,b))

How to print permutations of given list?
itertools.permutations(iterableList[,r])

Combinations are emitted in lexicographic sorted order. So if the input iterable is sorted, the combination tuples will be produced in sorted order.
itertools.combinations(iterableList,r)

Permutations : Order matters
Combinations : Order doesn't matters

How can we repeat a number say 2 times in combinations?
itertools.combinations_with_replacement(iterableList,repeatTimes)

How to print the count of consecutive occurence of element?
print(*[(len(list(c)), int(k)) for k, c in itertools.groupby(input())])
Example: 
Input: 1222311
Output : (1, 1) (3, 2) (1, 3) (2, 1)
Explain : One 1's Three 2's One 3 Two 1's

How to write for polar coordinates?
distance=(x*x+y*y)**0.5
print(distance)
print(cmath.phase(complex(x,y)))

How to convert polar to rectangular co-ordinates(x,y)?
cmath.rect(px,py)

How to convert co-ordinates(x,y) to polar?
cmath.polar(complex(x,y))

Which module is used for complex numbers?
cmath

How to convert co-ordinates(x,y) to complex number?
complex(x,y)

How to check if set a is subset of set b?
a.issubset(b)

How to print elements which are present only in set a and set b?
a.symmetric_difference(b)

Find substring in a string?
string.find(substring) will return index
rfind() - in reverse direction

How to get modulus of a^b mod c?
pow(a,b,c)

How to get divisor and remainder?
a//b - divisor
a%b - remainder
alternately
divmod(a,b) returns a tuple of divisor and remainder

How to convert binary number to decimal?
bin_num=1010
dec_num=(int)(bin_num,2)

How to get index of element in list python
l.index(element)

How to break a list?
l=list(map(int,input().split()))
n=3
m=[l[i*n:(i+1)*n] for i in range((len(l)+n-1)//n)]

print(m)
Input: 1 1 0 0 0 1 1 0 1
Output: [[1, 1, 0], [0, 0, 1], [1, 0, 1]]

How to check if key is present in dictionary?
if key in dict.key()

How to create 2-d array with element 0's?
a = [[0] * m for i in range(n)]

How to run in step 5 over a list?
list=list(map(int,input().split()))
l=[]
for i in list:
if len(l) < 5:
l.append(i)
else:
print(l)
l.remove(l[0])
l.append(i)
print(min(l))

print(max(l))

How to take more then 1 word input from a line?
l=list(map(int,input().strip().split()))
for 3 variables : n,m,q=list(map(int,input().strip().split()))

How to remove an element from a set?
s.pop() #remove first element

How to add list to set?
s=set()
list=list(map(int,input().split()))
s.update(list)
print(s,list)
#update only works for iterable objects

How to add only single element in set?
obj.add(element)

How to get the sum of elements in set?
s=set([1,2,3])
print(sum(s))
>>>6

How to get the length or size of set?
s=set([1,2,3])
print(len(s))
>>>3

list=raw_input().split()
take input :
from collections import OrderedDict
i=(int)(input())
while i:
list=raw_input().split()
d=OrderedDict()
d[list[0]]=list[3]
d[list[1]]=list[4]
d[list[2]]=list[5]
print(d)
i-=1


2 ** 3
8
above is 2 power 3

mystring="abcdefghij"
mystring[::-1]
'jihgfedcba'
Reverse the string

mystring[-1]
j
output 1st from last

mystring[start:stop:step]
step is jumps

'education'[3:6] returns cat

Strings are immutable

#comment

strVar.upper()
strVar.lower()
strVar.split('i')---i is the delimiter by default its whitespaces

>>> print('The {2} {1} {0}'.format('fox','brown','quick'))
The quick brown fox

float formatting follows "{value:width.precisionf}"
result=104.1234567
>>> print("The result was {r:1.3f}".format(r=result))
The result was 104.123


String formatted
>>> name="dhiru"
>>> age=26
>>> print(f'{name} is {age} years old.')
dhiru is 26 years old.

len(my_list)
#no of elements

concatenate
mylist + another_list

mutable
mylist[0] = 'ZERO'

mylist.append('four')

mylist.pop()
returns last element and removes it from list

mylist.pop(0)
removes at 0 location default location is -1

mylist.sort()
inplace sorting takes place

Below is wrong way
sortedlist=mylist.sort()
type(sortedlist)
NoneType

NoneType is special object in python means no value

WA
mylist.sort()
sortedlist=mylist

mylist.reverse()
sort in reverse inplace

Dictionaries
{'key1':'value1','key2':'value2'}
dictionaries cannot be sorted

d.keys()
d.values()

1. Do dictionaries keep an order? How do I print the values of the dictionary in order?

Dictionaries are mappings and do not retain order! If you do want the capabilities of a dictionary but you would like ordering as well, check out the ordereddict object lecture later on in the course!

tuple are immutable
t=('a','a','b')
t.count('a')
2

t.index('a')
0
first occurence of a

Sets are unordered collections of unique elements
myset=set()
myset.add(1)
mylist=[1,1,2,2,2,3,3,3]
set(mylist)
>{1,2,3,}

Booleans are operators that are used to convey True or False
1==1
True

b=None

%%writefile filename.txt
Hello this is a text file
this is the first/second line
this is the third line

filename=open('filename.txt')
filename.read()
filename.seek(0)
filename.readlines()
filename.close()

with open('filename.txt') as my_new_file:
contents = my_new_file.read()
after above command no need to close the opened file

with open('filename.txt',mode='r') as f:
print(f.read())

with open('filename.txt',mode='a') as f:
f.write('one line appended')

with open('hhkljkjj.txt',mode='w') as f:
f.write('one line appended')

with open('test.txt','w+') as fil:
    fil.write('Hello World')

for square root
import math
math.sqrt(num)
or num ** 0.5

sorted(list4) --- not inplace but return sorted version

if some_condition:
#code to execute
elif:
#something else to execute
else:
#else other code to execute

for num in my_list:
if num%2==0
print(f'even num: {num}')

mylist=[(1,2),(3,4),(5,6),(7,8)]
for a,b in mylist
print(a)
print(b)

for dictionaries:
for k,v in dict.items()
print(k)
print(v)

for v in dict.values():
print(v)

for num in range(10):
print(num)

3 to 10
for num in range(3,10):
print(num)

step size 2
range(0,11,2)

these are generators
list(range(0,11,2)

index_count = 0
for letter in 'abcde':
print('At index {} the letter is: {}'.format(index_count,letter))
index_count+=1

word='abcde'
for item in enumerate(word):
print(item)
output:
(0,'a')
(1,'b')
(2,'c')
(3,'d')
(4,'e')

for index,letter in enumerate(word):
print(index)
print(letter)

mylist1=[1,2,3,4,5]
mylist2=['a','b','c']
mylist3=[100,200,399]
for item in zip(mylist1,mylist2):
print(item)

for a,b,c in zip(mylist1,mylist2,mylist3):
print(a)
print(b)
print(c)

list(zip(mylist1,mylist2))

'a' in 'a world'
>>True

2 in [1,2,3]
>>True

mykey in {'mykey':345}
>>True

d={'mykey':345}
345 in d.values()
>>True

Minimum and maximum values
min(mylist)
max(mylist)

from random import shuffle

mylist=[1,2,3,4,5,6]
shuffle(mylist)
shuffles in place

from random import randint

randint(0,100)
mynum=randint(0,100)
mynum

Taking input
name=input('What is your name')
name

casting in python
a='10'
float(a)
int(a)
or
a=int(input('Your id number please:'))
a


List Comprehensions are unique way of quickly creating a list with Python
If you find yourself using a for loop along with .append() to create a list, List Comprehensions are a good alternative!

mystring='hello'
mylist[]
for letter in mystring:
mylist.append(letter)

mylist
['h','e','l','l','o']

mylist=[letter for letter in mystring]

get list of squares of first 10 numbers
mylist=[num**2 for num in range(0,11)]

Check for even numbers
mylist=[x for x in range(0,11) if x%2==0]

celcius=[0,10,20,34,5]
fahrenheit=[((9/5)*temp+32) for temp in celcius]

fahrenheit=[]
for temp in celcius
fahrenheit.append(((9/5)*temp)+32)
fahrenheit

results=[ x if x%2==0 else 'ODD' for x in range(0,11)]

mylist=[x*y for x in [1,2,3] for y in [1,10,1000]]


Use for, .split() and if to create a Statement that will print out words that start with 's':

st='Print only the words that start with s in this sentence'
>>> for word in st.split():
...     if word[0].lower() == 's':
...       print(word)
...
start
s
sentence

Use range() to print all the even numbers from 0 to 10
>>> for i in range(0,11):
...  if i%2==0:
...   print(i)
...
0
2
4
6
8
10

Use a list comprehension to create a list of all numbers between 1 and 50 that are divisible by 3
>>> mylist=[x for x in range(3,51,3)]
>>> mylist
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]

Go through the string below and if the length of a word is even print "even!" or the sentence
st='Print every word in this sentence that has an even number of letters'
>>> for s in st.split():
...  if len(s)%2==0:
...   print(s)
...
word
in
this
sentence
that
an
even
number
of


Use List Comprehensions to create a list of the first letters of every word in the string below
st='Create a list of the first letters of every word in this string'
>>> mylist=[x[0] for x in st.split()]
>>> mylist
['C', 'a', 'l', 'o', 't', 'f', 'l', 'o', 'e', 'w', 'i', 't', 's']


args and kwargs

def myfunc(*args):
return sum(args)*0.5

kwargs is like dictionaries
def myfunc(**kwargs):
print(kwargs)
if 'fruit' in kwargs:
print('My fruit of choice is {}'.format(kwargs['fruit']))
else:
print('I did not find any fruit here'

myfunc(fruit='apple',veggies='letuce')

def myfunc(*args,**kwargs):
print(args)
print(kwargs)
print('I would like {} {}'.format(args[0], kwargs['food']))

myfunc(10,20,30,fruit='orange',food='eggs',animal='dog')

write a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd
>>> def lesser_of_two_evens(a,b):
...  if a>b:
...   greater=a
...   lower=b
...  else:
...   greater=b
...   lower=a
...  if a%2==1 or b%2==1:
...   return greater
...  else:
...   return lower
...
>>> lesser_of_two_evens(11,5)
11
>>> lesser_of_two_evens(1,5)
5
>>> lesser_of_two_evens(1,4)
4
>>> lesser_of_two_evens(44,4)
4


Animal Crackers: Write a function takes a two-word string and returns True if both words begin with same letter
>>> def animal_crackers(a):
...  f=a.split()[0];
...  s=a.split()[1]
...  return f[0].lower()==s[0].lower()
...
>>> animal_crackers('Lwvel lwe')
True
>>> animal_crackers('Crazy Kanga')
False


makes twenty: Given two integers, return True if the sum of the integers is 20 or if one of the integers is 20. If not, return False
>>> def makes_twenty(a,b):
...  if a==20 or b==20:
...   return True
...  return a+b==20
...
>>> makes_twenty(20,10)
True
>>> makes_twenty(12,8)
True
>>> makes_twenty(1,8)
False

def makes_twenty(a,b):
return (n1+n2)==20 or n1==20 or n2==20

>>> def old_macdonald(name):
...  return name[0].upper()+name[1:3]+name[3].upper()+name[4:]
...
>>> old_macdonald('macdonald')
'MacDonald'
>>>

def old_macdonald(name):
return name[:3].capitalize() + name[3:].capitalize()


mylist=['a','b','c']
' '.join(mylist)
>>a b c

'contains delimiter kind of string'

Master yoda: Given a sentence, return a sentence with the words reversed
>>> def master_yoda(s):
...  return ' '.join(s.split()[::-1])
...
>>> master_yoda('i am home')
'home am i'

almost_there: Given an iteger n, return True if n is within 10 of either 100 or 200
>>> def almost_there(n):
...  return n<=110 and n>=90 or n<=210 and n>=190
...
>>> almost_there(90)
True
>>> almost_there(104)
True
>>> almost_there(150)
False
>>> almost_there(209)
True

def almost_there(n):
return (abs(100-n)<=10) or (abs(200-n)<=10)

Check for consecutive 3 in list
>>> def has_33(nums):
...  for i,j in enumerate(nums):
...   if i!=0 and (nums[i]==3 and nums[i-1]==3):
...    return True
...  return False
...
>>> has_33([1,3,3])
True
>>> has_33([1,3,1,3])
False
>>> has_33([3,1,3])
False


Given a string, return a string where for every character in the original there are three characters
>>> def paper_doll(s):
...  r=''
...  for i in s:
...   r=r+i*3
...  return r
...
>>> paper_doll('Hello')
'HHHeeellllllooo'
>>> paper_doll('Mississippi')
'MMMiiissssssiiissssssiiippppppiii'

Given three integers between 1 and 11, if their sum is less than or equal to 21, return their sum. If their sum exeeds 21 and there's an even an eleven, reduce the total sum by 10. Finally, if the sum(even after adjustment) exceeds 21, return 'BUST'

>>> def blackjack(n1,n2,n3):
...  sum=n1+n2+n3
...  if sum <= 21:
...   return sum
...  if sum > 21 and n1==11 or n2==11 or n3==11:
...   sum-=10
...  if sum <= 21:
...   return sum
...  return 'BUST'
...
>>> blackjack(5,6,7)
18
>>> blackjack(9,9,9)
'BUST'
>>> blackjack(9,9,11)
19

def blackjack:
if sum([n1,n2,n3])<=21:
return sum([n1,n2,n3])
elif 11 in [n1,n2,n3] and sum([n1,n2,n3]) <=31:
return sum([n1,n2,n3])-10
else:
return 'BUST'

SummerOf69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9(every 6 will be followed by at least one 9). Return 0 for no numbers.
>>> def summerOf69(nums):
...  f=0
...  sum=0
...  for i in nums:
...   if i==6:
...    f=1
...    continue
...   if i==9 and f==1:
...    f=0
...    continue
...   if f==0:
...    sum=sum+i
...  return sum
...
>>> summerOf69([1,3,5])
9
>>> summerOf69([4,5,6,7,8,9])
9
>>> summerOf69([2,1,6,9,11])
14

Spy Game: Write a function that takes in a list of integers and returns True if it contains 007 in order
>>> def spy_game(nums):
...  zero1=False
...  zero2=False
...  seven=False
...  for i in nums:
...   if zero1==False and i==0:
...    zero1=True
...    continue
...   if zero1==True and zero2==False and i==0:
...    zero2=True
...    continue
...   if zero1==True and zero2==True  and i==7:
...    return True
...  return False
...
>>> spy_game([1,2,4,0,0,7,5])
True
>>> spy_game([1,0,2,4,0,5,7])
True
>>> spy_game([1,7,2,0,4,5,0])
False


def spy_game(nums):
code=[0,0,7,'x']
for num in nums:
if num==code[0]:
code.pop()
return len(code)==1

Count Prime Numbers between 1 to 100
>>> mylist=list(range(0,101))
>>> mylist=list(range(0,101))


Count no. of primes till given number





Lamda expresssion and map and  filter
def square(num):
return n**2

mynums=[1,2,3,4,5]

list(map(square,mynums))

def check_even(num):
return num%2==0

mynums(1,2,3,4,5,6)
list(filter(check_even,mynums))

for n in filter(check_even,mynums):
print(n)
2
4
6


def square(num):
return num**2
lamda of above is below
square=lamda num: num**2

list(map(lamda num: num**2,mynums))

list(filter(lamda num:num%2==0,mynums))

list(map(lamda x:x[0],names))  ->
list(map(lamda x:x[::-1],names))  -> reverse the names


Nested Statements and Scope
LEGB
Local
Enclosing Function Local
Global
Built-in


x=50#global variable
def func():
global x -> anything happens on local x reflects to global
print(f'X is {x}')
x=200
print(f'local and global both are now {x}')

def ran_check(num,low,high):
if num in range(low,high):
print "%s is in the range" %str(num)
else:
print "The number is outside the range."

count upper and lower case letters
d={"upper":0, "lower":0}
for c in strings:
if c.upper():
d["upper"]+=1
elif c.lower():
d["lower"]+=1
else:
pass

set(mylist)
create a function like set
def unique_list(l):
x=[]
for a in l:
if a not in x:
x.append(a)
return x

Check if s is palindrome or not
return s == s[::-1]

Pangram: contains all the letters of english
import string
def ispangram(str1, alphabet-string.ascii_lowercase):
alphabet=set(alphabet)
return alphabet <= set(str1.lower())


from IPython.display import clear_output
>>>clear_output()
or
>>>print('\n'*100)

11927224883

def player_input():
marker=''
while not( marker == 'X' or marker == 'O'):
marker = input(Player1: Choose X or O: ').upper()

if marker == 'X':
return ('X','O')
else:
return ('O','X')

>>>p1,p2=player_input()

Randomly choose 0 or 1
import random
 flip=random.randint(0,1)

Infinite Loop

while True:
#Some code here


Object Oriented Programming (OOP) allows programmers to crete their own objects that have methods and attributes

class NameOfClass():
def __init__(self,param1,param2):
self.param1=param1
self.param2=param2

def some_method(self):
#method code
#self keyword refers to the class
print(self.param1)

class Dog():
def __init__(self,breed):
self.breed=breed

my_dog=Dog(breed='Lab')
type(my_dog)
__main__.Dog
>>>mydog.breed
'Lab'


method is a function inside class
class Animal():
def __init__(self):
print("Animal created")

def who_am_i(self):
print("I am an animal")

def eat(self):
print("I am eating")

Inheritence:
class Dog(Animal):
def __init__(self):
Animal.__init__(self)
print("Dog created")

Animal's method are available to Dog
>>>mydog=Dog()
>>>mydog.eat()

You can add and override methods in sub-class

Abstract classes in inheritence
Can never be instantiated
serve as only base class
class Animal():
def __init__(self,name):
self.name=name

def speak(self):
return NotImplementedError("Subclass must implement this abstract method")


special/dundar function in python
class Book():
def __init__(self,title,author,pages):
self.title=title
self.author=author
self.pages=pages

def __str__(self):
return f"{self.title} by {self.author}"

def __len__(self):
return self.pages

b=Book('India','APJ',300)
>>print(b)
>>India by APJ

delete the object from memory
>>del b

you can add special method for delete
def __del__(self):
print("book is deleted")



Pip install and PyPi
PyPi is a repository for open-source third-party Python packages.
It's similat to RubyGems in the Ruby world, PHP's Packagist, CPAN for Perl, and NPM for Node.js
There are many other libraries available that people have open-sourced and shared on PyPi
We can use pip install at the command line to install these packages
By installing Python from python.org or through the Anaconda distribution you already installed pip

pip is a simple way to download packages at your command line directly from the PyPi repository

pip install requests
pip install colorama
pip install openpyxl


>>> from colorama import init
>>> init()
>>> from colorama import Fore
>>> print(Fore.RED+"some red text")
some red text
>>> print(Fore.GREEN+"some red text")
some red text

How to create your own modules and packages
Modules are just .py scripts that you can call in another .py script
Packages are a colletion of modules

To Create package we must have __init__.py file in the package folder
from mymodule import myfunc
from MyMainPackage import some_main_script
from MyMainPackage.SubPackage import my_sub_script
myfunc()
some_main_script.report_main()
my_sub_script.sub_report()


__name__ and __main__
An often confusing part of Python is a mysterious line of code:
if __name__ == "__main__":
print("Script is called directly")
else:
print("Script is imported")

above is used is .py file is imported or its ran directly in cmdline
Sometimes when you are importing from a module, you are importing from a module, you would like to know whether a modules function is being used as an import, or if you using the original.py file of that module.


Errors are bound to happen in your code!
Especially when someone else ends up using it in an unexpected way
We can use error handling to attempt to plan for possible errors
For example, a user may try to write to a file that was only opened in mode='r'
Currently if there is any type of error in your code, the entire script will stop
We can use Error Handling to let the script continue with other code, even if there is an error

Three Keywords are used for error handling
try: This is the block of code to be attempted(may lead to an error)
except: Block of code will execute in case there is an error in try block
finally: A final block of code to be executed, regardless of an error

def ask_for_int():
while True:
try:
result=int(input("Please provide number: "))
except:
print("Whoops! That is not a number")
continue
else:
print("yes thank you")
break
finally:
print("I'm going to ask you again!\n")


try:
for i in ['a','b','c']:
print(i**2)
except TypeError:
print("a**2 is giving TypeError")

try:
x=5
y=0
z=x/y
except ZeroDivisionError:
print("Divided by zero error")


Testing tools
Pylint: This is a library that looks at your code and reports back possible issues
unittest: This is built-in library will allow to test your own programs and check you are getting desired outputs
Python as a set of style convention rules known as "PEP 8"

pip install pylint

pylint myprogram.py


unittest:
.capitalize() upper cases the first letter.
.title() upper cases first letter of every word


Decorator
def new_decorator(original_func):
def wrap_func():
print('Some extra code, before the original function')
original_func()
print('Some extra code, after the original function')
return wrap_func

def func_needs_decorator():
print("I wan to be decorated!!")

decorated_func=new_decorator(func_needs_decorator)
>>decorated_func()
Some extra code, before the original function
I want to be decorated!!
Some extra code, after the original function!


or

@new_decorator
def func_needs_decorator
print("I want to be decorated!!")


Generator
Generator functions allow us to write a function that can send back a value and then later resume to pick up where it left off
allowing us to generate a sequence of values over time
The main difference in syntax will be the use of a yield keyword statement
When a generator function is compiled they become an object that supports an iteration protocol.
That means when they are called in your code they don't actually return a value and then exit.
Generator functions will automatically suspend and resume their execution and state around the last point of value generation.
The advantage is that instead of having to compute an entire series of values up front, the generator computes one value waits until the next value is called for.

def create_cubes(n):
for x in range(n):
yield x**3

def gen_fibon(n):
a=1
b=1
for i in range(n):
yield a
a,b=b,a+b

for num in gen_fibon(10):
print(num)


print(next(g))

s='hello'
s_iter=iter(s)
next(s_iter)

Generator comprehension
mylist=[1,2,3,4,5]
gencomp=(item for item in mylist if item > 3)
for item in gencomp:
print(item)

difference between list and generator comprehension is gencomp uses ()


Collections module
from collections import Counter

l=[1,2,2,3,3,3,4,4,4]
Counter[l]
>>Counter({1:1,2:2,3:3,4:3})

word=sentence.split()
Counter(words)

c=Counter(words)
>>c.most_common(2)#shows 2 most common words

#Total words/counts
>>sum(c.values())
>>c.clear() #reset all counts
>>list(c) #lists unique elements
>>set(c) #convert to a set
>>dict(c) #convert to regular dictionary
>>c.items() #convert to list of (elem,cnt) pairs
>>Counter(dict(list_of_pairs)) #convert from list of (elem,cnt) pairs
>>c.most_common()[:-n-1:-1] #n Least common elements
>>c+=Counter() #remove zero and negative counts


defaultdict
defaultdict is a dictionary like object which provides all methods provided by dictionary but takes first argument(default_factory) as default data type for the dictionary. Using defaultdict is faster than doing the same using dict.set_default method.

A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
>>d=defaultdict(object)
or
>>defaultdict(lambda : 0) #default value is zero

for k,v in d.items():
print k,v

OrderedDict
from collections import OrderedDict
d=OrderedDict()
then insert element in dictionary, it will store the elements in order

in ordereddict, d1 == d2 returns True if order is also same


namedtuple
from collections import namedtuple
Dog=namedtuple('Dog','age breed name')
sam=Dog(age=2,breed='Lab',name='Sammy')


Datetime
import datetime
t=datetime(5,24,1)
print (t)


>>> print(datetime.time.min)
00:00:00
>>> print(datetime.time.max)
23:59:59.999999
>>> print(datetime.time.resolution)
0:00:00.000001
>>> print(datetime.date.today())
2019-05-10
>>> print(datetime.date.today().timetuple())
time.struct_time(tm_year=2019, tm_mon=5, tm_mday=10, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=130, tm_isdst=-1)
>>> print(datetime.date.today().day)
10
>>> print(datetime.date.today().month)
5
>>> print(datetime.date.min)
0001-01-01
>>> print(datetime.date.max)
9999-12-31
>>> print(datetime.date.resolution)
1 day, 0:00:00
>>> print(datetime.date(2019,5,9))
2019-05-09
>>> d1=datetime.date(2019,5,9)
>>> d1
datetime.date(2019, 5, 9)
>>> d2=d1.replace(day=11)
>>> d2
datetime.date(2019, 5, 11)
>>> d1-d2
datetime.timedelta(days=-2)

pdb is the pythons built-in debugger

import pdb

pdb.set_trace()

import timeit
timeit.timeit(' "-".join(str(n) for n in range(100)) ',number=10000)
>>> timeit.timeit('"-".join(str(n) for n in range(100))',number=10000)
0.332896964000156
>>> timeit.timeit('"-".join([str(n) for n in range(100)])',number=10000)
0.2858472170000823
>>> timeit.timeit('"-".join(map(str,range(100)))',number=10000)
0.23316591299999345


C:\Users\user>python -m timeit '"-".join(map(str,range(100)))'
20000000 loops, best of 5: 11.8 nsec per loop


Regular Expressions
import re
pattern=['term1','term2']
text='This is a string with term1, but not the other term'
re.search('hello','hello')
for pattern in patterns:
print('Searching for "%s" in: \n"%s"' %(pattern,text),

#Check for match
if re.search(pattern,text):
print('\n')
print('Match was found)
else:
print('\n')
print('No match was found')


>>> for pattern in patterns:
...  print('Searching "%s" in "%s"' %(pattern,text))
...  if re.search(pattern,text):
...   print('Match found')
...  else:
...   print('Match not found')
...
Searching "term1" in "This is a string with term1, but not the other term"
Match found
Searching "term2" in "This is a string with term1, but not the other term"
Match not found


"None" is returned if no match is found
>>> print(re.search('h','w'))
None

>>> match=re.search(patterns[0],text)
>>> type(match)
<class 're.Match'>

index of matched pattern starts at
>>> match.start()
22

index of matched pattern ends at
>>> match.end()
27

Acts like delimiter
>>> split_term='@'
>>> phrase='What is your email, is it hello@gmail.com?'
>>> re.split(split_term,phrase)
['What is your email, is it hello', 'gmail.com?']

how you separate domainName with email address

find all the matches
>>> re.findall('match','Here is one match, here is another match')
['match', 'match']

count all the matches
>>> len(re.findall('match','Here is one match, here is another match'))
2

pattern*
pattern+
pattern?
pattern{num}
pattern{num,num}

text_patterns=[
'sd*', #s followed by zero or more d's
'sd+', #s followed by one or more d's
'sd?', #s followed by zero or one d's
'sd{3}', #s followed by three d's
'sd{2,3}, #s followed by two to three d's
]


Character Sets are used when you wish to match any one of a group of characters at a point in the input. Brackets are used to construct character set inputs. For ex.
input [ab] searches for occurences of either a or b

^ exclude
[^ab] will match character other then a or b

Below removes all the punctuations
re.findall('[^!.?]+',test_phrase)

Character ranges
test_patterns=[
'[a-z]+', #sequence of lower case letters
'[A-Z]+', #sequence of upper case letters
'[a-zA-Z]+' #sequence of lower or upper case letters
'[A-Z][a-z]+' #one upper case letter followed by lower case letters
]

Escape codes
\d : a digit
\D : a non-digit
\s : whitespace(tab, space, newline, etc.)
\S : non-whitespace
\w : alphanumeric
\W : non-alphanumeric

test_patterns=[ r'\d+', r'\D+', r'\s+', r'\S+', r'\w+', r'\W+']

StingIO
The StringIO module implements an in-memory file like object. This object can then be used as input or output to most functions that would expect a standard file object.

import StingIO
message='This is just a normal string.'
f=StringIO.StringIO(message)
f.read()
''
f.write(' Second line written to file like object')

f.seek(0)
f.read()


Advanced Numbers
>>> hex(55)
'0x37'
>>> bin(55)
'0b110111'

pow(x,y,z)
(x**y)%z

>>> pow(2,4,3)
1
>>> abs(-3)
3
>>> round(3.5)
4
>>> round(3.4)
3
>>> round(3.15643,2)
3.16


Advanced String
>>> s='hello world'
>>> s.upper()
'HELLO WORLD'
>>> s.lower()
'hello world'
>>> s.count('o')
2
>>> s.find('o')
4
>>> s.center(20,'-')
'----hello world-----'
>>> 'hello\tworld'.expandtabs()
'hello   world'
>>> s.isalnum()
False
>>> t='hello'
>>> t.isalnum()
True
>>> t.isalpha()
True
>>> print '1234'.isdigit()
True
>>> print '123edsd'.isdigit()
False
>>> s.islower()
True
>>> s.isspace()
False
>>> s.istitle()
False
>>> 'Hello'.istitle()
True
>>> 'HELLO'.isupper()
True
>>> s.endswith('d')
True
>>> s.partition('l')
('he', 'l', 'lo world')


Advanced set
>>> s=set()
>>> s.add(1)
>>> s.add(2)
>>> s
{1, 2}
>>> s.clear()
>>> s
set()


>>> s
{1, 2, 3}
>>> sc=s.copy()
>>> sc
{1, 2, 3}
>>> s.add(4)
>>> s.add(5)
>>> s.difference(sc)
{4, 5}
>>> sc.difference(s)
set()
#values present in sc but not in s

>>> s1={1,2,3}
>>> s2={1,4,5}
>>> s1.difference_update(s2)
>>> s1
{2, 3}

>>> s
{1, 2, 3, 4, 5}
>>> s.discard(3)
>>> s
{1, 2, 4, 5}
#if the value is not present discard() does nothing but remove() will raise a KeyError exception

>>> s1
{1, 2, 3}
>>> s2
{1, 3, 4}
>>> s1.intersection(s2)
{1, 3}
>>> s1
{1, 2, 3}
>>> s2
{1, 3, 4}
>>> s1.intersection_update(s2)
>>> s1
{1, 3}
>>> s1={1,2}
>>> s2={1,2,4}
>>> s3={5}
>>> s1.isdisjoint(s2)
False
>>> s1.isdisjoint(s3)
True
>>> s1.issubset(s2)
True
>>> s2.issuperset(s1)
True
>>> s1.symmetric_difference(s2)
{4}
>>> s2.symmetric_difference(s1)
{4}
>>> s1.union(s2)
{1, 2, 4}
>>> s1.update(s2)
>>> s1
{1, 2, 4}

union() and intersection() methods are symmetric methods
a,b=set([1]),set([3])
print(a.union(b)==b.union(a))
print(a.intersection(b)==b.intersection(a))
print(a.difference(b)==b.difference(a))
>>>True
>>>True
>>>False

Advanced Dictionaries
>>> {x:x**2 for x in range(10)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>> {k:v**2 for k,v in zip(['a','b'],range(2))}
{'a': 0, 'b': 1}




Advanced list
>>> l=[1,2,3]
>>> l.append(4)
>>> l
[1, 2, 3, 4]
>>> l.count(10)
0
>>> l.count(1)
1
>>> x=[1,2,3]
>>> x.append([4,5])
>>> x
[1, 2, 3, [4, 5]]
>>> x=[1,2,3]
>>> x.extend([4,5])
>>> x
[1, 2, 3, 4, 5]
>>> l
[1, 2, 3, 4]
>>> l.index(2)
1
>>> l.insert(2,'inserted')
>>> l
[1, 2, 'inserted', 3, 4]
>>> p=l.pop()
>>> p
4
>>> l
[1, 2, 'inserted', 3]
>>> l.pop(0)
1
>>> l
[2, 'inserted', 3]
>>> l.remove('inserted')
>>> l
[2, 3]
>>> l=[1,2,3,4,3]
>>> l.remove(3)
>>> l
[1, 2, 4, 3]
>>> l.reverse()
>>> l
[3, 4, 2, 1]
>>> l.sort()
>>> l
[1, 2, 3, 4]

>>> bin(1024)
'0b10000000000'
>>> hex(1024)
'0x400'
>>> round(5.23222,2)
5.23
>>> s='hellow how are you Mary, are you feeling okay?'
>>> for x in s.split():
...  if x.islower():
...   print('True')
...  else:
...   print('False')
...
True
True
True
True
False
True
True
True
True
>>> s='sldasldfsldjfasdlfasdfasdfasldfsld'
>>> s.count('s')
8
>>> set1={2,3,1,5,6,8}
>>> set2={3,1,7,5,6,8}
>>> set1.difference(set2)
{2}
set1.union(set2)
>>> set1.update(set2)
>>> set1
{1, 2, 3, 5, 6, 7, 8}
>>> {x:x**3 for x in range(5)}
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64}


if i.isalnum():
if i.isalpha():
if i.isdigit():
if i.islower():
if i.isupper():

Text Alignment:
width=20
"string".ljust(width,'-')
"string".center(width,'-')
"string".rjust(width,'-')

textwrap
import textwrap
>>> import textwrap
>>> string = "This is a very very very very very long string."
>>> print textwrap.wrap(string,8)
['This is', 'a very', 'very', 'very', 'very', 'very', 'long', 'string.']

>>> import textwrap
>>> string = "This is a very very very very very long string."
>>> print textwrap.fill(string,8)
This is
a very
very
very
very
very
long
string.

Printing in format
def print_formatted(num):
    width=len(bin(num)[2:])
    for number in range(1,num+1):
        print(((str)(number)).rjust(width),oct(number)[2:].rjust(width),hex(number)[2:].rjust(width).upper(),bin(number)[2:].rjust(width))


Make first letter uppercase of every word:
import string
string.capwords("String to be capitalize Notice spaces   be    compressed")

"string to  be  capitalized".title()
"Only first word capitalized".capitalize()

def solve(s):
    l=[]
    l.append(s[0].upper())
    for i in range(1,len(s)):
        if l[i-1]==' ':
            l.append(s[i].upper())
        else:
            l.append(s[i])
    return ''.join(l)

Comments