CHAPTER 10. : VECTORS

example 10.1 page no :103

In [1]:
'''
example 10.1 page no :103
''' 

values = [] 
c = int(raw_input())
while(c != -1):
    values.append(c)
    c = int(raw_input())

size=len(values)
for i in range(size):
    print values[i] 
5
4
3
2
-1
5
4
3
2

example 10.2 page no :104

In [2]:
'''
example 10.2 page no :104
'''
import random

for i in range(4):
    x = random.random();
    print  x
0.16979844903
0.113100369897
0.851107623696
0.0966914962921

example 10.3 page no :105

In [3]:
'''
example 10.3 page no :105
'''
import random
def randomVector(n,upperBound):
    vec = []
    for i in range(n):
        vec.append(random.random () * 100 % upperBound)
    return vec

def printVector(vec):
    for i in range(len(vec)):
        print vec[i] ,

numValues = 20;
upperBound = 10;
vector = randomVector (numValues, upperBound);
printVector(vector)
1.84318995426 8.49475291756 7.92488160107 3.93550646061 0.967457025838 6.72758767668 6.22192058422 8.19279912461 7.4898535715 3.02785494125 2.97556694487 4.70451449621 8.21039455753 2.95832700489 7.02858630112 8.72631899097 5.67567455024 7.48090989023 9.14911759876 9.82069257056

example 10.4 page no: 106

In [4]:
'''
example 10.4 page no: 106
'''
import random
def howMany(vec,value):
    count = 0
    for i in range(len(vec)):
        if (vec[i] == value):
            count += 1
    return count

def randomVector(n,upperBound):
    vec = []
    for i in range(n):
        vec.append(int(random.random () * 100 % upperBound))
    return vec
    
numValues = 20;
upperBound = 10;
vector = randomVector (numValues, upperBound);
print "value \t howMany"
for i in range(upperBound):
    print i , '\t' , howMany(vector, i)
value 	 howMany
0 	2
1 	2
2 	0
3 	4
4 	3
5 	1
6 	2
7 	1
8 	2
9 	3
In [ ]: