Python Tutorial

Sunday, January 20, 2013

Python UUID

Python uuid generates unique id.
uuid1 and uuid4 generates random id. uuid3 and uuid 5 generate a UUID based on the SHA-1 hash of a namespace identifier (UUID) and a name (string).

All source code available on github

import uuid

print uuid.uuid1()
print "[Hex]",uuid.uuid1().hex
print uuid.uuid4()
print "[Hex]",uuid.uuid4().hex
print uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
print "[Hex]",uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org').hex
print uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
print "[Hex]",uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org').hex

Output:
9bfb379e-62ae-11e2-81fb-4c809312d053
[Hex] 9bfc702162ae11e2a2504c809312d053
cf0be0b2-8eed-4b87-8b42-03679d8c1c94
[Hex] dd3162cb5e454dc3976a1769ef604742
6fa459ea-ee8a-3ca4-894e-db77e160355e
[Hex] 6fa459eaee8a3ca4894edb77e160355e
886313e1-3b8a-5372-9b90-0c9aee199e5d
[Hex] 886313e13b8a53729b900c9aee199e5d

Tuesday, January 15, 2013

Problem solving using python : Candy I


Candy I: https://www.spoj.com/problems/CANDY/
All source code available on github

n=input()
while n != -1:
    a=[]
    s =0
    for i in range(0,n):
        d=input()
        s  += d
        a.append(d)
    avg = int(s/n)
    if avg*n != s:
        print -1
    else:
        r=0
        for i in range(0,n):
            if a[i]<avg:
                r += (avg - a[i])
        print r
    n = input()

Python getter, setter : access getter, setter as property



All source code available on github

class MyClass(object):
    def __init__(self):
        self.__name = "" # define private variable
        self.__id = 0 # define private variable

    def setName(self, name):
        self.__name = name
    def setId(self, id):
        self.__id = id
    def getName(self):
        return self.__name
    def getId(self):
        return self.__id

    idGS = property(getId, setId) # declare getter, setter property for id

a = MyClass()
a.setName("Python")
a.idGS=5

print "Name ", a.getName()
print "Id ", a.idGS



Output:

Name  Python
Id  5

Python getter, setter example



All source code available on github

class MyClass():
    def __init__(self):
        self.__name = "" # define private variable
        self.__id = 0 # define private variable

    def setName(self, name):
        self.__name = name
    def setId(self, id):
        self.__id = id
    def getName(self):
        return self.__name
    def getId(self):
        return self.__id



a = MyClass()
a.setName("Python")
a.setId(1)


print "Name ", a.getName()
print "Id ", a.getId()

#print a.__name #error
#print a.__id #error


Output:
Name  Python
Id  1