Chapter 15: Additional in 'C'

Example 15.1, Page number: 505

In [2]:
#Allocate memory to pointer variable. 

import sys

#Variable initialization
j = 0
k = int(raw_input("How many number : "))
p = [0 for i in range(0,k)]

#in python, all variables are allocated using dynamic memory allocation technique and no
#malloc function and pointer concept is available in python.

#Read the numbers
while j != k:
    p[j] = int(raw_input("Number %d = "%(j+1)))
    j += 1
    
j = 0

#Result
sys.stdout.write("The numbers are : ")
while j != k:
    sys.stdout.write("%d\t"%(p[j]))
    j += 1
    
How many number : 4
4
Number 1 = 1
Number 2 = 2
Number 3 = 3
Number 4 = 4
The numbers are : 1	2	3	4	

Example 15.2, Page number: 506

In [3]:
#Memory allocation to pointer variable. 

import sys

#Variable initialization
j = 0
k = int(raw_input("How many Number : "))
p = [0 for i in range(0,k)]

#in python, all variables are allocated using dynamic memory allocation technique and no
#calloc function and pointer concept is available in python.

#Read the numbers
while j != k:
    p[j] = int(raw_input("Number %d = "%(j+1)))
    j += 1
    
j = 0

#Result
sys.stdout.write("The numbers are : ")
while j != k:
    sys.stdout.write("%d\t"%(p[j]))
    j += 1
    
How many Number : 3
Number 1 = 45
Number 2 = 58
Number 3 = 98
The numbers are : 45	58	98	

Example 15.3, Page number: 507

In [6]:
#Reallocate memory 

import sys

#Variable Initialization
str1 = "India"

#in python, value tagged method is used for data storage instead of memory tagging.
#no realloc function is in python

#Result
sys.stdout.write("str = %s"%(str1))
str1 = "Hindustan"
sys.stdout.write("\nNow str = %s"%(str1))
str = India
Now str = Hindustan

Example 15.4, Page number: 508

In [6]:
#Display unused memory 

import psutil

psutil.phymem_usage()

#There is no coreleft() function in python. phymem_usage function in the module psutil gives the 
#status and usage of physical memory in python.
Out[6]:
usage(total=3165270016L, used=987840512L, free=2177429504L, percent=31.2)

Example 15.5, Page number: 510

In [1]:
#Linked list

import sys

#Variable Initialziation
ch = 'y'
p = 0
q = []

#Function Definitions
def gen_rate(m):
    q.append(m)
    
def show():
    print q
    
def addatstart(m):
    q.insert(0,m)
    
def append(m,po):
    q.insert(po,m)

def erase(d):
    q.remove(d)
    
def count():
    print len(q)
    
def descending():
    q.sort(reverse=True)
    
#Get choice
while ch == 'y':
    n = int(raw_input("1. Generate\n2. Add at starting\n3. Append\n4. Delete\n5. Show\n6.Count\n7.Descending\nEnter your choice: "));
    #There is no switch statement in python
    if n == 1:
        i = int(raw_input("How many node you want : "))
        for j in range(0,i):
            m = int(raw_input("Enter the element : "))
            gen_rate(m)
        show()
    else:
        if n == 2:
            m = int(raw_input("Enter the element : "))
            addatstart(m)
            show()
        else:
            if n == 3:
                m = int(raw_input("Enter the element and position "))
                po = int(raw_input("Enter the element and position"))
                append(m,po)
                show()
            else:
                if n == 4:
                    d = int(raw_input("Enter the number for deletion : "))
                    erase(d)
                    show()
                else:
                    if n == 5:
                        show()
                    else:
                        if n == 6:
                            count()
                        else:
                            if n == 7:
                                descending()
                                show()
                            else:
                                sys.stdout.write("Enter value between 1 to 7")
                
    ch = raw_input("Do u wnat to continue (y/n)")
    
1. Generate
2. Add at starting
3. Append
4. Delete
5. Show
6.Count
7.Descending
Enter your choice: 1
How many node you want : 4
Enter the element : 1
Enter the element : 5
Enter the element : 4
Enter the element : 7
[1, 5, 4, 7]
Do u wnat to continue (y/n)n

Example 15.6, Page number: 518

In [61]:
#Draw circle, line and arc using graphics function

%matplotlib inline
import pylab
import matplotlib.pyplot as plt

#Tkinter package is used for graphics
#Give proportionate sizes to draw
#draw circle
circle2=plt.Circle((.5,.5),.2,color='b')
fig = plt.gcf()
fig.gca().add_artist(circle2)


#draw line
figure()
pylab.plot([210,110],[150,150])

#Draw ellipse
figure()
from matplotlib.patches import Ellipse
e = Ellipse(xy=(35, -50), width=10, height=5, linewidth=2.0, color='g')
fig = plt.gcf()
fig.gca().add_artist(e)
e.set_clip_box(ax.bbox)
e.set_alpha(0.7)
pylab.xlim([20, 50])
pylab.ylim([-65, -35])
Populating the interactive namespace from numpy and matplotlib
WARNING: pylab import has clobbered these variables: ['pylab', 'e']
`%pylab --no-import-all` prevents importing * from pylab and numpy
Out[61]:
(-65, -35)

Example 15.7, Page number: 519

In [72]:
#Draw boxes and fill with different designs.

%pylab
#Tkinter package is used for graphics
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection

e = Rectangle(xy=(35, -50), width=10, height=5, linewidth=2.0, color='b')
fig = plt.gcf()
fig.gca().add_artist(e)
e.set_clip_box(ax.bbox)
e.set_alpha(0.7)
pylab.xlim([20, 50])
pylab.ylim([-65, -35])

#There are no different automatic fill styles. user should create the styles.

Example 15.8, Page number: 520

In [95]:
#Display text in different size, font, vertically and horizontally 

%pylab

from pylab import *

#Tkinter package is used for graphics
# set limits so that it no longer looks on screen to be 45 degrees
xlim([-5,5])

# Locations to plot text
l1 = array((1,1))
l2 = array((5,5))

# Rotate angle
angle = 90
trans_angle = gca().transData.transform_angles(array((45,)),
                                               l2.reshape((1,2)))[0]

# Plot text
th2 = text(l2[0],l2[1],'Hello(Horizontal Text with fontsize 25)\n\n',fontsize=25,
           rotation=0)
th2 = text(l2[0],l2[1],'Hello(Horizontal Text with fontsize 16)',fontsize=16,
           rotation=0)
th1 = text(l1[0],l1[1],'Hello(Vertical Text)',fontsize=16,
           rotation=angle)
show()
Using matplotlib backend: module://IPython.kernel.zmq.pylab.backend_inline
Populating the interactive namespace from numpy and matplotlib
WARNING: pylab import has clobbered these variables: ['power', 'draw_if_interactive', 'random', 'fft', 'angle', 'linalg', 'info']
`%pylab --no-import-all` prevents importing * from pylab and numpy

Example 15.9, Page number: 521

In [108]:
#Display status of mouse button pressed 

from Tkinter import *
from tkFileDialog import askopenfilename
import Image, ImageTk

if __name__ == "__main__":
    root = Tk()

    #setting up a tkinter canvas with scrollbars
    frame = Frame(root, bd=2, relief=SUNKEN)
    frame.grid_rowconfigure(0, weight=1)
    frame.grid_columnconfigure(0, weight=1)
    xscroll = Scrollbar(frame, orient=HORIZONTAL)
    xscroll.grid(row=1, column=0, sticky=E+W)
    yscroll = Scrollbar(frame)
    yscroll.grid(row=0, column=1, sticky=N+S)
    canvas = Canvas(frame, bd=0, xscrollcommand=xscroll.set, yscrollcommand=yscroll.set)
    canvas.grid(row=0, column=0, sticky=N+S+E+W)
    xscroll.config(command=canvas.xview)
    yscroll.config(command=canvas.yview)
    frame.pack(fill=BOTH,expand=1)

    

    #function to be called when mouse is clicked
    def printcoords(event):
        #outputting x and y coords to console
        print "Mouse Button pressed"
        print (event.x,event.y)
    #mouseclick event
    canvas.bind("<Button 1>",printcoords)

    root.mainloop()
    
import win32api, win32con

print "Current cursor position at " 
print win32api.GetCursorPos()
Mouse Button pressed
(207, 115)
Current cursor position at 
(502, 188)

Example 15.10, Page number: 523

In [110]:
#Change mouse cursor.

#Placing the cursor on top of the circle button will change the pointer to circle
# and plus button to plus symbol

from Tkinter import *
import Tkinter

top = Tkinter.Tk()

B1 = Tkinter.Button(top, text ="circle", relief=RAISED,\
                         cursor="circle")
B2 = Tkinter.Button(top, text ="plus", relief=RAISED,\
                         cursor="plus")
B1.pack()
B2.pack()
top.mainloop()
In [ ]: