Check number is even or odd using bitwise operator Python

# The AND bitwise operator ‘&’ gives 1 when both bits are 1 else 0. An even number will have bit #  as 0 while odd number will have bit as 1. So if we ‘&’ with 1 (…0001) then for even number it will # be 0 and odd number will be 1

def checkOddEven(element):

    if (element & 1) == 0:

        return ‘Number is even’

    else:

        return‘Number is odd’

Advertisements

Find an integer that occurs only once in an array

#There is two ways of doing this use a hash(dict) to parse the array and store the key and value. #Then loop through the hash and return the key whose value is 1

#Second way is to use the XOR operation and return the whatever value is remaining. The logic is #whenever you XOR an integer with itself it gives a 0 and 0 XOR’ed with integer is the integer #itself.

def  lonelyInteger( arr):

   value = 0

   for element in arr:

        value = value ^ element

   return value

print lonelyInteger([1])

Memoization in Python

”’

This code snippet is taken from

http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/

”’

from functools import partial

class memoize(object):
“””cache the return value of a method

This class is meant to be used as a decorator of methods. The return value
from a given method invocation will be cached on the instance whose method
was invoked. All arguments passed to a method decorated with memoize must
be hashable.

If a memoized method is invoked directly on its class the result will not
be cached. Instead the method will be invoked like a static method:
class Obj(object):
@memoize
def add_to(self, arg):
return self + arg
Obj.add_to(1) # not enough arguments
Obj.add_to(1, 2) # returns 3, result is not cached
“””
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
if obj is None:
return self.func
return partial(self, obj)
def __call__(self, *args, **kw):
obj = args[0]
try:
cache = obj.__cache
except AttributeError:
cache = obj.__cache = {}
key = (self.func, args[1:], frozenset(kw.items()))
try:
res = cache[key]
except KeyError:
res = cache[key] = self.func(*args, **kw)
return res
if __name__ == “__main__”:
# example usage
class Test(object):
v = 0
@memoize
def inc_add(self, arg):
self.v += 1
return self.v + arg

t = Test()
assert t.inc_add(2) == t.inc_add(2)
assert Test.inc_add(t, 2) != Test.inc_add(t, 2)

Connecting to Mysql using Python

#You will need to install the mysqldb module

# pip install MySQL-python
#pip install MySQLdb

import MySQLdb

#

db = MySQLdb.connect(host=”127.0.0.1″, # your host
user=”user”, # your username
passwd=”passsword”, # your password
db=”db_name”) # name of the data base

cur = db.cursor()
cur.execute(“select * from TABLENAME;”)

# get the number of rows in the resultset
numrows = int(cur.rowcount)
print numrows
# get and display one row at a time.
for row in cur.fetchall():
print row

”’

Here is a detailed list of things you can do using this module

http://mysql-python.sourceforge.net/MySQLdb.html

””

Python range function

The Range function

The built-in range function in Python is very useful to generate sequences of
numbers in the form of a list.

The given end point is never part of the generated list;

range(10) generates a list of 10 values, the legal indices for items of a
sequence of length 10.

It is possible to let the range start at another number, or to specify a
different increment (even negative;

Sometimes this is called the ‘step’):

Range Examples

>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

# You can use range() wherever you would use a list.

a = range(1, 10)
for i in a:
print i

for a in range(21,-1,-2):
print a,

#output>> 21 19 17 15 13 11 9 7 5 3 1

# We can use any size of step (here 2)
>>> range(0,20,2)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

>>> range(20,0,-2)
[20, 18, 16, 14, 12, 10, 8, 6, 4, 2]

# The sequence will start at 0 by default.
#If we only give one number for a range this replaces the end of range value.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# If we give floats these will first be reduced to integers.
>>> range(-3.5,9.8)
[-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]

Python Socket programming

”’
Created on Oct 14, 2013

@author: ishaansutaria
”’
import socket #for sockets

#Creates a UDP socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#You can use bind to use a socket number. But it is not required.
#if you do not use this statement then it will bind to a port that is available
s.bind((“”, 44444))
#Server address
host = ‘xxxxxxxxx.com’;
#Port on which you want to send the packet
port = 55056;
msg = ‘This is the message being sent in the udp packet’

#Send the packet
s.sendto(j, (host, port))
print “message sent”

#Receiving Message
while 1 == 1:
d = s.recvfrom(1024)
print d