Python-Codebook - Code of Geeks - by-COG - Compressed PDF
Python-Codebook - Code of Geeks - by-COG - Compressed 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.
[email protected]
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
s = tuple(input().split(‘,’)) // taking tuple as a input where elements are seperated by
comma
1. Converting a number from octal, binary and hexadecimal system to decimal number
system.
n1 = 0o17 # representation of octal numbers
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
String Methods :
l = ["one","two","three"]
s = "-".join(l)
print(s)
Output : one-two-three
Output :
10,Code of Geeks,1345.345
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 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.
3. itertools.combinations(iterable[, r]) :
This tool returns the length subsequences of elements from the input iterable.
Combinations are emitted in lexicographic sorted order.
from itertools import combinations
l=['1','2','3']
print(list(combinations(l,2)))
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
**************