Search This Blog

Thursday, March 5, 2015

Data Types: Tuples, Sets, Dictionaries

Tuples:


Tuples are similar to lists but they are immutable. We can convert as list to tuple ans vice versa.

>>> mytuple=tuple(["Harry Potter",25,100,3])
>>> mytuple

('Harry Potter', 25, 100, 3)

Note that tuple has () instead of a list's []

>>> moviename,runningTime,upVotes,downVotes=mytuple
>>> moviename
'Harry Potter'
>>> runningTime
25
>>> upVotes
100
>>> downVotes

3


Sets:

Sets are unordered collection of unique objects.

List to a set: myset = set(moviename)
Set to list: mylist = list(myset)

>>> a=set([1,2,3,3,2])
>>> a

set([1, 2, 3])

Sets have only unique items

>>> b=set([3,4,5])
>>> b
set([3, 4, 5])
>>> a|b

set([1, 2, 3, 4, 5])

Intersection of sets

>>> a&b
set([3])

>>> 


>>> a-b

set([1, 2])
>>> b-a
set([4, 5])

>>> 

Sets are useful in finding different unique values


Dictionaries:


Dictionaries are unordered key-value pairs

a={}
Empty dictionary

>>> a={"Movie":"Harry Potter", "sitCom":"Big bang theory"}
>>> print a
{'Movie': 'Harry Potter', 'sitCom': 'Big bang theory'}










Variables and Data Types


             Reference
Name ----------------> Deepti
Variable                     Object


  • "Name", which is a variable acts as a reference to "Deepti" which is an object
  • It is the object that has the data type associated with it,


>>> id(name)
42209536
>>> hex(id(name))
'0x2841100'
>>> name.__repr__
<method-wrapper '__repr__' of str object at 0x02841100>
>>> 


>>> name = "Deepti"
>>> name = 'deepti'
>>> name = "Deepti\nvaidyula"
>>> name
'Deepti\nvaidyula'



  • # The 'r' here tells that it is a raw string and don't interpret the \n

>>> name = r"Deepti\nvaidyula" 
>>> name
'Deepti\\nvaidyula'

>>> print name
Deepti\nvaidyula
>>> name = "Deepti\nvaidyula"
>>> print name
Deepti
vaidyula


  • # Python also supports unicode

>>> name = u"Deepti"
>>> name

u'Deepti'

# Convert unicode to String - use str
>>> str(name)
'Deepti'
>>> name
u'Deepti'


  • Use 'unicode' to convert to unicode




  • We cannot directly change string objects in memory as they are immutable

>>> name = "Daniel"
>>> name[0]
'D'
>>> name[0] = 'a'

Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    name[0] = 'a'

TypeError: 'str' object does not support item assignment
>>> name = "Radcliffe"
>>> name

'Radcliffe'


>>> a="Daniel"
>>> name = a
>>> name
'Daniel'
>>> a

'Daniel'



>>> a="Radcliffe"
>>> a
'Radcliffe'
>>> name
'Daniel'

String Concatenation

fn = "deepti"
ln = "Vaidyula"

full_name = fn + ln
print full_name
full_name = fn + ' ' + ln
print full_name

>>> 
deeptiVaidyula
deepti Vaidyula

  • Python like most high languages has garbage collection. When any object is no longer referenced by any variable, it is automatically cleaned up.
  • Repeated sequence in string
>>> rhyme = "twinkle"
>>> print rhyme*2 + " little star"
twinkletwinkle little star

String Slicing


  • string[start:end:steps]


>>> num="123456789"
>>> print num[5]
6
>>> print num[5:8]
678
>>> print num[5:8:2]
68
>>> print num[5:8:2]
KeyboardInterrupt
>>> print num[5:8:1]
678
>>> print num[5:9:1]
6789
>>> print num[5:9:2]
68
>>>


  • num.find returns the index

>>> num.find("5")
4

>>> num.find("abc")
-1
>>>
"abc" is not present in num

>>> name = "Daniel Radcliffe"
>>> name.split()
['Daniel', 'Radcliffe']
>>> 

>>> name = "Daniel:Radcliffe"
>>> name.split(":")
['Daniel', 'Radcliffe']

>>> name.replace("Daniel", "Ginny")

'Ginny:Radcliffe'

String Formatting

>>> ip="192.168.12.38"
>>> print "Hack this ip : %s" %ip
Hack this ip : 192.168.12.38

Operations and Lists



>>> 2 + 2
4
>>> list=[1,2,3,4]
>>> list[0]
1
>>> list[-1]
4
>>> len(list)

4


  • Lists are heterogenous. So, we can mix numbers and alphabet


>>> mylist=[1,2,3,4,["a","b","c"]]
>>> mylist
[1, 2, 3, 4, ['a', 'b', 'c']]
>>> len(mylist)

5
>>> mylist.append(5)
>>> mylist
[1, 2, 3, 4, ['a', 'b', 'c'], 5]
>>> mylist.reverse()
>>> print mylist.reverse()
None
>>> mylist.pop()
5
>>> mylist
[1, 2, 3, 4, ['a', 'b', 'c']]
>>> mylist.insert(4,"inserted")
>>> mylist

[1, 2, 3, 4, 'inserted', ['a', 'b', 'c']]
>>> mylist

[1, 2, 4, 'inserted', ['a', 'b', 'c']]













Tuesday, May 27, 2014

Faster commands that improve performance


  • Tuple is faster than list
  • An operation like a_list = a_list + 1 is memory intensive

Saturday, May 3, 2014

Python - Cat animation using Pygame

import pygame, sys
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((400,300))
FPS = 30
fpsClock = pygame.time.Clock()

pygame.display.set_caption('Animation')

BLACK = (0,0,0)
WHITE = (255,255,255)
RED   = (255,0,0)
BLUE  = ( 0, 0, 255)

catImg = pygame.image.load('cat.jpg')
catx = 10
caty = 10
direction = 'right'
                           

while True:
    screen.fill(WHITE)
    if direction == 'right':
        catx += 5
        if catx == 360 :
            direction = 'down'
    elif direction == 'down':
        caty += 5
        if caty == 260:
            direction ='left'
    elif direction == 'left':
        catx -= 5
        if catx == 10:
            direction = 'up'
    elif direction == 'up':
        caty -= 5
        if caty == 10:
             direction = 'right'
    screen.blit(catImg, (catx,caty))
    
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()
    fpsClock.tick(FPS)



Tuesday, March 25, 2014

Print a hollow diamond - with numbers


if __name__ == "__main__" :
    try:
        act_size = int(input("Enter the size of the diamond : "))
        size=1
        size_max = 2*act_size - 1
        level=1
        i_size = 2 * act_size
        for j in range(0,i_size):
            pos=1         
            for i in range(i_size):
                if pos > act_size - level+1 and pos <=act_size+level-1 and level<=act_size :
                    print(" ", end='')
                elif pos <= act_size and size < 2*act_size and level<=act_size :
                    print(size, end='')
                    size += 2
                elif pos > act_size and pos <= i_size and level<=act_size :
                    size -= 2
                    print(size, end='')
                if level > act_size and pos <= level - act_size:                 
                    print(size_max,end='')
                    size_max += 2                   
                elif level > act_size and pos > i_size - level + act_size :
                    size_max -= 2
                    print(size_max,end='')                   
                elif level > act_size:
                    print(" ",end='')
               
                pos += 1
            size_max = 2*(i_size-level)-1
            size = (2*level) + 1
            level += 1
            print("")
               
    except :
        print("ERROR: Only numbers are accepted")



 

Sunday, March 16, 2014

None


None is :

  • a special constant in python
  • a null value
  • of datatype NoneType


None is not:

  • 0
  • is not an empty string
  • is not the same as False


You can:

  • compare None to anything other than None always returns False.
  • assign None to any variable
You cannot create other NoneType objects. All variables with a value of None are equal to each other.



ImportError handling

You run in to import errors by using the try...except blocks.
You run in to this error when the module that you are trying to import does not exist in the sys.path. However, if you want to gracefully continue your execution even if there is an import error (and if this what your program expects) then you can handle it using except.

try: import abcexcept ImportError: print("It is still OK to continue")

or

You can also chose to import sys path