Chapter 14: Advanced and Specialized Topics¶

Program 14.1, page no. 592¶

In :
import string
import sys

print "Enter a character: ",
ch = raw_input()

if ch.isalnum():
if ch.isdigit():
print "You entered the digit ", ch
elif ch.islower():
print "You entered a lower case ", ch.upper()
elif ch.isupper():
print "You entered a upper case ", ch.lower()
elif ch in string.punctuation:
print "You entered a punctuation character ", ch
else:
print "You entered ", ch, "but I don't know what it is!"
Enter a character: g
You entered a lower case  G

Program 14.2, page no. 596¶

In :
print "Enter a string of less than 100 characters: ",
text = raw_input()

print "Enter the string sought: ",
sought = raw_input()
sought = sought.lower()
count = 0

sought_len = len(sought)

for i in range(len(text)):
substr = text[i:sought_len+i]
if substr == sought:
count += 1

print "First string entered: ", text
print "Second string entered: ", sought
print "The second string was found in first %d times" %count
The second string was found in first 7 times

Program 14.3, page no. 606¶

In :
cx = 1.0 + 3.0j
cy = 1.0 - 4.0j

sum = cx + cy
diff = cx - cy
product = cx * cy
quotient = cy/cy
conjugate = cx.conjugate()

print "Complex numbers are supported"
print "Working with complex numbers: "
print "Starting values: cx = %.2f%+.2fi cy = %.2f%+.2fi" %(cx.real, cx.imag, cy.real, cy.imag)
print "The sum cx + cy = %.2f%+.2fi" %(sum.real, sum.imag)
print "The difference cx - cy = %.2f%+.2fi" %(diff.real, diff.imag)
print "The product cx * cy = %.2f%+.2fi" %(product.real, product.imag)
print "The quotient cx / cy = %.2f%+.2fi" %(quotient.real, quotient.imag)
print "The conjugate of cx = %.2f%+.2fi" %(conjugate.real, conjugate.imag)
Complex numbers are supported
Working with complex numbers:
Starting values: cx = 1.00+3.00i cy = 1.00-4.00i
The sum cx + cy = 2.00-1.00i
The difference cx - cy = 0.00+7.00i
The product cx * cy = 13.00-1.00i
The quotient cx / cy = 1.00-0.00i
The conjugate of cx = 1.00-3.00i

Program 14.4, page no. 610¶

In :

def get_data(pdata):
pd = pdata
pd *= 3
print "The get_data thread makes it: data.a=%d and data.b=%d " %(pd, pd)

def process_data(pdata):
pd = pdata

mydata = [123, 345]
print "Before starting the get_data thread: mydata.a=%d and mydata. b=%d" %(mydata, mydata)
t1.start()
t2.start()
print "After both threads finish executing: mydata.a=%d and mydata. b=%d" %(mydata, mydata)
Before starting the get_data thread: mydata.a=123 and mydata. b=345
The get_data thread makes it: data.a=369 and data.b=345
After both threads finish executing: mydata.a=369 and mydata. b=345

Program 14.5, page no. 616¶

In :
import math
import time

time.sleep(1)
for i in range(1000000):
x = math.sqrt(3.1415926)