Python Functions
Top Python Interview Questions
##################################################################
##of the consecutive letters will be replaced by the numbers of the letter
##Sample Input : aaabbbccedf
##Sample Output: a2b2c1edf
##################################################################
def encode(string):
newStr = ''
i=0
tmp=[]
for ele in string:
if ele in tmp:
i+=1
else:
if i != 0:
newStr = newStr+str(i)
i=0
tmp=[]
tmp.append(ele)
newStr=newStr+ele
return newStr
##################################################################
##of sequense from 1 to N .
## Sample Input: [1,2,4,7,9,3,5,5,8,6]
## Sample Output: 5
##################################################################
return sum(arr)-(len(arr)*(len(arr)-1))/2
##################################################################
##This function will return the integer which occurred in the list only once
##Sample Input : [1,2,3,4,4,3,2]
##Sample Output: 1
##################################################################
##################################################################
def loanlyInt(arr):
ans = 0for ele in arr:
ans = ans ^ ele
return ans
##################################################################
##A Binary Search Tree
class Node:
def __init__(self,nodeData):
self.data, self.left, self.right = nodeData, None, None
class BST(Node):
def __init__(self):
self.head = None
def traverseLeft(self,cur_node):
if cur_node.left != None:
return self.traverseLeft(cur_node.left)
else:
return cur_node
def traverseRight(self,cur_node):
if cur_node.right != None:
return self.traverseRight(cur_node.right)
else:
return cur_node
def traverseLeaf(self,cur_leaf,new_node):
if new_node.data <= cur_leaf.data:
if cur_leaf.left == None:
cur_leaf.left = new_node
return
else:
return self.traverseLeaf(cur_leaf.left, new_node)
else:
if cur_leaf.right == None:
cur_leaf.right = new_node
return
else:
return self.traverseLeaf(cur_leaf.right, new_node)
def insertLeaf(self,nodeData):
new_node = Node(nodeData)
if self.head==None:
self.head = new_node
else:
self.traverseLeaf(self.head,new_node)
def main():
bst = BST()
bst.insertLeaf(3)
bst.insertLeaf(3)
main()
##################################################################
def __init__(self,nodeData):
self.data, self.left, self.right = nodeData, None, None
class BST(Node):
def __init__(self):
self.head = None
def traverseLeft(self,cur_node):
if cur_node.left != None:
return self.traverseLeft(cur_node.left)
else:
return cur_node
def traverseRight(self,cur_node):
if cur_node.right != None:
return self.traverseRight(cur_node.right)
else:
return cur_node
def traverseLeaf(self,cur_leaf,new_node):
if new_node.data <= cur_leaf.data:
if cur_leaf.left == None:
cur_leaf.left = new_node
return
else:
return self.traverseLeaf(cur_leaf.left, new_node)
else:
if cur_leaf.right == None:
cur_leaf.right = new_node
return
else:
return self.traverseLeaf(cur_leaf.right, new_node)
def insertLeaf(self,nodeData):
new_node = Node(nodeData)
if self.head==None:
self.head = new_node
else:
self.traverseLeaf(self.head,new_node)
def main():
bst = BST()
bst.insertLeaf(3)
bst.insertLeaf(3)
main()
##################################################################
##This function will convert a interger to binary
##Sample Imput: 8
##Sample Output : 1000
##################################################################
def binary(N):
binStr = ""
while (N>0):
binStr = str(N%2) + binStr
N = N/2
return binStr
##################################################################
##This function will convert an binary to Decimal
##Smpple Input: 1000
##Sample Output: 8
##################################################################
def binaryToDecimal(binStr):
N = 0
j = 0
for i in range(len(binStr)-1,-1,-1):
N = N + int(binStr[i]) * 2**j
j+=1
return N
##################################################################
##This method will return a list of prime numbers in a given range N.
##Sample Input : 10
##Sample Output : [2,3,5,7]
##################################################################
def genPrime(N):
return [2,3,5] + [i for i in range(6,N) if i%2 !=0 and i%3 !=0 and i%5 !=0]
##################################################################
##Linked List
##################################################################
class Node:
def __init__(self):
self.data = None
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def seekLastNode(self,cur_node):
if cur_node.next == None:
return cur_node
else:
return self.seekLastNode(cur_node.next)
def traverseLinkedList(self,cur_node):
if cur_node.next != None:
print "|%s|next->" %cur_node.data,
return self.traverseLinkedList(cur_node.next)
else:
print "|%s|" %cur_node.data,
def insertNode(self,node_data):
node = Node()
node.data = node_data
if self.head == None:
self.head = node
else:
last_node = self.seekLastNode(self.head)
last_node.next = node
def main():
l = LinkedList()
l.insertNode(4)
l.insertNode(8)
l.insertNode(12)
l.insertNode(44)
l.insertNode(21)
l.insertNode(43)
l.insertNode(55)
l.insertNode(9)
l.traverseLinkedList(l.head)
main()
##Output: |4|next-> |8|next-> |12|next-> |44|next-> |21|next-> |43|next-> |55|next-> |9|
##What is so unique about the Python List
like C the array is not required to set the size while initializing, the size of the python list increases as the numbers are added to the python list.
>>> import sys
>>> a=[]
>>> sys.getsizeof(a)
72
>>> a.append(1)
>>> sys.getsizeof(a)
104
>>> a.append(1)
>>> sys.getsizeof(a)
104
>>> a.append(1)
>>> sys.getsizeof(a)
104
>>> a.append(1)
>>> sys.getsizeof(a)
104
>>> 104-72
32
>>> a.append(1)
>>> sys.getsizeof(a)
136
>>> 136-104
32
>>>
##################################################################
##Singleton Class Implementation
##################################################################
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@singleton
class MyClass:
pass
import sys
a = MyClass()
b = MyClass()
print id(a)
print id(b)
##################################################################
##Decorators
##################################################################
def decorator(argFunction):
def inner(*args,**kwargs):
print "Pre Decoration"
argFunction(*args, **kwargs)
print "Post Decor"
return inner
@decorator
def mainFunc(arg1,arg2):
print arg1,arg2
mainFunc(1,2)
def mainNew(a,b,c):
print a,b,c
decMainNew = decorator(mainNew)
decMainNew(1,2,3)
########################################################################
Static and Class Methods
class Test:
def __init__(self):
pass
def __setattr__(self,attr,val):
print "hereeeeeeeeeeeeeeee"
self.__dict__[attr]=val
return
for key,value in t.__dict__.iteritems():
print key,value
##Decorators
##################################################################
def decorator(argFunction):
def inner(*args,**kwargs):
print "Pre Decoration"
argFunction(*args, **kwargs)
print "Post Decor"
return inner
@decorator
def mainFunc(arg1,arg2):
print arg1,arg2
mainFunc(1,2)
def mainNew(a,b,c):
print a,b,c
decMainNew = decorator(mainNew)
decMainNew(1,2,3)
########################################################################
Static and Class Methods
class A(object):
def foo(self,x):
print "executing foo(%s,%s)"%(self,x)
@classmethod
def class_foo(cls,x):
print "executing class_foo(%s,%s)"%(cls,x)
@staticmethod
def static_foo(x):
print "executing static_foo(%s)"%x
a=A()
Below is the usual way an object instance calls a method. The object instance,
a
, is implicitly passed as the first argument.a.foo(1)
# executing foo(<__main__.A object at 0xb7dbef0c>,1)
With classmethods, the class of the object instance is implicitly passed as the first argument instead of
self
.a.class_foo(1)
# executing class_foo(<class '__main__.A'>,1)
You can also call
class_foo
using the class. In fact, if you define something to be a classmethod, it is probably because you intend to call it from the class rather than from a class instance. A.foo(1)
would have raised a TypeError, but A.class_foo(1)
works just fine:A.class_foo(1)
# executing class_foo(<class '__main__.A'>,1)
One use people have found for class methods is to create inheritable alternative constructors.
With staticmethods, neither
self
(the object instance) nor cls
(the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:a.static_foo(1)
# executing static_foo(1)
A.static_foo('hi')
# executing static_foo(hi)
Staticmethods are used to group functions which have some logical connection with a class to the class.
foo
is just a function, but when you call a.foo
you don't just get the function, you get a "partially applied" version of the function with the object instance a
bound as the first argument to the function. foo
expects 2 arguments, while a.foo
only expects 1 argument.a
is bound to foo
. That is what is meant by the term "bound" below:print(a.foo)
# <bound method A.foo of <__main__.A object at 0xb7d52f0c>>
With
a.class_foo
, a
is not bound to class_foo
, rather the class A
is bound to class_foo
.print(a.class_foo)
# <bound method type.class_foo of <class '__main__.A'>>
Here, with a staticmethod, even though it is a method,
a.static_foo
just returns a good 'ole function with no arguments bound. static_foo
expects 1 argument, and a.static_foo
expects 1 argument too.print(a.static_foo)
# <function static_foo at 0xb7d479cc>
And of course the same thing happens when you call
static_foo
with the class A
instead.print(A.static_foo)
# <function static_foo at 0xb7d479cc>
#############################################################################
## __getarrt__, __setattr__
#############################################################################
def __init__(self):
pass
def __setattr__(self,attr,val):
print "hereeeeeeeeeeeeeeee"
self.__dict__[attr]=val
return
The above code will set the attributes, for the objects
t=Test()
t.x=25
Get all the the attributes on an object
print t.__dict__for key,value in t.__dict__.iteritems():
print key,value
Comments
Post a Comment