var1 = 11 #define and initialize three variables
var2 = 22
var3 = 33
print hex(id(var1)) #print the address of these variables
print hex(id(var2))
print hex(id(var3))
from ctypes import c_int,pointer,addressof
var1 = c_int(11) #two integer variables
var2 = c_int(22)
print hex(id(var1)),'\n',hex(id(var2)),'\n' #print addresses of variables
ptr = pointer(var1) #pointer to integer variable var1
print hex(addressof(ptr)) #print address of ptr
ptr = pointer(var2) #pointer to integer variable var2
print hex(addressof(ptr)) #print address of ptr
#in python, id(a) != addressof(pinter(a))
from ctypes import c_int,pointer
var1 = c_int(11) #two integer variables
var2 = c_int(22)
ptr = pointer(var1) #pointer to integer variable var1
print ptr[0] #print contents of pointer (11)
ptr = pointer(var2) #pointer to integer variable var2
print ptr[0] #print contents of pointer (22)
from ctypes import c_int,pointer
var1 = c_int() #integer variable
ptr = pointer(var1) #set pointer to address of var1
ptr[0] = c_int(37) #same as var1 = 37
var2 = ptr[0] #same as var2 = var1
print var2 #verify var2 is 37
from ctypes import c_int,pointer,c_float
intvar = c_int() #define integer variable
flovar = c_float() #define float variable
ptrint = pointer(intvar)
ptrflo = pointer(flovar)
ptrvoid = pointer(intvar)
ptrvoid = pointer(flovar)
intarray = [31,54,77,52,93] #array
for j in range(5): #for each element
print intarray[j] #print value
from ctypes import c_int
intarray = [31,54,77,52,93] #array
arr = (c_int * len(intarray))(*intarray) #pointer to intarray
for j in range(5): #for each element
print arr[0 + j] #print value
from ctypes import c_int
intarray = [31,54,77,52,93] #array
arr = (c_int * len(intarray))(*intarray) #pointer to intarray
for j in range(5): #for each element
print arr[0 + j] #print value
def centimize(v):
v *= 2.54 #convert inches to centimeters
return v
var = 10.0 #var has value of 10 inches
print 'var =',var,'inches'
var = centimize(var) #change variable var to centimeters
print 'var =',var,'centimeters'
from ctypes import c_float,pointer
def centimize(ptrd):
ptrd[0] *= 2.54 #ptrd[0] is the same as var
var = 10.0 #var has value of 10 inches
print 'var =',var,'inches'
var = c_float(10.0)
centimize(pointer(var)) #change variable var to centimeters
print 'var =',var.value,'centimeters'
MAX = 5 #number of array element
def centimize(ptrd):
for j in range(MAX):
ptrd[0+j] *= 2.54 #ptrd points to elements of array
varray = [10.0,43.1,95.9,59.7,87.3]
centimize(varray) #change elements of array to cm
for j in range(MAX): #display new array values
print 'varray[%d]=%.3f centimeter' %(j,varray[j])
from ctypes import c_int,pointer
def order(numb1 ,numb2): #orders two numbers
if numb1[0] > numb2[0]: #if 1st larger than 2nd
temp = numb1[0] #swap them
numb1[0] = numb2[0]
numb2[0] = temp
n1 = c_int(99);n2 = c_int(11) #one pair ordered, one not
n3 = c_int(22);n4 = c_int(88)
order(pointer(n1) , pointer(n2)) #order each pair of numbers
order(pointer(n3) , pointer(n4))
print 'n1 =',n1.value #print out all numbers
print 'n2 =',n2.value
print 'n3 =',n3.value
print 'n4 =',n4.value
def order(numb1 ,numb2): #orders two numbers
if numb1 > numb2: #if 1st larger than 2nd
temp = numb1 #swap them
numb1 = numb2
numb2 = temp
return numb1,numb2
def bsort(ptr,n):
for j in range(n-1): #outer loop
for k in range(j+1,n,1): #inner loop starts at outer
ptr[j] ,ptr[k] = order(ptr[j] ,ptr[k]) #order the contents
N = 10 #array size
arr = [37,84,62,91,11,65,57,28,19,49] #test array
bsort(arr,N) #sort the array
for j in range(N): #print out sorted array
print arr[j],'',
str1 = "Defined as an array" #two strings
str2 = "Defined as a pointer"
print str1 #display both string
print str2
print str2[1:] #str2 starts from "efined..."
def dispstr(ps):
print ps #display string str through ps
str = "Idle people have the least leisure." #string
dispstr(str) #display string
def copystr(dest,src):
dest = src #copy string
return dest
str1 = "Self-conquest is the greatest victory."
str2 = "" #empty string
str2 = copystr(str2,str1) #copy str1 to str2
print str2
Days = 7 #number of variables in array
arrptrs = ["Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday"]
for j in range(Days): #display every string
print arrptrs[j]
str = "Idle hands are the devil's workshop."
strlen = len(str) #get length of str
ptr = ["" for j in range(strlen + 1)] #set aside memory: string + '\0'
ptr = str #copy str to new memory area ptr
print 'ptr =',ptr #show that ptr is now in str
del ptr
class String: #user-defined string type
def __init__(self,s): #constructor
self.__str = s #copy argument to str
def __del__(self): #destructor
print 'Deleting str' #release memory
def display(self): #display the string
print self.__str
s1 = String("Who knows nothing doubts nothing.") #uses 1-arg constructor
print 's1 =', #display string
s1.display()
del s1
from ctypes import POINTER,Structure
class Distance(Structure): #Distance class
def getdist(self): #get length from user
self.__feet = input("\nEnter feet: ")
self.__inches = input("Enter inches: ")
def showdist(self): #display distance
print self.__feet , '\' -' , self.__inches , '\"'
dist = Distance() #define a named Disatance object
dist.getdist() #access object member with dot operator
dist.showdist()
distptr = POINTER(Distance) #points to Distance
distptr = dist
distptr.getdist() #access object members
distptr.showdist()
from ctypes import Structure,POINTER
class Distance(Structure): #Distance class
def getdist(self): #get length from user
self.__feet = input("Enter feet: ")
self.__inches = input("Enter inches: ")
def showdist(self): #display distance
print self.__feet , '\' -' , self.__inches , '\"'
dist = Distance()
distptr = POINTER(Distance)
distptr = dist
distptr.getdist()
distptr.showdist()
from ctypes import Structure
class person(Structure): #class of persons
def setName(self): #set the name
self.__name = raw_input("Enter name: ")
def printName(self): #get the name
print ' Name is :',self.__name
ob = [person() for j in range(100)] #array of persons
persPtr = ob #array to persons
n = 0 #number of persons in array
while True: #put persons in array
persPtr[n].setName() #set person's name
n += 1 #count new person
choice = raw_input('Enter another (y/n)? ') #person ?
if choice=='n': #quit on 'n'
break
for j in range(n): #print names of all persons
print 'person number',j+1
persPtr[j].printName()
class link:
def __init__(self):
self.data = None # contains the data
self.next = None # contains the reference to the next node
class linklist:
def __init__(self):
self.first = None
def additem(self, d): # add data item
newlink = link() # make a new link
newlink.data = d # give it data
newlink.next = self.first # it points to next link
self.first = newlink # now first points to this
def display(self):
current = self.first # set ptr to first link
while current: # quit on last link
print current.data # print data
current = current.next # move to next link
li = linklist() # make linked list
li.additem(25) # add four items to linked list
li.additem(36)
li.additem(49)
li.additem(64)
li.display() # display entire list
from ctypes import Structure,POINTER
def order(numb1 ,numb2): #orders two objects
if numb1.getname() > numb2.getname(): #if the name of 1st larger than 2nd
temp = numb1 #swap them
numb1 = numb2
numb2 = temp
return numb1,numb2
def bsort(ptr,n):
for j in range(n-1): #outer loop
for k in range(j+1,n,1): #inner loop starts at outer
ptr[j] ,ptr[k] = order(ptr[j] ,ptr[k]) #order the contents
return ptr
class person(Structure): #class of persons
def setName(self): #set the name
self.__name = raw_input("Enter name: ")
def printName(self): #display the name
print self.__name
def getname(self): #returns the name
return self.__name
ob = [person()]*100 #array of persons
persPtr = POINTER(person) #pointer to person
persPtr = ob #array of pointers to persons
n = 0 #number of persons in array
while True: #put persons in array
persPtr[n] = person()
persPtr[n].setName() #set person's name
n += 1 #count new person
choice = raw_input('Enter another (y/n)? ') #person ?
if choice=='n': #quit on 'n'
break
print '\nUnsorted list:'
for j in range(n): #print names of all persons
persPtr[j].printName()
persPtr = bsort(persPtr,n) #sorts the content of array according to their name
print '\nSorted list:'
for j in range(n): #print names of all persons
persPtr[j].printName()
LEN = 80 #length of expression, in character
MAX = 40 #size of stack
class stack:
def __init__(self):
self.__st = [None]*MAX #stack: array of chars
self.__top = 0 #number of top of stack
def push(self,var): #put char on stack
self.__top += 1
self.__st[self.__top] = var
def pop(self): #take char off stack
x = self.__st[self.__top]
self.__top -= 1
return x
def gettop(self): #get top of stack
return self.__top
class express: #expression class
def __init__(self,ptr):
self.__s = stack() #stack for analysis
self.__pStr = ptr #input string
self.__len = len(self.__pStr) #length of input string
def parse(self): #add items to stack
for j in range(self.__len): #for each input character
ch = self.__pStr[j] #get next character
if ch >= '0' and ch<='9': #if it's a digit,
self.__s.push(ch) #save the character
#if it's operator
elif ch == '+' or ch == '-' or ch == '*' or ch == '/':
if self.__s.gettop() == 1: #if it's first operator
self.__s.push(ch) #put on stack
else: #not first operator
lastval = self.__s.pop() #get previous digit
lastop = self.__s.pop() #get previous operator
#if this is * or / AND last operator was + or -
if (ch=='*' or ch=='/') and (lastop == '+' or lastop == '-'):
self.__s.push(lastop) #restore last two pops
self.__s.push(lastval)
else: #in all other cases
#do last operation, and push result on stack
if lastop == '+':
self.__s.push(str(int(self.__s.pop()) + int(lastval)))
elif lastop == '-':
self.__s.push(str(int(self.__s.pop()) - int(lastval)))
elif lastop == '*':
self.__s.push(str(int(self.__s.pop()) * int(lastval)))
elif lastop == '/':
self.__s.push(str(int(int(self.__s.pop()) / int(lastval))))
else:
print 'Unknown oper'
self.__s.push(ch) #put current operator on stack
else: #not a known character
print 'Unkown input character'
def solve(self): #remove items from stack
while self.__s.gettop() > 1:
lastval = self.__s.pop() #get previous value
a = self.__s.pop() #get previous operator
#do operation, push answer
if a == '+':
self.__s.push(str(int(self.__s.pop()) + int(lastval)))
elif a == '-':
self.__s.push(str(int(self.__s.pop()) - int(lastval)))
elif a == '*':
self.__s.push(str(int(self.__s.pop()) * int(lastval)))
elif a == '/':
self.__s.push(str(int(int(self.__s.pop()) / int(lastval))))
else:
print 'Unknown oper'
return self.__s.pop() #last item on stack is ans
print 'Enter an arithmetic expression'
print 'of the form 2+3*4/3-2'
print 'No number may have more than one digit.'
print 'Dont\'t use any spaces or parentheses.'
while True:
string = raw_input("Enter expression: ") #input from user
eptr = express(string) #make expression
eptr.parse() #parse it
print '\nThe numerical value is: ',eptr.solve() #solve it
del eptr #delete expression
ans = raw_input("\n\nDo another (Enter y or n)? ")
if ans == 'n':
break