Chapter 8: Arrays

Example reverse.c, Page 164

In [5]:
N=10
li = raw_input("Enter %d numbers: " % N) #accepting input in list
a = map(int, li.split()) 
print "In reverse order: ",
for i in a[::-1]: #print reversed list
    print i,
Enter 10 numbers: 34 82 49 102 7 94 23 11 50 31
In reverse order:  31 50 11 23 94 7 102 49 82 34

Example repdigit.c, Page 166

In [7]:
digit_seen=[False]*10 #initialise with false
n=int(raw_input("Enter a number: "))#input number
while(n>0): #calculate if any digit repeated
    digit=n%10
    if (digit_seen[digit]==True):
        break
    digit_seen[digit]=True
    n=n/10
if(n>0): 
    print "Repeated digit" #print result
else:
    print "No repeated digit"
Enter a number: 28212
Repeated digit

Example interest.c, Page 169

In [2]:
import sys
#initialisation
value=[None]*5 
NUM_RATES=int(sys.getsizeof(value)/sys.getsizeof(value[0]))-1
INITIAL_BALANCE=100.00
#accept input
low_rate=int(raw_input("Enter interest rate: "))
num_years=int(raw_input("Enter number of years: "))
print ""
#print calculated result table
print "Years",
for i in range (NUM_RATES):
    print "%6d%%" % (low_rate + i),
    value[i]=INITIAL_BALANCE
print ""
for year in range (num_years):
    print "%3d\t"%(year+1),
    for i in range (NUM_RATES):
        value[i]=value[i]+ (low_rate+i)/100.0*value[i]
        print "%7.2f"%value[i],
    print ""
    
Enter interest rate: 6
Enter number of years: 5

Years      6%      7%      8%      9%     10% 
  1	 106.00  107.00  108.00  109.00  110.00 
  2	 112.36  114.49  116.64  118.81  121.00 
  3	 119.10  122.50  125.97  129.50  133.10 
  4	 126.25  131.08  136.05  141.16  146.41 
  5	 133.82  140.26  146.93  153.86  161.05 

Example deal.c, Page 173

In [2]:
import random
#initialisation
NUM_SUITS=4
NUM_RANKS=13
in_hand = [[False for i in xrange(13)] for i in xrange(4)]
rank_code=['2','3','4','5','6','7','8','9','t','j','q','k','a']
suit_code=['c','d','h','s']
#accet input
num_cards=int(raw_input("Enter number of cards in hand: "))
print "Your hand: ",
while(num_cards>0):
    suit=random.randint(0,(NUM_SUITS-1)) #generate random suit
    rank=random.randint(0,(NUM_RANKS-1)) #generate random rank
    if (in_hand[suit][rank]!=True):
        in_hand[suit][rank]=True
        num_cards=num_cards-1
        #print hand
        print "%c%c" % (rank_code[rank],suit_code[suit]),
print ""
Enter number of cards in hand: 5
Your hand:  9h 4d 5d 3d ad 

Example reverse2.c, Page 174

In [3]:
n=int(raw_input("How many numbers do you want to reverse?")) #accept number of elements
li = raw_input("Enter %d numbers: " % n) #accepting input in list
a = map(int, li.split())
print "In reverse order: ", #print reversed list
for i in a[::-1]:
    print i,
How many numbers do you want to reverse?10
Enter 10 numbers: 34 82 49 102 7 94 23 11 50 31
In reverse order:  31 50 11 23 94 7 102 49 82 34
In [ ]: