Chapter 7: Pointers

Program 7.1, page no. 266

In [2]:
import sys

number = 10;
print "number's address: ", id(number)
print "number's value: ", number
 
pnumber = id(number)
print "pnumber's address: ", id(pnumber)
print "pnumber's size: %d bytes" %(sys.getsizeof(pnumber))
print "pnumber's value: ", pnumber
print "value pointed to: ", number
number's address:  42843088
number's value:  10
pnumber's address:  54575640
pnumber's size: 24 bytes
pnumber's value:  42843088
value pointed to:  10

Program 7.2, page no. 270

In [3]:
num1 = 0
num2 = 0
pnum = None
 
pnum = id(num1)
num1 = 2
num2 += 1
num2 += num1
pnum = id(num2)
num2 += 1
print "num1 = %d num2 = %d pnum = %d pnum + num2 = %d" %(num1, num2, pnum, pnum + num2)
num1 = 2 num2 = 4 pnum = 42843256 pnum + num2 = 42843260

Program 7.3, page no. 272

In [4]:
print "Input an integer: ",
value = int(raw_input())
print "You entered: ", value
Input an integer: 7
 You entered:  7

Program 7.4, page no. 276

In [5]:
multiple = ['M', 'y','s','t', 'r', 'i', 'n', 'g']
 
p = id(multiple[0])
print "The address of the first array element : ", p
p = id(multiple)
print "The address obtained from the array name: ", p
The address of the first array element :  140170253709440
The address obtained from the array name:  58009432

Program 7.5, page no. 277

In [6]:
multiple = "a string"
p = multiple
 
for i in range(len(multiple)):
    print "multiple[%d] = %c *(p+%d) = %c id(multiple[%d]) = %d p+%d = %d " %(i, multiple[i], i, p[i], i, id(multiple[i]), i, id(p[i]))
multiple[0] = a *(p+0) = a id(multiple[0]) = 140170254071168 p+0 = 140170254071168 
multiple[1] =   *(p+1) =   id(multiple[1]) = 140170254278248 p+1 = 140170254278248 
multiple[2] = s *(p+2) = s id(multiple[2]) = 140170254071048 p+2 = 140170254071048 
multiple[3] = t *(p+3) = t id(multiple[3]) = 140170254070208 p+3 = 140170254070208 
multiple[4] = r *(p+4) = r id(multiple[4]) = 140170254275768 p+4 = 140170254275768 
multiple[5] = i *(p+5) = i id(multiple[5]) = 140170254277248 p+5 = 140170254277248 
multiple[6] = n *(p+6) = n id(multiple[6]) = 140170254276568 p+6 = 140170254276568 
multiple[7] = g *(p+7) = g id(multiple[7]) = 140170254073528 p+7 = 140170254073528 

Program 7.6, page no. 277

In [7]:
import sys

multiple = [15, 25, 35, 45]
p = multiple
 
for i in range(sys.getsizeof(multiple)/sys.getsizeof(multiple[0])):
    print "address p+%d (id(multiple[%d])): %d *(p+%d) value: %d" %( i, i, id(p[i]), i, p[i])
 
print "Type integer occupies: %d bytes" %sys.getsizeof(int())
address p+0 (id(multiple[0])): 42842968 *(p+0) value: 15
address p+1 (id(multiple[1])): 42842728 *(p+1) value: 25
address p+2 (id(multiple[2])): 42842488 *(p+2) value: 35
address p+3 (id(multiple[3])): 42844240 *(p+3) value: 45
Type integer occupies: 24 bytes

Program 7.7, page no. 279

In [9]:
board = [['1','2','3'],
         ['4','5','6'],
         ['7','8','9']]
print "address of board : ", id(board)
print "address of board[0][0] : ", id(board[0][0])
print "value of board[0]: ", board[0]
address of board :  58026608
address of board[0][0] :  140170254070808
value of board[0]:  ['1', '2', '3']

Program 7.7A, page no. 280

In [10]:
board = [['1','2','3'],
         ['4','5','6'],
         ['7','8','9']]
 
print "value of board[0][0] : %c" % (board[0][0])
print "value of board[0]: ", board[0][0]
print "value of **board: ", board[0][0]
value of board[0][0] : 1
value of board[0]:  1
value of **board:  1

Program 7.8, page no. 281

In [11]:
board = [['1','2','3'],
         ['4','5','6'],
         ['7','8','9']]

for i in range(3):
    for j in range(3):
        print " board: ", board[i][j]
 board:  1
 board:  2
 board:  3
 board:  4
 board:  5
 board:  6
 board:  7
 board:  8
 board:  9

Program 7.9, page no. 283

In [12]:
board = [['1','2','3'],
         ['4','5','6'],
         ['7','8','9']]

for i in range(3):
    for j in range(3):
        print " board: ", board[i][j]
 board:  1
 board:  2
 board:  3
 board:  4
 board:  5
 board:  6
 board:  7
 board:  8
 board:  9

Program 7.10, page no. 285

In [13]:
size = [['6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '7'],
        ['1', '5', '3', '7', ' ', '1', '1', '3', '1', '5', '3', '7'],
        ['2', '8', '4', '8', ' ', '8', '4', '8', '2', '8', '4', '8']]
headsize = [164, 166, 169, 172, 175, 178, 181, 184, 188, 191, 194, 197]
hat_found = False
print "Enter the circumference of your head above your eyebrows in inches as a decimal value: ",
cranium = float(raw_input())
your_head = int(8.0*cranium)
i = 0
if(your_head == headsize[i]):
    hat_found = True
else:
    for i in range(1, len(headsize)):
        if(your_head > headsize[i - 1] and your_head <= headsize[i]):
            hat_found = True
            break
if(hat_found):
    print "Your hat size is %c %c%c%c" %(size[0][i], size[1][i], ' ' if (size[1][i]==' ') else '/', size[2][i])
else:
    if(your_head < headsize[0]):
        print "You are the proverbial pinhead. No hat for you I'm afraid."
    else:
        print "You, in technical parlance, are a fathead, No hat for you, I'm afraid."
Enter the circumference of your head above your eyebrows in inches as a decimal value: 22.5
 Your hat size is 7 1/4

Program 7.11, page no. 290

In [14]:
pPrimes = []
found = False
 
print "How many primes would you like - you'll get at least 4? ",
total = int(raw_input())
total = 4 if total < 4 else total
 
pPrimes.append(2) # First prime
pPrimes.append(3) # Second prime
pPrimes.append(5) # Third prime
count = 3
trial = 5
 
while(count < total):
    trial += 2
    for i in range(1, count):
        if((trial % pPrimes[i]) == 0):
            found = False
            break
        else:
            found = True
    if(found):
        pPrimes.append(trial)
        count += 1

for i in range(total):
    print "\t", pPrimes[i],
    if(not((i+1) % 5)):
        print ""
How many primes would you like - you'll get at least 4? 25
 	2 	3 	5 	7 	11 
	13 	17 	19 	23 	29 
	31 	37 	41 	43 	47 
	53 	59 	61 	67 	71 
	73 	79 	83 	89 	97 

Program 7.13, page no. 300

In [15]:
import sys

print "Enter text on an arbitrary number of lines (go on typing hit enter to terminate): "
print "Should be less than 10000 characters: "
text = raw_input()

if len(text) > 10000:
    print "Maximum length exceeded, terminating..."
    sys.exit()

distinct_words = []
word_occurrance = []
list_text = text.split(" ")
for word in list_text:
    if not word in distinct_words:
        distinct_words.append(word)
        word_occurrance.append(0)
        
for i in range(len(list_text)):
    if list_text[i] in distinct_words:
        index = distinct_words.index(list_text[i])
        word_occurrance[index] += 1

for i in range(len(distinct_words)):
    if(i % 5 == 0):
        print "\n"
    print distinct_words[i], "\t     ", word_occurrance[i],
Enter text on an arbitrary number of lines (go on typing hit enter to terminate): 
Should be less than 10000 characters: 
Peter Piper picked a peck of pickled pepper. A peck of pickled pepper Peter Piper picked. If Peter Piper picked a peck of pickled pepper, Where's the peck of pickled pepper Peter Piper picked?


Peter 	      4 Piper 	      4 picked 	      2 a 	      2 peck 	      4 

of 	      4 pickled 	      4 pepper. 	      1 A 	      1 pepper 	      2 

picked. 	      1 If 	      1 pepper, 	      1 Where's 	      1 the 	      1 

picked? 	      1

Program 7.14, page no. 306

In [16]:
print "Enter strings to be sorted, separated by '.' Press Enter to end: "
text = raw_input()

dot_separated = text.split('.')
text_sorted = sorted(dot_separated)

for str in text_sorted:
    print str
Enter strings to be sorted, separated by '.' Press Enter to end: 
Many a mickle makes a muckle. A fool and your money are soon partners. Every dog has his day. Do unto others before they do it to you. A nod is as good as a wink to a blind horse. The bigger they are, the harder they hit. Least said, soonest mended.

 A fool and your money are soon partners
 A nod is as good as a wink to a blind horse
 Do unto others before they do it to you
 Every dog has his day
 Least said, soonest mended
 The bigger they are, the harder they hit
Many a mickle makes a muckle

Program 7.15, page no. 316

In [2]:
print "To use this calculator, enter any expression with or without spaces."
print "An expression may include the operators"
print " +, -, *, /, %, or **(raise to a power)."
print "Use = at the beginning of a line to operate on "
print "the result of the previous calculation."
print "Enter quit to stop the calculator."

result = 0
while True:
    e = raw_input()
    if e == 'quit':
        break
    else:
        try:
            result = eval(str(result) + e)
            print "= ",result
        except ZeroDivisionError:
            print "Division by zero"
To use this calculator, enter any expression with or without spaces.
An expression may include the operators
 +, -, *, /, %, or **(raise to a power).
Use = at the beginning of a line to operate on 
the result of the previous calculation.
Enter quit to stop the calculator.
7/8
=  0
/0
Division by zero
+3
=  3
/2
=  1
**5
=  1
+8
=  9
*2
=  18
quit