The Joy of Computing Using Python: Assignment 3
The Joy of Computing Using Python: Assignment 3
Assignment 3
(a) sum=0
w e i g h t s =[97 , 5 2 , 6 5 , 4 3 , 7 7 ]
f o r w in w e i g h t s :
sum=sum+w
print (sum)
(b) sum=0
w e i g h t s =[97 , 5 2 , 6 5 , 4 3 , 7 7 ]
f o r w in range ( len ( w e i g h t s ) ) :
sum=sum+w
print (sum)
(c) sum=0
w e i g h t s =[97 , 5 2 , 6 5 , 4 3 , 7 7 ]
f o r w in w e i g h t s :
sum=sum+w
print (sum)
(d) sum=0
w e i g h t s =[97 , 5 2 , 6 5 , 4 3 , 7 7 ]
f o r w in w e i g h t s :
sum=w
print (sum)
1
CORRECT ANSWER: (a)
First option is correct. Indenting is wrong in the second and third options whereas in the third option, the
sum is not calculated by adding the items in the list in the last option.
3. Consider a python list named ‘book titles’. Pick the statement to add ‘Who moved my cheese?’ as the third
item.
Given: book titles = [‘Exam Warriors’, ‘Evil in the Mahabharata’, ‘6 TIMES THINNER’, ‘The Driver in the
Driverless Car’, ‘Evolution’]
2
(d) roll= random.random(6)
CORRECT ANSWER: (c)
8. Which of the plots in the options is most likely to be generated from the following code?
import random
import m a t p l o t l i b . p y p l o t a s p l t
def p l a y ( ) :
amt=0
f o r i in range ( 0 , 1 0 0 ) :
r=random . r a n d i n t ( 1 , 1 0 0 0 )
i f ( r !=random . r a n d i n t ( 1 , 1 0 0 0 ) ) :
amt=amt
else :
amt=amt+1000
return amt
l =[]
f o r j in range ( 0 , 1 0 0 ) :
s=0
f o r i in range ( 0 , 1 0 0 ) :
s=s+p l a y ( )
l . append ( s )
x =[]
y =[]
f o r each in l i s t ( set ( l ) ) :
x . append ( each )
y . append ( l . count ( each ) )
p l t . p l o t (x , y , ' ro ' )
p l t . show ( )
(a)
(b)
3
(c)
(d)
9. Assuming, there is no file named ‘file.txt’ on my computer, what does the following code do?
with open ( ' f i l e . t x t ' , ' w ' ) a s f :
f . w r i t e ( ' Hey ! I am w r i t i n g . ' ) ;
f . close ()
with open ( ' f i l e . t x t ' , ' w ' ) a s f :
f . w r i t e ( ' Hey I am w r i t i n g t h e s e c o n d l i n e . ' ) ;
f . close ()
with open ( ' f i l e . t x t ' , ' r ' ) a s f :
print ( f . r e a d ( ) )
f . close ()
(a) [‘i’, ‘ ’, ‘a’, ‘m’, ‘ ’, ‘t’, ‘o’, ‘ ’, ‘g’, ‘o’, ‘ ’, ‘t’, ‘o’, ‘ ’,
‘K’, ‘T’, ‘ ’, ‘i’, ‘n’, ‘ ’, ‘A’]
(b) [‘i’, ‘a’, ‘m’, ‘t’, ‘o’, ‘g’, ‘o’, ‘t’, ‘o’, ‘K’, ‘T’, ‘i’, ‘n’, ‘A’]
(c) [‘i’, ‘am’, ‘to’, ‘go’, ‘to’, ‘KT’, ‘in’, ‘A’]
(d) [‘i’, ‘ ’, ‘am’,‘ ’, ‘to’,‘ ’, ‘go’,‘ ’, ‘to’,‘ ’, ‘KT’,‘ ’, ‘in’,‘ ’,
‘A’]
4
CORRECT ANSWER: (a)
First option is correct because every element including whitespace in the input string becomes an element in
the output list.