Chapter 7: Arrays and Strings

Example 7.1, Page Number 264

In [1]:
age = []*4                            #array 'age' of 4 

for j in range(4):                    #get 4 ages
    x = input("Enter an age: ")
    age.append(x)                     #access array element

    
for j in range(4):                    #display 4 ages
    print '\nYou entered',age[j],
Enter an age: 44
Enter an age: 16
Enter an age: 23
Enter an age: 68

You entered 44 
You entered 16 
You entered 23 
You entered 68

Example 7.2, Page Number 267

In [2]:
SIZE = 6                   #size of array
sales = []*SIZE            #array of 6 variables

print 'Enter widget sales for 6 days'

for j in range(SIZE):      #put figures in array
    x = input()
    sales.append(x)
    
total = 0

for j in range(SIZE):      #read figures from array
    total += sales[j]      #to find total
    
average = total / SIZE     #find average

print 'Average =',average,'\n'
Enter widget sales for 6 days
352.64
867.70
781.32
867.35
746.21
189.45
Average = 634.111666667 

Example 7.3, Page Number 268

In [3]:
days_per_month = (31,28,31,30,31,30,31,31,30,31,30,31)

month = input("Enter month (1 to 12): ")      #get date
day = input("Enter day (1 to 31): ")


total_days = day                #separate days

for j in range(month-1):                  #add days each month
    total_days += days_per_month[j] 
    
print 'Total days from start of year is:',total_days
Enter month (1 to 12): 3
Enter day (1 to 31): 11
Total days from start of year is: 70

Example 7.4, Page Number 270

In [4]:
DISRICTS = 4                   #array dimensions
MONTHS = 3

sales = [[0] * (DISRICTS+1) for i in range(MONTHS+1)]            #two-dimensional array definition


print '',
for d in range(DISRICTS):                          #get array values
    for m in range(MONTHS):
        print 'Enter sales for district',d+1,
        print ', month',m+1,': ',
        sales[d][m] = input()                      #put number in array
        
        
print '\n'
print '                             month'
print '                 1           2           3',


for d in range(DISRICTS):
    print '\nDistrict',d+1,
    for m in range(MONTHS):
        print '%10.2f' %(sales[d][m]),          #get number from array
 Enter sales for district 1 , month 1 : 3964.23
 Enter sales for district 1 , month 2 : 4135.87
 Enter sales for district 1 , month 3 : 4397.98
 Enter sales for district 2 , month 1 : 867.75
 Enter sales for district 2 , month 2 : 923.59
 Enter sales for district 2 , month 3 : 1037.01
 Enter sales for district 3 , month 1 : 12.77
 Enter sales for district 3 , month 2 : 378.32
 Enter sales for district 3 , month 3 : 798.22
 Enter sales for district 4 , month 1 : 2983.53
 Enter sales for district 4 , month 2 : 3983.73
 Enter sales for district 4 , month 3 : 9494.98
 

                             month
                 1           2           3 
District 1    3964.23    4135.87    4397.98 
District 2     867.75     923.59    1037.01 
District 3      12.77     378.32     798.22 
District 4    2983.53    3983.73    9494.98

Example 7.5, Page Number 273

In [5]:
DISRICTS = 4                                 #array dimensions
MONTHS = 3

                                             #initialize array elements
sales = [[1432.07,234.50,654.01],
         [322.00,13838.32,17589.88],
         [9328.34,934.00,4492.30],
         [12838.29,2332.63,32.98]]
        
print '\n'
print '                             month'
print '                 1           2           3',


for d in range(DISRICTS):                    #display array elements
    print '\nDistrict',d+1,
    
    for m in range(MONTHS):
        print '%10.2f' %(sales[d][m]),       #access array elements

                             month
                 1           2           3 
District 1    1432.07     234.50     654.01 
District 2     322.00   13838.32   17589.88 
District 3    9328.34     934.00    4492.30 
District 4   12838.29    2332.63      32.98

Example 7.6, Page Number 274

In [6]:
DISRICTS = 4                   #array dimensions
MONTHS = 3

def display(funsales):         #function for display array elements
    print '\n'
    print '                             month'
    print '                 1           2           3',

    for d in range(DISRICTS):
        print '\nDistrict',d+1,
        for m in range(MONTHS):
            print '%10.2f' %(sales[d][m]),         #access array elements
            
            
            
sales = [[1432.07,234.50,654.01],           #initialize two-dimentional array
         [322.00,13838.32,17589.88],
         [9328.34,934.00,4492.30],
         [12838.29,2332.63,32.98]]

display(sales)                       #call function; array as argument

                             month
                 1           2           3 
District 1    1432.07     234.50     654.01 
District 2     322.00   13838.32   17589.88 
District 3    9328.34     934.00    4492.30 
District 4   12838.29    2332.63      32.98

Example 7.7, Page Number 277

In [7]:
SIZE = 4                    #number of parts in array

class part:                 #specify a structure
    modelnumber = None      #ID number of widget
    partnumber = None       #ID number of widget part
    cost = None             #cost of part
    
    
    
apart = [part() for i in range(SIZE)]         #define array of structures


for n in range(SIZE):                         #get values for all members
    apart[n].modelnumber = input('Enter model number: ')          #get model number
    apart[n].partnumber = input('Enter part number: ')            #get part number
    apart[n].cost = input('Enter cost: ')                         #get cost
    print 
    
    
for n in range(SIZE):                          #show values for all members
    print 'Model',apart[n].modelnumber,
    print ' Part',apart[n].partnumber,
    print ' Cost',apart[n].cost
Enter model number: 44
Enter part number: 4954
Enter cost: 133.45

Enter model number: 44
Enter part number: 8431
Enter cost: 97.59

Enter model number: 77
Enter part number: 9343
Enter cost: 109.99

Enter model number: 77
Enter part number: 4297
Enter cost: 3456.55

Model 44  Part 4954  Cost 133.45
Model 44  Part 8431  Cost 97.59
Model 77  Part 9343  Cost 109.99
Model 77  Part 4297  Cost 3456.55

Example 7.8, Page Number 279

In [8]:
class Stack:
    __max = 10            #define maximum size of stack array
    
    def __init__(self):                                    #constructor
        self.__st = [0 for i in range(self.__max)]         #stack: array of integers
        self.__top = -1                                    #number of top of stack, initially -1
     
    def push(self,var):                #put number on stack
        self.__top += 1
        self.__st[self.__top] = var
        
    def pop(self):                     #take number from stack
        x = self.__st[self.__top]
        self.__top -= 1
        return x
    
    
    
s1 = Stack()              #define a stack variable

s1.push(11)               #push value on stack
s1.push(22)

print '1:',s1.pop()       #pop value from stack, and display it
print '2:',s1.pop()

s1.push(33)               #push values on stack
s1.push(44)
s1.push(55)
s1.push(66)

print '3:',s1.pop()       #pop values from stack
print '4:',s1.pop()
print '5:',s1.pop()
print '6:',s1.pop()
1: 22
2: 11
3: 66
4: 55
5: 44
6: 33

Example 7.9, Page Number 283

In [9]:
class Distance:                     #Distance class
    
    def getdist(self):              #get length from usser
        self.__feet = input('   Enter feet: ')
        self.__inches = input('   Enter inches: ')
        
    def showdist(self):            #display distance
        print self.__feet,'\' -',self.__inches,'\"',
        
        
        
dist = [Distance() for i in range(100)]                #array of distances
n = 0                                                  #count the entries


while True:                                            #get distances from user
    
    print '\nEnter distance number',n+1
    dist[n].getdist()                                  #store distances in array
    n += 1 
    
    ans = raw_input('Enter another (y/n)?: ')
    if(ans == 'n'):                                    #quit if user types 'n'
        break
        
for j in range(n):                                     #display all distances
    print '\nDistance number',j+1,'is',
    dist[j].showdist()
Enter distance number 1
   Enter feet: 5
   Enter inches: 4
Enter another (y/n)?: y

Enter distance number 2
   Enter feet: 6
   Enter inches: 2.5
Enter another (y/n)?: y

Enter distance number 3
   Enter feet: 5
   Enter inches: 10.75
Enter another (y/n)?: n

Distance number 1 is 5 ' - 4 " 
Distance number 2 is 6 ' - 2.5 " 
Distance number 3 is 5 ' - 10.75 "

Example 7.10, Page Number 286

In [10]:
from random import randrange                          #for selecting random number

symbols = ['♣','♦','♥','♠']             #array for printing the symbol of cards
Suit = ["clubs","diamonds","hearts","spades"]  


#from 2 to 10 are integers without names
jack = 11      
queen = 12 
king = 13
ace = 14


class card:       
    
    def __init__(self):             #constructor
        self.__number = None
        self.__suit = None
        
    def set(self,n,s):
        self.__number = n           #2 to 10, jack, queen, king, ace
        self.__suit = s             #clubs, diamonds, hearts, spades
        
    
    def display(self):              #display the cards
        
        if self.__number >= 2 and self.__number <= 10:       #display the card number
            print self.__number ,
            
        else:
            if self.__number == jack:
                print 'J',
            elif self.__number == queen:
                print 'Q',
            elif self.__number == king:
                print 'K',
            elif self.__number == ace:
                print 'A',
                
        if self.__suit == "clubs":              #dispaly the symbol
            print symbols[0],
        elif self.__suit == "diamonds":
            print symbols[1],
        elif self.__suit == "hearts":
            print symbols[2],
        elif self.__suit == "spades":
            print symbols[3],
            
            
            
            
deck = [card() for j in range(52)]           #array of cards

for j in range(52):                      #make an ordered deck
    num = (j % 13) + 2                   #cycles through 2 to 14, 4 times
    su = Suit[j / 13]                    #cycles through 0 to 3, 13 times
    deck[j].set(num,su)                  #set cards

    
print '\nOrderd deck:'

for j in range(52):                      #display ordered deck
    deck[j].display()
    print '',
    if (j+1)%13 == 0:                    #new line every 13 cards
        print

        
        
for j in range(52):                      #for each card in deck,
    
    k = randrange(2,52)%52        #pick card at random
    
    temp = deck[j]                       #and swap them
    deck[j] = deck[k]
    deck[k] = temp

print '\nshuffled deck:'

for j in range(52):                      #display suffled card
    deck[j].display()                    
    print '',
    if (j+1)%13 == 0:                    #new line every 13 cards
        print
Orderd deck:
2 ♣  3 ♣  4 ♣  5 ♣  6 ♣  7 ♣  8 ♣  9 ♣  10 ♣  J ♣  Q ♣  K ♣  A ♣ 
2 ♦  3 ♦  4 ♦  5 ♦  6 ♦  7 ♦  8 ♦  9 ♦  10 ♦  J ♦  Q ♦  K ♦  A ♦ 
2 ♥  3 ♥  4 ♥  5 ♥  6 ♥  7 ♥  8 ♥  9 ♥  10 ♥  J ♥  Q ♥  K ♥  A ♥ 
2 ♠  3 ♠  4 ♠  5 ♠  6 ♠  7 ♠  8 ♠  9 ♠  10 ♠  J ♠  Q ♠  K ♠  A ♠ 

shuffled deck:
J ♦  5 ♦  7 ♣  7 ♦  4 ♦  2 ♦  J ♣  10 ♥  5 ♣  8 ♣  6 ♥  2 ♥  6 ♣ 
8 ♦  3 ♠  8 ♠  K ♠  7 ♠  2 ♠  Q ♥  K ♦  6 ♠  10 ♠  8 ♥  6 ♦  K ♣ 
7 ♥  10 ♦  3 ♦  Q ♦  Q ♠  J ♥  9 ♦  9 ♥  9 ♠  J ♠  K ♥  4 ♣  A ♥ 
4 ♥  5 ♥  A ♣  5 ♠  2 ♣  4 ♠  9 ♣  Q ♣  A ♦  3 ♥  3 ♣  10 ♣  A ♠ 

Example 7.11, Page Number 290

In [11]:
MAX = 80                               #max characters in string
str = [0 for i in range(MAX)]          #string variable str

str = raw_input("Enter a string ")     #put string in str

print 'You entered:',str             #display string from str
Enter a string amanuensis
You entered: amanuensis

Example 7.12, Page Number 292

In [12]:
MAX = 20              #max characters in string
str = []*MAX          #string variable str

str = raw_input("Enter a string: ")        #put string in str

print 'You entered: %20s' %str             #display string from str
Enter a string: hello world.....
You entered:     hello world.....

Example 7.13, Page Number 292

In [13]:
str = []

str = "Farewell! thou art too dear for my possessing."      #store string in an array

print str,'\n'          #print array
Farewell! thou art too dear for my possessing. 

Example 7.14, Page Number 293

In [14]:
MAX = 20              #max characters in string
str = []*MAX          #string variable str

str = raw_input("Enter a string: ")     #put string in str

print 'You entered:',str                #display string from str
Enter a string: Law is a bottomless pit.
You entered: Law is a bottomless pit.

Example 7.15, Page Number 294

In [15]:
print 'Enter a string:'

str = ""                     #string variable
stopword = "$"               #taking for checking the termination condition


while True:
    
    line = raw_input()               #taking input line by line
    
    if line.strip() == stopword:     #stop when tenmination condition matches
        break
        
    str += "%s\n" % line
    
    
print 'You entered:'
print str                   #print the whole string
Enter a string:
Ask me no more where Jove bestows
When June is past, the fading rose;
For in your beauty's orient deep
These flowers, as in their causes, sleep.
$
You entered:
Ask me no more where Jove bestows
When June is past, the fading rose;
For in your beauty's orient deep
These flowers, as in their causes, sleep.

Example 7.16, Page Number 295

In [16]:
str1 = []                                       #initialized string
str1 = "Oh, Captain, my Captain! our fearful trip is done"

MAX = 80                    #size of str2 buffer
str2 = [None]*MAX           #empty string

str2 = ''.join(str1)        #copy str1 character to str2

print str2                  #print str2
Oh, Captain, my Captain! our fearful trip is done

Example 7.17, Page Number 296

In [17]:
str1 = []

str1 = "Tiger, tiger, burning bright\nIn the forests of the night"

MAX = 80                    #size of str2 buffer
str2 = str1                 #copy str1 to str2

print str2                  #display str2
Tiger, tiger, burning bright
In the forests of the night

Example 7.18, Page Number 297

In [18]:
Days = 7                      #number of string in array

star = ["Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday"]          #arrray of string

for j in range(Days):         #display every string
    print star[j]
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Example 7.19, Page Number 298

In [19]:
class part:
    
    def setpart(self,pname,pn,c):                    #set data
        self.__partname = pname
        self.__partnumber = pn
        self.__cost = c
        
    def showpart(self):                              #display data         
        print 'Name %s,'     %self.__partname,
        print 'number %d,'   %self.__partnumber,
        print 'costs $%.2f'  %self.__cost
        
        
#define part objects        
part1 = part()
part2 = part()

part1.setpart("handle bolt",4473,217.55)             #set parts
part2.setpart("start level",9924,419.25)
 
print 'First part:'                                  #show part
part1.showpart()
print 'Second parrt:'
part2.showpart()
First part:
Name handle bolt, number 4473, costs $217.55
Second parrt:
Name start level, number 9924, costs $419.25

Example 7.20, Page Number 300

In [20]:
class String:
    
    def __init__(self,s = '\0'):               #overloaded constructor
        self.__str = s
        
    def display(self):                         #display string
        print self.__str
        
    def concat(self,s2):                       #add argument string to this string
        if len(self.__str)+len(s2.__str) < 80:
            self.__str = self.__str + s2.__str
        else:
            print 'String too long'
        
        
        
s1 = String("Merry Christmas!  ")              #define the string
s2 = String("Season's Greetings!")
s3 = String()

print 's1 =',               #display them all
s1.display()
print 's2 =',
s2.display()
print 's3 =',
s3.display()

s3 = s1                     #assignment

print 's3 =',               #display s3
s3.display()

s3.concat(s2)               #concatenation

print 's3 =',               #display s3
s3.display()
s1 = Merry Christmas!  
s2 = Season's Greetings!
s3 = 
s3 = Merry Christmas!  
s3 = Merry Christmas!  Season's Greetings!

Example 7.21, Page Number 303

In [21]:
s1 = "Man"                 #initialize
s2 = "Beast"

s3 = s1                    #assign
print 's3 =',s3

s3 = "Neither " + s1 + " Nor "         #concatenate
s3 += s2                               #concatenate
print 's3 =',s3
 
s4 = s2                    #swap s1 and s2
s2 = s1
s1 = s4

print s1 , 'nor' , s2
s3 = Man
s3 = Neither Man Nor Beast
Beast nor Man

Example 7.22, Page Number 304

In [22]:
greeting = "Hello, "

full_name = raw_input("Enter your full name: ")            #get the name of user
print 'Your full name is:',full_name

nickname = raw_input("Enter your nickname: ")              #get the nickname
 
greeting += nickname                                       #append name with greeting
print greeting                                             #output: "Hello, Jim"

print 'Enter your address on separate lines'
print 'Terminate with \'$\''

address = ""
stopword = "$"

while True:
    line = raw_input()               #taking input line by line
    if line.strip() == stopword:     #stop when tenmination condition matches
        break
    address += "%s\n" % line
    
print 'Your address is:'
print address                   #print the whole string
Enter your full name: F. Scott Fitzgerald
Your full name is: F. Scott Fitzgerald
Enter your nickname: Scotty
Hello, Scotty
Enter your address on separate lines
Terminate with '$'
1922 Zelda Lane
East Egg, New York
$
Your address is:
1922 Zelda Lane
East Egg, New York

Example 7.23, Page Number 305

In [23]:
def find_first_not_of(s1,s2):
    
    a = len(s2)                        #length of the string to be checked
    
    arr = [99 for j in range(a)]       #array for storing the matches index
    
    for j in range(a):
        n = s1.find(s2[j])             #A character of second string is present in the first string then 
        if n!=-1:
            arr[j] = n                 #put the index in the array
            
    arr.sort()                         #sort the array to check first occarence
    
    return arr[0]+1                    #return the first index



s1 = "In xanada did Kubla Kahn a stately pleasure dome decree"

n = s1.find("Kubla")
print 'Found kubla at',n

n = s1.index("d")
print 'First of spde at',n

n = find_first_not_of(s1,"aeiouAEIOU")
print 'Found consonant at',n
Found kubla at 14
First of spde at 7
Found consonant at 1

Example 7.24, Page Number 306

In [24]:
s1 = "Quick! Send for Count Graystone."
s2 = "Lord"
s3 = "Don't "

s1 = s1[7:]                          #remove "Quick! "
s1 = s1.replace("Count",s2)          #replace "Count" with "Lord"
s1 = s1.replace("S","s")             #replace 'S' with 's'
s1 = s3 + s1                         #insert "Don't " at beginning
s1 = s1[:-1]                         #remove '.'
s1 = s1 + "!!!"                      #append "!!!"
s1 = s1.replace(" ","/")             #replace all white space with '/'
    
print s1
Don't/send/for/Lord/Graystone!!!

Example 7.25, Page Number 308

In [25]:
aName = "George"

username = raw_input("Enter your first name: ")

if username == aName:                    #operator ==
    print "Greetings, George"
    
elif username < aName:                   #operator <
    print 'You come before George'
    
else:
    print 'You come after George'
    
    
    
print 'The first two letters of your name',    

username = username[:2]
aName = aName[:2]

if username == aName:
    print "match",
elif username < aName:
    print 'come before',
else:
    print 'come after',
print aName
Enter your first name: Alfred
You come before George
The first two letters of your name come before Ge

Example 7.26, Page Number 309

In [26]:
word = raw_input("Enter a word: ")    #take string from user
wlen = len(word)                      #length of string object

print 'One character at a time: ',
for j in range(wlen):
    print word[j],
    
charray = []*80
charray = word                        #copy string object to another object
print '\nArray contains:',charray
Enter a word: symbiosis
One character at a time:  s y m b i o s i s 
Array contains: symbiosis
In [ ]: