In [2]:
abs(-3) # Gives the absolute value of a variable
Out[2]:
In [3]:
all([1,2,3,0]) # Returns True if all iterators are true.
Out[3]:
In [4]:
any([1,2,3,4,0]) # If any value is true among the iterators
Out[4]:
In [24]:
def prime():
pass
print(callable(prime))
# Returns True if object has a return statement
# instances of classes are callable if they have __call))() method
a = 3
callable(a)
Out[24]:
In [27]:
chr(49) # Returns the ASCII represenattion of the number
Out[27]:
In [30]:
complex('3')
Out[30]:
In [ ]:
dir() # Returns a list of names in the current lcoal scope
In [ ]:
import numpy as np
dir(numpy)
In [42]:
divmod(10,3) # Returns the quotient and the remainder
Out[42]:
In [47]:
temp = ['a', 'b', 'f']
list(enumerate(temp, start = 6))
Out[47]:
In [50]:
# Why we use enumerate because it let's use use both the index and the value of the sequence
for index, value in enumerate(temp):
print('The index is %d amd the letter is %c'%(index, value))
In [51]:
format(45, 'b') # To convert in different integer representations
Out[51]:
In [ ]:
globals() # returns a dictionary of current global symbol table
# You can use to see the globals of a function or class
In [60]:
a = 3
id(a) # Kind of address in the memory
Out[60]:
In [62]:
input('Give me something as input')
Out[62]:
In [ ]:
locals() # returns the free variables
In [64]:
a = 2.3412456432
round(a, 3)
Out[64]:
In [70]:
if(3 or 0):
print('Or is True')
if(3 and 0):
print('And is True')
In [72]:
if 3 is 3:
print('The world is round')
if 3 is not 4:
print('The world is round')
In [78]:
a = 3
b = 3.0
if (a == b):
print('Double = works')
if (a is b): # Is does the strict comparison
print('Is works')
In [79]:
# Bitwise operations
x | y # THe or operation
x ^ y # The xor operation
x & y # And operation
x << y # Multiplyting by 2**y
~x # The bits of x reversed
Out[79]:
In [ ]:
# Some sequence operations
s.count(x) # Return the total number of occurences of x
s.index(x[, i[, j]]) # First occurence of x at or after i and before index j
x in s
x not in s
s+t # Concatenation of two sequences
In [85]:
a = list(('a','b','c','d'))
print(a)
In [88]:
a = ['a','b','c','d']
print(a)
In [96]:
myList = [4,5,8,1,23,4,6,8]
myList.sort(reverse = False)
print(myList)
In [97]:
myList.append('a')
print(myList)
In [98]:
myList.remove(1)
print(myList)
In [99]:
a = myList.pop()
print(a)
In [100]:
myList.insert(3, 'b')
print(myList)
In [103]:
myTuple = tuple((1,2,3,'a'))
print(myTuple)
In [112]:
myTuple = (1,2,3,'a', 1+2j)
print(myTuple[3])
# you cannot now add or remove elements from a tuple after its creation
In [133]:
mySet = set((1,2,3,4,'a'))
print(mySet)
In [134]:
mySet[1]
In [135]:
mySet.remove(1)
In [136]:
mySet = {1,2,3,'a',1+2j}
print(mySet)
In [137]:
len(mySet)
Out[137]:
In [138]:
2 in mySet
Out[138]:
In [139]:
mySet2 = {'a','b','c','d'}
mySet.isdisjoint(mySet2) # Tells whether two sets have all differen elements
Out[139]:
In [140]:
mySet3 = {1,2}
mySet3.issubset(mySet)
Out[140]:
In [141]:
mySet.union(mySet2)
Out[141]:
In [142]:
myFrozenSet = frozenset((1,2,3,4))
myFrozenSet
Out[142]:
In [145]:
myDict = dict(one=1, two=2, three=3, four=4)
myDict
Out[145]:
In [146]:
len(myDict)
Out[146]:
In [148]:
myDict['one']
Out[148]:
In [153]:
# You can use __missing__ to specify what to do when a key is not found
class Counter(dict):
def __missing__(self, key):
print('The key is not present')
return 0
myDict = Counter()
print(myDict['red'])
In [154]:
myDict = {'one':1, 'two':2, 'three':3}
myDict
Out[154]:
In [156]:
# You can check for keys
'one' in myDict
Out[156]:
In [164]:
# If you want to iterate over the keys in a dictionary
for key in iter(myDict):
print(key)
In [165]:
myDict.get('one')
Out[165]:
In [167]:
print(myDict.get('zero'))
In [169]:
for values in myDict.items():
print(values)
In [171]:
# Best way to iterate over a dictionary
for key, value in myDict.items():
print('For key = ', key, ' the value is ', value)
In [179]:
myDict.update({'zero':0})
myDict
Out[179]:
All exceptions are instances of a class that derieves from BaseExceptions.
General approach to handle exceptions
try:
...
except SomeExceptionName:
What you want to do if you face that exception
Various base classes
In [191]:
for _ in range(2):
try:
x = int(input('Enter a anumber '))
except ValueError:
print('You did not enter a number')
finally:
print('This line will always be executed')
In [203]:
# To create new exceptions
class B(Exception):
pass
In [206]:
try:
pass
except B:
pass
In [208]:
a = 3
assert (a == 4)
# We would get an exception as a is 3 not 4
Various exception that youmay face
In [212]:
import sys
sys.getrecursionlimit()
# Always remember that tail recursion is not efficient inpython so
# always try to solve the problem iteratively that recursively in pyton.
Out[212]:
It is a process of building software by composing pure functions, avoiding shared state, muatble data and side effects. COntrast with object oriented programming hwere application state is usually shared and colocated with methods in objects.
In [223]:
import itertools
import operator
data = [3,4,6,1,9,0,7,5,8]
print(data)
In [221]:
# Accumulate -> To make a iterator that returns accumulated sums
list(itertools.accumulate(data, func=operator.add))
Out[221]:
In [225]:
# Chain -> Make an iterator that returns elements from first iterable until it is exhausted.
list1 = [1,2,3,'a']
list2 = ['b', 'c', 'd']
list(itertools.chain(list1, list2))
Out[225]:
In [ ]:
# Combinations -> Returns subsequences of length r from input iterables
list(itertools.combinations(data,3))
In [ ]:
# Combinations with replacements
list(itertools.combinations_with_replacement(data, 3))
In [ ]:
# cycle -> To cycle through the sequence. Note it is infinte
These were some of the iterators. I did not get into the glory details of the topic as data science does not require them. And any other functions that I did not dicuss are because they are not used in data science and deep learning.