Python Codebook by COG Updated - Compressed 1 PDF
Python Codebook by COG Updated - Compressed 1 PDF
PYTHON
CODEBOOK
In this e-book, we will look at different Python Hacks. This e-book is useful for anyone
who wants to brush up Python concepts and that too in very less time. This will prove
to be a great reference if you want to start competitive programming with Python.
www.codeofgeeks.com
© 2020
All rights reserved. No portion of this book may be reproduced in any form
without permission from the publisher.
support@codeofgeeks.com
Taking inputs :
s = input() // taking string as input
n = int(input()) // taking int as input
b = bool(input()) // taking boolean value as input
l = list(input().split(‘,’)) // taking list as a input where elements are seperated by comma
1. Let us assume that we have to print values of two variables – a=10 b=20 as 10—
-20, We can do this by : print(a,b,sep=’—‘)
2. The output displayed by the print() method can be formatted as you like.
‘%’ operator is used for this purpose. It joins a string with a variable or
value. Example :
print(“string” % (variable-list))
3. Mathematical methods
ceil(x) : It raises x value to the next higher integer value. For example, ceil(4.5) gives 5.
floor(x) : It decreases x value to previous integer value. For example, floor(4.5) gives 4.
degrees(x) : It converts angle value x from radians to degrees.
radians(x) : It converts x value from degree to radians.
sin(x) : It gives a sine value of x.
cos(x) : It gives a cosine value of x.
tan(x) : It gives a tan value of x.
exp(x) : It gives exponential of x.
fabs(x) : It gives absolute value of x. Like fabs(-4.53) gives 4.53.
factorial(x) : It gives the factorial of x.
fmod(x,y) : It gives remainder of division of x & y. Like, fmod(13.5,3) gives 1.5.
fsum(val) : It gives the accurate sum of floating point values.
log10(x) : It gives base-10 logarithm of x.
sqrt(x) : It gives the square-root of number x.
pow(x,y) : It raises x value to the power y.
Indexing in Strings :
0 1 2 3 4 5 6
p Y t h o n n
-7 -6 -5 -4 -3 -2 -1
Reversing a String :
i=1
n=len(s)
while i<=n:
print(s[-i],end=' ')
i+=1
Slicing a String :
string-name[start : stop : stepsize]
If given string is “pythonn” so s[0:7:2] gives pton as output.
Repeating a String :
s = ‘pythons’
print(s*2)
Concatenation of Strings :
Strings can be concatenated with one another using ‘+‘ operator.
s1 = "string 1"
s2 = "string 2"
s3 = s1 + s2
print(s3)
Output : string 1string 2
print(s.lstrip())
print(s.rstrip())
print(s.strip())
Output :
Python
String Methods :
4. sep.join(str) : When a group of strings are given, it is possible to join them all
and make a single string. Syntax : seperator.join(string)
l = ["one","two","three"]
s = "-".join(l)
print(s)
Output : one-two-three
8. s.title() : It converts a string in such way that first letter of a word in string is
a uppercase letter.
s = "pYthon"
print(s.upper()) // PYTHON
print(s.lower()) // python
print(s.swapcase()) // PyTHON
11. s.alnum() : It returns True if all characters in the string are alpha
numeric (A-Z, a-z, 0-9).
12. s.alpha() : It returns True if string has atleast one character and all other
characters are alphabetic (A-Z, a-z).
13. s.isdigit() : It returns True, if the string contains only numeric digits (0-9).
14. s.islower() : It returns True, if at least one or more letters are in lowercase.
15. isupper() : It returns True, if at least one or more letters are in uppercase.
Output :
10,Code of Geeks,1345.345
We can use range() function to generate a sequence of integers which can be stored in
a list. The format of range() function is :
range(start, stop, stepsize)
If not mentioned, start is specified to be 0 and stepsize is taken 1.
l1 = range(10)
for i in l1:
print(i)
l=[1,2,3,4,5]
i=0
while i<len(l):
print(l[i])
i+=1
Output : 1 2 3 4 5
Repetition of Lists :
l = [10,20]
print(l*2)
Output : [10,20,10,20]
Membership in Lists :
l = [10,20,30,40,50]
a = 30
print(a in l)
Output :
True
List Methods
l=[2,4,6,23]
print(max(l))
print(min(l))
Output :
23
2
2D Lists :
Suppose we want to create a 3X3 matrix, so we can represent as list – of – lists. For
example,
mat = [[3,4,5],[4,6,2],[4,7,2]]
Creation :
for r in mat:
for c in r :
print(c,end=' ')
print()
Tuple Creation :
tup = tuple(range(4,9,2))
print(tup)
Output :
Sets – Python
A Set is an unordered collection data type that is iterable, mutable, and has no
duplicate elements.
Basic set operations & methods :
1. Set.add() : If we want to add a single element to an existing set, we can use the
.add() operation.
It adds the element to the set and returns ‘None’.
set1 = set('codeofgeeks')
set1.add('z')
print(set1)
Output :
{'c','d','e','f','g','k','o','s','z'}
2. Set.remove() :
This operation removes element from the set. If element does not exist, it raises
a KeyError.
s = set([1,2,3,4,5])
s.remove(4)
print(s)
Output :
{1,2,3,5}
3. Set.pop() : This operation removes and return an arbitrary element from the set.
If there are no elements to remove, it raises a KeyError.
5. Set.union() : Union of two given sets is the smallest set which contains all
the elements of both the sets.
s = set("code of geeks")
print(s.union("geeks "))
Output :
{'g', 'o', 'd', 'f', 'c', 'k', 'e', 's', ' '}
6. Set.intersection() : It is the largest set which contains all the elements that
are common to both the sets.
s = set("code of geeks")
print(s.intersection("geeks "))
Output :
{'s', 'e', 'g', ' ', 'k'}
Dictionary represents a group of elements arranged in the form of key-pair pair. The
Key and its value are seperated by a colon(:).
dict = {‘Name’ : ‘Vikas’, ‘Id’ : 20}
Dictionary Methods :
1. dict.clear() : It removes all key-value pairs from dictionary.
2. dict.copy() : It copies content of one dictionary to another one.
3. dict.get() : It returns the value associated with key ‘ k ‘.
4. dict.items() : It returns an object that contains key-value pairs of dictionary.
5. dict.keys() : It returns a sequence of keys from the dictionary ‘d’.
6. dict.values() : It returns a sequence of values from the dictionary ‘d’.
7. dict.pop(k,v) : It removes the key ‘k’ and its value from ‘d’.
8. dict.update(x) : It adds all elements from dictionary ‘x’ to ‘d’.
9. zip() : converts two lists to a dictionary.
Output :
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
If r is not specified or is None, then r defaults to the length of the iterable and
all possible full-length permutations are generated.
from itertools import permutations
l=['1','2','3']
print(list(permutations(l)))
Output :
[('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), ('3', '1', '2'), ('3', '2', '1')]
3. itertools.combinations(iterable[, r]) :
This tool returns the length subsequences of elements from the input iterable.
Combinations are emitted in lexicographic sorted order.
Output :
[('1', '2'), ('1', '3'), ('2', '3')]
Bisect
This module provides support for maintaining a list in sorted order without having
to sort the list after each insertion. The module is called bisect because it uses a
basic bisection algorithm to do its work.
The following functions are provided:
bisect.bisect_left(list, item[, lo[, hi]])
Locate the proper insertion point for item in list to maintain sorted order. The
parameters lo and hi may be used to specify a subset of the list which should be
Similar to bisect_left(), but returns an insertion point which comes after any
existing entries of item in list.
bisect.bisect(…)
Alias for bisect_right().
import bisect
l = []
print(" ENTER ANY 5 ELEMENTS ")
for i in range(0,5):
c=int(input())
bisect.insort(l,c)
print(l)
Output
ENTER ANY 5 ELEMENTS :
Python Regex
ReGex, also termed as Regular Expression, is the efficient way of handling regular
expressions in a Python Program. It generally involves a sequence of characters that
forms a search pattern.
To work with regular expressions, we have to import re module.
import re
s = ‘code of geeks is for programming geeks’
x = re.findall(‘geek’,s)
print(x)
Output
[‘geek’,’geek’]
re.search() : It searches the string for a match. In the case of more than 1 match only the
first occurrence of the match will be returned.
Example : Below code will the find the existence of word ‘a’ in a string.
import re
s = ‘sdadfghja’
x = re.search(‘a’,s)
print(x.start())
Output
2
re.split() : It is used to split a string into list, as per the separator specified.
Example : Below code will split the string into a list taking ‘-‘ as a separator.
import re
txt = "code-of-geeks"
x = re.split("-", txt)
print(x)
Output
[‘code’, ‘of’, ‘geeks’]
import re
s = "code of geeks"
x = re.sub("geeks","god",s)
print(x)
Output
code of god
**************
For more study material please visit : https://www.codeofgeeks.com