Sie sind auf Seite 1von 27

What is Hashing?

Hashing is an algorithm that compresses data of any arbitrary length to a fixed


length.
------------------------------------------------------------
The exec() method executes the dynamically created program, which is either a
string or a code object.
The syntax of exec();

exec(object, globals, locals)


program = 'a = 5\nb=10\nprint("Sum =", a+b)'
exec(program)

program = input('Enter a program:')


exec(program)
If you want to take Python code from the user which allows multiline code (using
'\n'), you can use compile() method before using exec().

from math import *


exec('print(dir())')
['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__name__', '_dh',
'_i', '_i1', '_i2', '_ih', '_ii', '_iii', '_oh', '_sh', 'acos', 'acosh', 'asin',
'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees',
'e', 'erf', 'erfc', 'exit', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod',
'frexp', 'fsum', 'gamma', 'gcd', 'get_ipython', 'hypot', 'inf', 'isclose',
'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2',
'modf', 'nan', 'pi', 'pow', 'quit', 'radians', 'sin', 'sinh', 'sqrt', 'tan',
'tanh', 'trunc']
----------------------------------------------------------------
Memory management in Python:
Memory management in Python involves a private heap containing all Python objects
and data structures. The management of this private heap is ensured internally by
the Python memory manager. The Python memory manager has different components which
deal with various dynamic storage management aspects, like sharing, segmentation,
preallocation or caching.

At the lowest level, a raw memory allocator ensures that there is enough room in
the private heap for storing all Python-related data by interacting with the memory
manager of the operating system
---------------------------------------------------------------
common in two files
file1 = set(line.strip() for line in open('file1.txt'))
file2 = set(line.strip() for line in open('file2.txt'))

for line in file1 & file2:


if line:
print line

------------------------------------------------------------------
The re.sub() function in the re module can be used to replace substrings.

The syntax for re.sub() is re.sub(pattern,repl,string).

That will replace the matches in string with repl.

In this example, I will replace all occurrences of the re pattern ("cool")


in string (text) with repl ("good").
-----------------------------------------------------
import re
programming = ["Python", "Perl", "PHP", "C++"]

pat = "^B|^P|i$|H$"

for lang in programming:

if re.search(pat,lang,re.IGNORECASE):
print lang , "FOUND"

else:
print lang, "NOT FOUND"
-----------------------------------------------------
How Python Differs from Other Languages
Python is easy to learn.
Python is good for statring out because the syntax of Python is very simple and
understandable.
We can create GUI and CGI in few lines of code.
Who uses Python?

Python is used for developing many popular Web products


Youtube.
Google.
Yahoo! map.
Shopzilla.
Ultraseek.
Comparing Python With Other Languages

Python is compared with the mostly liked programming languages such as Java,
JavaScript, Tcl, Perl, Smalltall and C++ also.
We will find Python is a good language for development

Python vs Java

Point of Difference Python


Java
Program run time Python program runs slower than Java
Java program runs faster than python
Program development time Takes less time than Java
Takes more time for developing same program
Length of the code Python code is 3-5 times shorter than Java code
Java code is longer than Python
Type Python is dynamically typed
Java is not dynamically typed
-----------------------------------------------------------------------------------
----------
In case of shallow copy, a reference of object is copied in other object. It means
that any changes made to a copy of object do reflect in the original object.

In case of deep copy, a copy of object is copied in other object. It means that any
changes made to a copy of object do not reflect in the original object.
-----------------------------------------------------------------------------------
-----------
Python�s model is neither �call by value� nor �call by reference� (because any
attempt to use those terms for Python requires you to use non-standard definitions
of the words �-value� and �-reference�). The most accurate description is CLU�s
�call by object� or �call by sharing�. Or, if you prefer, �call by object
reference�.
-----------------------------------------------
�Pickling� is the process whereby a Python object hierarchy is converted into a
byte stream
--------------------------------------
from decimal import Decimal
def pyramid_o(n):
k=1
while k < n:
for i in range(1,n+1):
for j in range(1,i+1):
print k,
k=k+1
print "\n"
pyramid_o(4)

2 3

4 5 6

7 8 9 10

from decimal import Decimal


def pyramid_o(n):
k=1
while k < n:
for i in range(1,n+1):
for j in range(1,i+1):
print j,
k=k+1
print "\n"
pyramid_o(4)

1 2

1 2 3

1 2 3 4

from decimal import Decimal


def pyramid_o(n):
k=1
while k < n:
for i in range(1,n+1):
for j in range(1,i+1):
print i,
k=k+1
print "\n"
pyramid_o(4)

2 2

3 3 3

4 4 4 4
#To get value for ('abc','de','f') -> d+e=f,a+b=d,b+c=e
from decimal import Decimal
def f(z,y,x):
if z[1]=="?":
print "? found"
if y[0]=='?':
print "? found"
m=(Decimal(x[0])+Decimal(y[1]))%10
n=m-Decimal(z[0])
p=Decimal(y[1])-n
print m,n,p
f('4??','?2','3')

#customer's message, and an array of items that they can order

import re
from decimal import Decimal
def orderAmount(stg,msg):
s=[m.start() for m in re.finditer(stg, msg)]
#print s
t=[]
for i in s:
k=msg[i-2]
t.append(k)
print t
print sum(Decimal(i) for i in t)

#orderAmount("apples","Please send me 3 apples and 2 oranges")


orderAmount("apples","4 apples 5 apples 6 b 7 d")
9

https://www.youtube.com/watch?v=7lmCu8wz8ro
metaclasses: 18:50
metaclasses(explained): 40:40
decorator: 45:20
generator: 1:04:30
context manager: 1:22:37
summary: 1:40:00

What Does It Take to Be An Expert At Python


Notebook based off James Powell's talk at PyData 2017'
https://www.youtube.com/watch?v=7lmCu8wz8ro
If you want to become an expert in Python, you should definitely watch this PyData
talk from James Powell.
Video Index
metaclasses: 18:50
metaclasses(explained): 40:40
decorator: 45:20
generator: 1:04:30
context manager: 1:22:37
summary: 1:40:00
Definitions Python is a language orientated around protocols - Some behavior or
syntax or bytecode or some top level function and there is a way to tell python how
to implement that on an arbitrary object via underscore methods. The exact
correspondance is usually guessable, but if you can't guess it you can it... google
python data model
Metaclass Mechanism: Some hook into the class construction process. Questions: Do
you have these methods implemented. Meaning: Library code & User code? How do you
enforce a constraint?
Decorator Hooks into idea that everything creates a structure at run time. Wrap
sets of functions with a before and after behavior.
Generators Take a single computation that would otherwise run eagerly from the
injection of its parameters to the final computation and interleaving with other
code by adding yield points where you can yield the intermediate result values or
one small piece of the computation and also yield back to the caller. Think of a
generator of a way to take one long piece of computation and break it up into small
parts.
Context managers Two structures that allow you to tie two actions together. A setup
action and a teardown action and make sure they always happen in concordance with
each other.
In [7]:
# some behavior that I want to implement -> write some __ function __
# top-level function or top-level syntax -> corresponding __
# x + y -> __add__
# init x -> __init__
# repr(x) --> __repr__
# x() -> __call__

class Polynomial:
def __init__(self, *coeffs):
self.coeffs = coeffs

def __repr__(self):
return 'Polynomial(*{!r})'.format(self.coeffs)

def __add__(self, other):


return Polynomial(*(x + y for x, y in zip(self.coeffs, other.coeffs)))

def __len__(self):
return len(self.coeffs)

def __call__(self):
pass
3 Core Patterns to understand object orientation
Protocol view of python
Built-in inheritance protocol (where to go)
Caveats around how object orientation in python works
In [8]:
p1 = Polynomial(1, 2, 3)
p2 = Polynomial(3, 4, 3)
In [9]:
p1 + p2
Out[9]:
Polynomial(*(5, 7, 7))
In [10]:
len(p1)
Out[10]:
3
Metaclasses
In [26]:
# File 1 - library.py

class Base:
def food(self):
return 'foo'
In [27]:
# File2 - user.py
assert hasattr(Base, 'foo'), "you broke it, you fool!"

class Derived(Base):
def bar(self):
return self.foo
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-27-08fa6af0fb76> in <module>()
1 # File2 - user.py
2
----> 3 assert hasattr(Base, 'foo'), "you broke it, you fool!"
4
5 class Derived(Base):

AssertionError: you broke it, you fool!


In [41]:
# File 1 - library.py

class Base:
def foo(self):
return self.bar()
In [42]:
# File2 - user.py

assert hasattr(Base, 'foo'), "you broke it, you fool!"

class Derived(Base):
def bar(self):
return 'bar'
In [45]:
Derived.bar
Out[45]:
<function __main__.Derived.bar>
In [18]:
def _():
class Base:
pass

from dis import dis


In [19]:
dis(_) # LOAD_BUILD_CLASS
2 0 LOAD_BUILD_CLASS
2 LOAD_CONST 1 (<code object Base at 0x10f2daed0, file
"<ipython-input-18-a194b247271c>", line 2>)
4 LOAD_CONST 2 ('Base')
6 MAKE_FUNCTION 0
8 LOAD_CONST 2 ('Base')
10 CALL_FUNCTION 2
12 STORE_FAST 0 (Base)
14 LOAD_CONST 0 (None)
16 RETURN_VALUE
In [165]:
# Catch Building of Classes

class Base:
def foo(self):
return self.bar()

old_bc = __build_class__
def my_bc(*a, **kw):
print('my buildclass ->', a, kw)
return old_bc(*a, **kw)
import builtins
builtins.__build_class__ = my_bc
In [1]:
# Catch Building of Classes

class Base:
def foo(self):
return self.bar()

old_bc = __build_class__
def my_bc(fun, name, base=None, **kw):
if base is Base:
print('Check if bar method defined')
if base is not None:
return old_bc(fun, name, base, **kw)
return old_bc(fun, name, **kw)

import builtins
builtins.__build_class__ = my_bc
In [80]:
import builtins
In [79]:
import importlib
importlib.reload(builtins)
Out[79]:
<module 'builtins' (built-in)>
In [2]:
class BaseMeta(type):
def __new__(cls, name, bases, body):
print('BaseMeta.__new__', cls, name, bases, body)
return super().__new__(cls, name, bases, body)

class Base(metaclass=BaseMeta):
def foo(self):
return self.bar()
BaseMeta.__new__ <class '__main__.BaseMeta'> Base () {'__module__': '__main__',
'__qualname__': 'Base', 'foo': <function Base.foo at 0x107378048>}
In [167]:
class BaseMeta(type):
def __new__(cls, name, bases, body):
if not 'bar' in body:
raise TypeError('bad user class')
return super().__new__(cls, name, bases, body)

class Base(metaclass=BaseMeta):
def foo(self):
return self.bar()
my buildclass -> (<function BaseMeta at 0x10749cf28>, 'BaseMeta', <class 'type'>)
{}
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-167-f2133308a9ce> in <module>()
----> 1 class BaseMeta(type):
2 def __new__(cls, name, bases, body):
3 if not 'bar' in body:
4 raise TypeError('bad user class')
5 return super().__new__(cls, name, bases, body)

<ipython-input-165-f7e591caa0e8> in my_bc(*a, **kw)


8 def my_bc(*a, **kw):
9 print('my buildclass ->', a, kw)
---> 10 return old_bc(*a, **kw)
11 import builtins
12 builtins.__build_class__ = my_bc

<ipython-input-1-8d1486f0ff44> in my_bc(fun, name, base, **kw)


10 print('Check if bar method defined')
11 if base is not None:
---> 12 return old_bc(fun, name, base, **kw)
13 return old_bc(fun, name, **kw)
14

... last 1 frames repeated, from the frame below ...

<ipython-input-1-8d1486f0ff44> in my_bc(fun, name, base, **kw)


10 print('Check if bar method defined')
11 if base is not None:
---> 12 return old_bc(fun, name, base, **kw)
13 return old_bc(fun, name, **kw)
14

RecursionError: maximum recursion depth exceeded


In [5]:
class BaseMeta(type):
def __new__(cls, name, bases, body):
if name != 'Base' and not 'bar' in body:
raise TypeError('bad user class')
return super().__new__(cls, name, bases, body)

class Base(metaclass=BaseMeta):
def foo(self):
return self.bar()

def __init_subclass__(*a, **kw):


print('init_subclass', a, kw)
return super().__init_subclass__(*a, **kw)
In [8]:
help(Base.__init_subclass__)
Help on method __init_subclass__ in module __main__:

__init_subclass__(*a, **kw) method of __main__.BaseMeta instance


This method is called when a class is subclassed.

The default implementation does nothing. It may be


overridden to extend subclasses.

Decorators
In [12]:
# dec.py
In [77]:
def add(x, y=10):
return x + y
In [14]:
add(10, 20)
Out[14]:
30
In [15]:
add
Out[15]:
<function __main__.add>
In [28]:
# Name of function
add.__name__
Out[28]:
'add'
In [27]:
# What module function is assigned to
add.__module__
Out[27]:
'__main__'
In [26]:
# Default values
add.__defaults__
Out[26]:
(10,)
In [25]:
# Byte code for function
add.__code__.co_code
Out[25]:
b'|\x00|\x01\x17\x00S\x00'
In [24]:
# Variable names function interacts with
add.__code__.co_varnames
Out[24]:
('x', 'y')
What's your source code?
In [31]:
from inspect import getsource
In [32]:
getsource(add)
Out[32]:
'def add(x, y=10):\n return x + y\n'
In [33]:
print(getsource(add))
def add(x, y=10):
return x + y

In [35]:
# What file are you in?
from inspect import getfile
getfile(add)
Out[35]:
'<ipython-input-19-3cec442ba064>'
In [37]:
from inspect import getmodule
getmodule(add)
Out[37]:
<module '__main__'>
In [38]:
print('add(10)', add(10))
print('add(20, 30)', add(20, 30))
print('add("a", "b")', add("a", "b"))
add(10) 20
add(20, 30) 50
add("a", "b") ab
In [40]:
#Count how long it took to run
In [41]:
def add_timer(x, y=10):
before = time()
rv = x + y
after = time()
print('elapsed:', after - before)
return rv
In [42]:
print('add(10)', add_timer(10))
print('add(20, 30)', add_timer(20, 30))
print('add("a", "b")', add_timer("a", "b"))
elapsed: 0.0
add(10) 20
elapsed: 9.5367431640625e-07
add(20, 30) 50
elapsed: 9.5367431640625e-07
add("a", "b") ab
But what if we have multiple functions that require timing?
In [49]:
def sub(x, y=10):
return x - y
In [46]:
print('sub(10)', sub(10))
print('sub(20, 30)', sub(20, 30))
sub(10) 0
sub(20, 30) -10
In [55]:
def timer(func, x, y=10):
before = time()
rv = func(x, y)
after = time()
print('elapsed', after - before)
return rv
In [56]:
print('add(10)', timer(add, 10))
print('add(20, 30)', timer(add, 20, 30))
print('add("a", "b"', timer(add, "a", "b"))
elapsed 9.5367431640625e-07
add(10) 20
elapsed 9.5367431640625e-07
add(20, 30) 50
elapsed 9.5367431640625e-07
add("a", "b") ab
In [74]:
def timer(func):
def f(x, y=10):
before = time()
rv = func(x, y)
after = time()
print('elapsed', after - before)
return rv
return f
In [78]:
add = timer(add)
In [79]:
print('add(10)', add(10))
print('add(20, 30)', add(20, 30))
print('add("a", "b")', add("a", "b"))
elapsed 9.5367431640625e-07
add(10) 20
elapsed 9.5367431640625e-07
add(20, 30) 50
elapsed 9.5367431640625e-07
add("a", "b") ab
In [80]:
# Don't need to do add = timer(add) with decorators...
In [87]:
@timer
def add_dec(x, y=10):
return x + y

@timer
def sub_dec(x, y=10):
return x - y
In [88]:
print('add(10)', add_dec(10))
print('add(20, 30)', add_dec(20, 30))
print('add("a", "b")', add_dec("a", "b"))
print('sub(10)', sub_dec(10))
print('sub(20, 30)', sub_dec(20, 30))
elapsed 9.5367431640625e-07
add(10) 20
elapsed 1.1920928955078125e-06
add(20, 30) 50
elapsed 1.1920928955078125e-06
add("a", "b") ab
elapsed 9.5367431640625e-07
sub(10) 0
elapsed 0.0
sub(20, 30) -10
In [91]:
# Don't hardcode parameters in decorator functions
def timer_k(func):
def f(*args, **kwargs):
before = time()
rv = func(*args, **kwargs)
after = time()
print('elapsed', after - before)
return rv
return f
In [92]:
@timer_k
def add_dec(x, y=10):
return x + y

@timer_k
def sub_dec(x, y=10):
return x - y

print('add(10)', add_dec(10))
print('add(20, 30)', add_dec(20, 30))
print('add("a", "b")', add_dec("a", "b"))
print('sub(10)', sub_dec(10))
print('sub(20, 30)', sub_dec(20, 30))
elapsed 9.5367431640625e-07
add(10) 20
elapsed 9.5367431640625e-07
add(20, 30) 50
elapsed 9.5367431640625e-07
add("a", "b") ab
elapsed 0.0
sub(10) 0
elapsed 9.5367431640625e-07
sub(20, 30) -10
In [93]:
# What if I want to run a function n number of times
In [94]:
# Let's have add run 3 times in a row and sub run twice in a row
In [97]:
n = 2

def ntimes(f):
def wrapper(*args, **kwargs):
for _ in range(n):
print('running {.__name__}'.format(f))
rv = f(*args, **kwargs)
return rv
return wrapper

@ntimes
def add_dec(x, y=10):
return x + y

@ntimes
def sub_dec(x, y=10):
return x - y
In [98]:
print('add(10)', add_dec(10))
print('add(20, 30)', add_dec(20, 30))
print('add("a", "b")', add_dec("a", "b"))
print('sub(10)', sub_dec(10))
print('sub(20, 30)', sub_dec(20, 30))
running add_dec
running add_dec
add(10) 20
running add_dec
running add_dec
add(20, 30) 50
running add_dec
running add_dec
add("a", "b") ab
running sub_dec
running sub_dec
sub(10) 0
running sub_dec
running sub_dec
sub(20, 30) -10
Higher Order Decorators
In [103]:
def ntimes(n):
def inner(f):
def wrapper(*args, **kwargs):
for _ in range(n):
print('running {.__name__}'.format(f))
rv = f(*args, **kwargs)
return rv
return wrapper
return inner

@ntimes(2)
def add_hdec(x, y=10):
return x + y

@ntimes(4)
def sub_hdec(x, y=10):
return x - y
In [104]:
print('add(10)', add_hdec(10))
print('add(20, 30)', add_hdec(20, 30))
print('add("a", "b")', add_hdec("a", "b"))
print('sub(10)', sub_hdec(10))
print('sub(20, 30)', sub_hdec(20, 30))
running add_hdec
running add_hdec
add(10) 20
running add_hdec
running add_hdec
add(20, 30) 50
running add_hdec
running add_hdec
add("a", "b") ab
running sub_hdec
running sub_hdec
running sub_hdec
running sub_hdec
sub(10) 0
running sub_hdec
running sub_hdec
running sub_hdec
running sub_hdec
sub(20, 30) -10
Generators
In [105]:
# gen.py - use whenever sequencing is needd
In [109]:
# top-level syntax, function -> underscore method
# x() __call__

def add1(x, y):


return x + y

class Adder:
def __call__(self, x, y):
return x + y
add2 = Adder()
In [110]:
add1(10, 20)
Out[110]:
30
In [111]:
add2(10, 20)
Out[111]:
30
In [113]:
# top-level syntax, function -> underscore method
# x() __call__

def add1(x, y):


return x + y

class Adder:
def __init__(self):
self.z = 0

def __call__(self, x, y):


self.z += 1
return x + y + self.z

add2 = Adder()
In [130]:
from time import sleep
# This example has storage... and has eager return of the result sets
def compute():
rv = []
for i in range(10):
sleep(.5)
rv.append(i)
return rv
In [120]:
compute()
Out[120]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Wasteful because we have to wait for the entire action to complete and be read into
memory, when we really just care about each number (one by one)
In [129]:
class Compute:
def __call__(self):
rv = []
for i in range(100000):
sleep(5)
rv.append(i)
return rv

def __iter__(self):
self.last = 0
return self

def __next__(self):
rv = self.last
self.last += 1
if self.last > 10:
raise StopIteration()
sleep(.5)
return self.last

compute = Compute()

# THIS IS UGLY... now let's make a generator


In [131]:
#This is a generator... don't eagerly compute. Return to user as they ask for it...
def compute():
for i in range(10):
sleep(.5)
yield i
In [125]:
# for x in xs:
# pass

# xi = iter(xs) -> __iter__


# while True:
# x = next(xi) -> __next__
In [136]:
for val in compute():
print(val)
0
1
2
3
4
5
6
7
8
9
In [133]:
class Api:
def run_this_first(self):
first()
def run_this_second(self):
second()
def run_this_last(self):
last()
In [137]:
def api():
first()
yield
second()
yield
last()
Context Manager
In [2]:
# cty.py

from sqlite3 import connect


In [156]:
# with ctx() as x:
# pass

# x = ctx().__enter__
# try:
# pass
# finally:
# x.__exit__

class temptable:
def __init__(self, cur):
self.cur = cur
def __enter__(self):
print('__enter__')
self.cur.execute('create table points(x int, y int)')
def __exit__(self, *args):
print('__exit__')
self.cur.execute('drop table points')

with connect('test.db') as conn:


cur = conn.cursor()
with temptable(cur):
cur.execute('insert into points (x, y) values(1, 1)')
cur.execute('insert into points (x, y) values(1, 2)')
cur.execute('insert into points (x, y) values(2, 1)')
cur.execute('insert into points (x, y) values(2, 2)')
for row in cur.execute("select x, y from points"):
print(row)
for row in cur.execute('select sum(x * y) from points'):
print(row)
__enter__
(1, 1)
(1, 2)
(2, 1)
(2, 2)
(9,)
__exit__
In [162]:
rm test.db
In [164]:
def temptable(cur):
cur.execute('create table points(x int, y int)')
print('created table')
yield
cur.execute('drop table points')
print('dropped table')

class contextmanager:
def __init__(self, cur):
self.cur = cur
def __enter__(self):
self.gen = temptable(self.cur)
next(self.gen)
def __exit__(self, *args):
next(self.gen, None)

with connect('test.db') as conn:


cur = conn.cursor()
with contextmanager(cur):
cur.execute('insert into points (x, y) values(1, 1)')
cur.execute('insert into points (x, y) values(1, 2)')
cur.execute('insert into points (x, y) values(2, 1)')
cur.execute('insert into points (x, y) values(2, 2)')
for row in cur.execute("select x, y from points"):
print(row)
for row in cur.execute('select sum(x * y) from points'):
print(row)
created table
(1, 1)
(1, 2)
(2, 1)
(2, 2)
(9,)
dropped table
In [8]:
class contextmanager:
def __init__(self, gen):
self.gen = gen
def __call__(self, *args, **kwargs):
self.args, self.kwargs = args, kwargs
return self
def __enter__(self):
self.gen_inst = self.gen(*self.args, **self.kwargs)
next(self.gen_inst)
def __exit__(self, *args):
next(self.gen_inst, None)

def temptable(cur):
cur.execute('create table points(x int, y int)')
print('created table')
yield
cur.execute('drop table points')
print('dropped table')
temptable = contextmanager(temptable)

with connect('test.db') as conn:


cur = conn.cursor()
with temptable(cur):
cur.execute('insert into points (x, y) values(1, 1)')
cur.execute('insert into points (x, y) values(1, 2)')
cur.execute('insert into points (x, y) values(2, 1)')
cur.execute('insert into points (x, y) values(2, 2)')
for row in cur.execute("select x, y from points"):
print(row)
created table
(1, 1)
(1, 2)
(2, 1)
(2, 2)
dropped table
In [12]:
class contextmanager:
def __init__(self, gen):
self.gen = gen
def __call__(self, *args, **kwargs):
self.args, self.kwargs = args, kwargs
return self
def __enter__(self):
self.gen_inst = self.gen(*self.args, **self.kwargs)
next(self.gen_inst)
def __exit__(self, *args):
next(self.gen_inst, None)

@contextmanager
def temptable(cur):
cur.execute('create table points(x int, y int)')
print('created table')
yield
cur.execute('drop table points')
print('dropped table')
with connect('test.db') as conn:
cur = conn.cursor()
with temptable(cur):
cur.execute('insert into points (x, y) values(1, 1)')
cur.execute('insert into points (x, y) values(1, 2)')
cur.execute('insert into points (x, y) values(2, 1)')
cur.execute('insert into points (x, y) values(2, 2)')
for row in cur.execute("select x, y from points"):
print(row)
created table
(1, 1)
(1, 2)
(2, 1)
(2, 2)
dropped table
In [15]:
from sqlite3 import connect
from contextlib import contextmanager

@contextmanager
def temptable(cur):
cur.execute('create table points(x int, y int)')
print('created table')
try:
yield
finally:
cur.execute('drop table points')
print('dropped table')

with connect('test.db') as conn:


cur = conn.cursor()
with temptable(cur):
cur.execute('insert into points (x, y) values(1, 1)')
cur.execute('insert into points (x, y) values(1, 2)')
cur.execute('insert into points (x, y) values(2, 1)')
cur.execute('insert into points (x, y) values(2, 2)')
for row in cur.execute("select x, y from points"):
print(row)
created table
(1, 1)
(1, 2)
(2, 1)
(2, 2)
dropped table

#password generator
import string
import random
def password1():
p1=random.choice(string.ascii_lowercase)
p2=random.choice(string.ascii_uppercase)
p3=random.choice(string.digits)
p4=random.choice(string.punctuation)
p5=random.choice(string.printable)
p6=random.choice(string.printable)
p7=random.choice(string.printable)
p8=random.choice(string.printable)
x=str(p1)+str(p2)+str(p3)+str(p4)+str(p5)+str(p6)+str(p7)+str(p8)
y=list(x)
random.shuffle(y)
p=''.join(y)
return p
z=password1()
print z

#All Printable
import string
for i in string.printable:
print i,

#Cities with position


cities=['a','b','c','d','e']
j=1
for i in cities:
print i +" has the position "+str(j)
j += 1
or
#Cities with position
cities=['a','b','c','d','e']
for i,city in enumerate(cities):
print city +" has the position "+str(i)

#Dealing with 2 lists to get values in column


states =['a','b','c','d','e']
capital=['x','y','z','k','l']
for i in range(len(states)):
s=states[i]
c=capital[i]
print c +" is the capital of "+s
or
#Dealing with 2 lists to get values in column
states =['a','b','c','d','e']
capital=['x','y','z','k','l']
for s,c in zip(states,capital):
print c +" is the capital of "+s

#Swap two variables


x=10
y=-20
print "x=%d and y=%d" % (x,y)
x,y=y,x
print "x=%d and y=%d" % (x,y)

#To use default value of Dict


#Find 'c' age if it is in x Dict
x={'a':10,'b':20,'c':30}
age=x.get('c','Unknown')
print "age of 'c' is "+str(age)
#If not in the x Dict
x={'a':10,'b':20}
age=x.get('c','Unknown')
print "age of 'c' is "+str(age)

#To find a value in a list(for ..else is used as loop has to be completed)


x=['a','b','c']
for i in x:
if 'd' == i:
print "found"
break
else:
print "not found"

#To open and print a textfile(To open and automatic close of file)
with open('new_file.txt') as f:
for i in f:
print i

#Convert string to int using try..except..else block


strn=raw_input("Give a string to convert: ")
try:
i=int(strn)
except:
print "Not convertible"
else:
print "Successfully converted to int " + str(i)
finally:
print "DONE"

https://www.programiz.com/python-programming/examples
def add(x,y):
a=x+y
return a
z=add(8,10)
print z

def sqrt(x):
y=x**(.5)
return y
z=sqrt(16)
print z

def area_triangle(a,b,c):
s=(a+b+c)/2
return (s*(s-a)*(s-b)*(s-c))**(0.5)
z=area_triangle(4,4,4)
print z

def eq_soln(a,b,c):
s=(b**2) - (4*a*c)
if s > 0:
k=2*a
t=s/k
l=t**(.5)
else:
s=-s
k=2*a
t=s/k
l=t**(.5)
return l,-l
z=eq_soln(1,2,3)
print z

def swap(a,b):
x=a
a=b
b=x
return a,b
z=swap(1,2)
print z

import random
def random1():
z= random.randint(0,9)
return z
z=random1()
print z

def pos_neg_zero(x):
if x > 0:
return "positive"
elif x < 0:
return "negative"
else:
return "zero"

z=pos_neg_zero(-9)
print z

def odd_or_even(x):
if x % 2== 0:
return "even"
else:
return "odd"

z=odd_or_even(9)
print z

def leap_year(x):
if x % 4== 0:
if x % 400 ==0:
return "not a leap year"
else:
return "leap year"

z=leap_year(2000)
print z

def largest_three(a,b,c):
return max(a,b,c)

z=largest_three(2000,3000,4000)
print z

def prime_number(x):
for i in range(2,x/2):
if (x % i) == 0:
return "composite number"
else:
return "prime number"

z=prime_number(17)
print z

def prime_no_interval(x,y):
for i in range(x,y):
for j in range(2,y/2):
if (i % j) == 0:
break
else:
print i

z=prime_no_interval(7,16)
print z

def factorial(x,factorial=1):
for i in xrange(1,x):
factorial=factorial*i
return factorial
z=factorial(6)
print z

def multable_n(n):
for i in xrange(1,11):
print "%d X %d = %d" % (n,i,n*i)
z=multable_n(7)
print z

def fibo_n(n):
if n <=1:
return n
else:
return(fibo_n(n-1) + fibo_n(n-2))
def fibo(x):
for i in range(x):
print fibo_n(i)
z=fibo(7)
print z

def print_factors(x):
for i in range(1,x+1):
if (x % i) == 0:
print i
print_factors(9)

#Random card picking from a deck of cards


import random
x=["S","D","H","C"]
y=[i for i in range(1,14)]
a=random.choice(x)
b=random.choice(y)
print str(b) + " of " + str(a)

#Copy from one list to other


def abbr(l):
j=[]
for i in l:
j.append(i)
return j

k=abbr(['a','b'])
print k

https://www.youtube.com/watch?v=p-89r5QvQvQ
Interview Questions on different companies
Thursday, August 18, 2016
11:44 PM
Tech Mahindra
Monday, February 29, 2016
11:45 PM
Mainly OOPs concepts
1. What is Class ?
2. What is inheritance ?
3. Regex to find IP address
4. Difference between extend and append? Appends object at end. Extends list
by appending elements from the iterable.
5. What is Abstract class? Use the abc module to create abstract classes. Use
the abstractmethod decorator to declare a method abstract,so inherited class can
instanitate itself.
6. Dictionary comprehension? To shorten a entire for or while loop and write
it in 1 sentence.l = [n for n in range(1, 11)]
7. What is constructor? A constructor is a special kind of method that Python
calls when it instantiates an object using the definitions found in your class. def
__init__(self, Name="there"):
self.Greeting = Name + "!"
8. What is Generator? Every generator(non reversible) is an iterator, but not
vice versa.A generator is built by calling a function that has one or more yield
expressions.iterator is a more general concept: any object whose class has a next
method (__next__ in Python 3) and an __iter__ method that does return self.
9. Difference between range() and xrange()?Same,xrange() is a generator using
less memory , to retrieve n times loop

Wipro
Saturday, June 25, 2016
11:46 PM
1. Fibonacci series
def recur_fibo(n):
"""Recursive function to
print Fibonacci sequence"""
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

2. Even numbers in a series

Nvidia [Tele]
Thursday, August 18, 2016
11:48 PM
1. What are
a. Classmethods --cls argument
b. Static methods --any argument other than cls or self --can't modify state
of either class or
c. Instance methods --self argument--can modify state of object

Class methods

A class method is one that belongs to the class as a whole. It doesn't require an
instance. Instead, the class will automatically be sent as the first argument. A
class method is declared with the @classmethod decorator.

For example:

class Foo(object):
@classmethod
def hello(cls):
print("hello from %s" % cls.__name__)
Foo.hello()
-> "Hello from Foo"
Foo().hello()
-> "Hello from Foo"
Instance Methods

On the other hand, an instance method requires an instance in order to call it, and
requires no decorator. This is by far the most common type of method.

class Foo(object):
def hello(self):
print("hello from %s" % self.__class__.__name__)
Foo.hello()
-> TypeError: hello() missing 1 required positional argument: 'self'
(note: the above is with python3; with python2 you'll get a slightly different
error)

Static methods

A static method is similar to a class method, but won't get the class object as an
automatic parameter. It is created by using the @staticmethod decorator.

class Foo(object):
@staticmethod
def hello(cls):
print("hello from %s" % cls.__name__)

Foo.hello()
-> TypeError: hello() missing 1 required positional argument: 'cls'
2. What is Package and how to create it?
3. How to find the middle of a linked list?

HCL
Saturday, July 02, 2016
11:48 PM
1. Regex for credit card number detection
2. Decorator example A decorator takes in a function, adds some functionality
and returns it.
def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner

def ordinary():
print("I am ordinary")

def smart_divide(func):
def inner(a,b):
print("I am going to divide",a,"and",b)
if b == 0:
print("Whoops! cannot divide")
return

return func(a,b)
return inner
@smart_divide
def divide(a,b):
return a/b

>>> divide(2,5)
I am going to divide 2 and 5
0.4

>>> divide(2,0)
I am going to divide 2 and 0
Whoops! cannot divide
3. Reversal of an array not using split or any function
4. IP address validation using regex
5. Code to find out how many vowels are there in a string
6. Example of a decorator function

Affine Analytics
Thursday, August 18, 2016
11:48 PM
Conducted written test with Python consists of only 10% of the question paper;
which includes Big data, Javascript etc.
Got rejected on written test and returned back.

Sungard AS [Tele]
Thursday, August 18, 2016
11:48 PM
1. When does the bytecode gets generated?
� During import of the module bytecode gets generated and we can see a .pyc
file
2. Default modules installed in Python builtin,main,os
3. What is the significance of __init__.py ? With out the presence the
collection block directory will not be considered as Package.
4. How and Why do we use Decorators in Python?
5. What will be the output of the following statement:
For I in range(3):
Pass
6. How to convert an integer to string?
use str(d) for getting string form of an integer

7. What is the difference between Tuples and Lists?


a. Tuples are immuatable
b. Tuples can be the key of a dictionary
c. Tuples are faster compared to Lists

8. How does memory management happens in Python (Heap structure)?


a. Reference count of each object has been maintained by Python
b. If the refcount becomes less than 1, that object gets deleted

9. What are the built-in types of Python ?


a. Zip
b. Reduce
c. Filter
d. map

10. Which pattern does Django support ?


a. MVC

11. What are lambda expressions?


12. Which databases have you used?
13. Did you use Unit testing ?

Snapwiz
Monday, August 22, 2016
11:30 AM
Main focus on Algorithms.
Abhishek told to focus on Algos while going for interview at Startups.
1. Asked about logic to generate random numbers
2. Logic to shuffle a pack of songs
3. Logic to find two elements in a list whose sum is 'x'
4. Object tag and identifier questions also asked

Seven Lakes
Tuesday, August 30, 2016
3:00 PM
1. Algorithm to find sum of two numbers in a list
2. Algorithm to find square root of a number
3. Algorithm to find maximum mark kept by which student on a table with
columns named as student, test and marks.
4. What are 1NF, 2NF and 3NF in SQL?

Sony
Wednesday, August 31, 2016
8:57 AM
1. What are Decorators and why do we use it?--function as arg and returns as
function
2. Multiprocessing and multithreading in Python
Here asked about Parent, Child and process relation concept. How a parent will know
that a process's invoker has been killed.
3. Differences between __repr__ and __str__ in Python?
The goal of __repr__ is to be unambiguous(favours all types,The goal of __str__ is
to be readable(favours string type)
4. How to implement stack and queue in Python ?
5. How does Python interprets ?py source code is first compiled to byte code
as .pyc. This byte code can be interpreted
6. How to run a module if I delete it's *.py file, but the *.pyc file is
present?
7. How does memory management happen in Python?
8. How to know what are the attributes/methods present of a class or object?
9. Have you worked on SQLAlchemy ?
10. What is multi-threading and multiprocessing in Python?
11. Write a program to write 'd' in place of 'a', 'e' in place of 'b'�.'a' in
place of 'w' with proper unit test cases.

EY [Tele]
This is totally a web development JD, focusing more on
Django and front end. Feeling scared and irresponsibleness at the same time.
� Interviewed by Amar
� He has completed 1 year in EY
� Basically works on financial services
� Does work on risk analysis
� is previous employee of Accenture
� He has visited USA within a year of joining
Works we will do
� Data quality check
� Any technology we have to learn like
o Java
o Python
o VBA
o Javascript etc.
� Client will give us appreciation
� Office is on ITPL road
Rewards to performing employees
� Learning scope is lot
� Travel on training
� Increment, packages are good
� Quarterly rewards are still there
� Business partners appreciates us
o Prashant is the partner
o He rewards gracefully
Friday, September 09, 2016
12:00 PM
� A company's stocks current market price is $100.
`Call` has $100 price with premium $10
`Put` has also the same.
Which one if you sell will become more loss?
Answer: is `Call` as Call option can become $150 or more, however `Put` can become
max to max $0.
� What is `hash map` and How does it gets created?
� Difference between `dictionary` and `hash map`?
� There are two linked lists. They have a common node. How to find the
common node?
� There are 100 elements in a list 1 to 100 in a random order. How to find
the missing element?
� What is `Duration` in a bond?
� What is LIBOR ?
� What is DV01 or modified duration? How does it modifies the interest
rate?
� What is the difference between `warrants` and `calls` ?

Das könnte Ihnen auch gefallen