# Python Revision Tour 2 Solutions

Assignment Solutions of Python Revision Tour 2 chapter from the Class 12 Sumita Arora book. Question answer of Computer Science (Python) CBSE Class VII are useful for Board Examinations.

## Python Revision Tour 2 Assignment Solutions for Class 12

Q.1.What is the internal structure of python strings?

Strings in python are stored by storing each character separately in contiguous(next or together in sequence) locations. The characters are given two-way indices:
0,1,2,… size-1 in the forward direction and
-1,-2,-3,…., -size in the backward direction.

Q.2. Write a Python script that traverses through an input string and prints its characters in different lines- two characters per line.

s=input(“Enter the string”)
for i in range(0,len(s),2) :
print(“/n”,s[0+i],s[1+i])

Q.3.Discuss the utility and significance of lists, Briefly.

A list is a standard data type of Python that can store a sequence of values belonging to any type.
The size of a list is not needed to be preset.
Often we need to store a group of values to use them later in the program, this is done using lists, e.g.
L = [‘c’, 5, 67.5, False]

Q.4.What do you understand by mutability? What does “in place” task mean?

Mutability means that in the same memory address, new value can be stored as and when we want. Mutable types are those values can be changed in place means the changes can occur at the same memory location.

a) Set the second entry (index 1) to 17
b) Add 4, 5 and 6 to the end of the list
c) Remove the first entry from the list
d) Sort the list
e) Double the list
f) Insert 25 at index 3

Ans:
l = [8, 9, 10]
a) Set the second entry (index 1) to 17
l = 17
b) Add 4, 5 and 6 to the end of the list
l.extend( [4, 5, 6] ) # extend function can extend the list with the list given in the argument
c) Remove the first entry from the list
del l # del to remove an element
d) Sort the list
l.sort( ) # sorts the original list
e) Double the list
l = 2 * l # this will be equal to l + l
f) Insert 25 at index 3
l = 25

Q.6. What’s a[1:1] if a is a string of at least two characters? And What if string is shorter?
Empty string

Q.7.What are the two ways to add something to a list? How are they different?

Append and Extend
L.append(4) // can only add a element.
L.extend[1,3,4] //add many elements in a list.

Q.8.What are the two ways to remove something from a list? How are they different?

pop(<index>) : pops the element at the index given and returns the value
remove(<value>) : removes the value from the list, nothing is returned

Q.9. What is the difference between a list and a tuple?

List is mutable. Tuple is immutable.
In list datatypes can be added and deleted. In tuple nothing can be added or deleted.

Q.10.In the Python shell , do the following:
(i)Define a variable named states that is an empty list.
(ii) Add ‘Delhi’ to the list.
(iii)Now add ‘Punjab’ to the end of the list.
(iv)Define a variable states2 that is initialized with ‘Rajasthan’, ‘Gujrat’ and ‘Kerala’.
(v)Add ‘Odisha’ to the beginning of the list.
(vi)Add ‘Tripura’ so that it is the third state in the list
(vii)Add ‘Haryana’ to the list so that it appears before ‘Gujrat’ in the list.
(viii)Remove the 5th state from the list and print that state’s name.

Q.11. Discuss the utility and significance of Tuples, briefly.

The tuples are immutable . They are used when the size and elements to be stored are already known. It can store different type of data.
written as tup=(9,10,1). We cannot change the value or add or delete values in Tupple.

Q.12.If a is (1,2,3)
a) what is the difference (if any) between a * 3 and (a, a, a)?
b) is a * 3 equivalent to a + a + a ?
c) what is the meaning of a[1:1]?

d) what’s the difference between a[1:2] and a[1:1]?

Ans:
a) what is the difference (if any) between a * 3 and (a, a, a)?
a * 3 is a tuple of 9 elements, that is, the original 1, 2 and replicated thrice where as (a, a, a) is a tuple of 3 tuples each tuple being a.
a * 3 = (1, 2, 3, 1, 2, 3, 1, 2, 3)
(a, a, a) = ((1, 2, 3), (1, 2, 3), (1, 2, 3))

b) is a * 3 equivalent to a + a + a?
Yes, they both are equal to (1, 2, 3, 1, 2, 3, 1, 2, 3)

c) what is the meaning of a[1:1]?
It is an empty slice of the original tuple a

d) what is the difference between a[1: 2] and a[1: 1]?
a[1: 2] is equal to a or 2 where as a[1: 2] is an empty slice, that is, ( )

Q.13. What is the difference between (30) and (30,) ?

(30) is an integer type.
(30,)is a tuple type.

Q.14. Why is a dictionary termed as an unordered collection of objects.

Ans:
Dictionary is termed as an unordered collection of objects because it doesn’t remember the order of positioning of its elements but just the mapping of its keys and values. For e.g. if
a = {1 : “a”, 2 : “b”}
b = {2 : “b”, 1 : “a”}
a == b is True

Q.15. What type of objects can be used as keys in dictionaries?

Ans:
All immutable type objects can be used as keys in python. Key cannot be of mutable type object.

Q.16. Though tuples are immutable type, yet they cannot always be used as keys in a dictionary. What is the condition to use tuples as a key in a dictionary?

Directly or indirectly the Tuple must not contain any mutable objects. All the elements in Tuple should be immutable .

Q.17. Dictionary is a mutable type, which means you can modify its contents? What all is modifiable in a dictionary? Can you modify the keys of a dictionary?

We can add key value pair in the Dictionary. Keys a re immutable and hence they are not modifiable. Values are modifiable in a dictionary.

Q.18.How is del D and del D[<key>] different from one another if D is a dictionary?

del D is used to delete the whole dictionary while del D[<key>] is used to delete only the key : value pair with the given key.

Q.19. Create a dictionary named D with three entries, for keys ‘a’, ‘b’, and ‘c’. What happens if you try to index a nonexistent key (D[‘d’])? What does Python do if you try to assign to a nonexistent key d?

Ans:
If we try to call with a non-existing key, python will raise an error.
If we try to assign to a non-existent key, an new key : value pair will be added to the dictionary, e.g.

Q.20.What is sorting? Name some popular sorting techniques.

Ans:
Sorting refers to arranging elements in a specific order – ascending or descending.
Some popular sorting techniques or algorithms are Bubble sort, Insertion sort, Selection sort, Heap sort, Quick sort etc.

Q.21. Discuss Bubble sort and Insertion sort techniques.

Ans:
Insertion sort:
· In insertion sort – divide the array into a sorted part and an unsorted part. After each pass the sorted part increases by 1 and the unsorted part decreases by 1.
· In the first step we choose the second element and compare it to the first element and swap if second element is smaller than the first one. Now 1st and 2nd elements are the sorted part and all other elements are the unsorted part.
· Now in each step we choose an element starting from the 3rd element compare it to its previous elements while it is smaller than them and then put it at its correct position in the sorted array.
· For instance the array a = [42, 29, 74, 11, 65] will be sorted like this,
a = [29, 42, 74, 11, 65]
a = [11, 29, 42, 74, 65]
a = [11, 29, 42, 65, 74]
Bubble sort:
· In bubble sort, two adjoining values are compared repetitively and then heavier one gets down the array. In each pass the heaviest element gets settled to its appropriate position, e.g. search and place heaver element.
· For array 35, 6, 8, 11, 15, 9, 7, 22, 41
· After first pass the array becomes,
· 6, 8, 11, 15, 9, 7, 22, 35, 41
· And after the second pass the array becomes
· 6, 8, 11, 9, 7, 15, 22, 35, 41
· This continues until the whole array is sorted.

### Application Based Questions : Python Revision Tour 2 Solutions

Q.1. What will be the output produced by the following code fragments?

a) y=str(123)
x=”hello”*3
print(x,y)
x=”hello”+”world”
y=len(x)
print(y,x)

Output:
hellohellohello 123
10 helloworld

b)
x=”hello”+”to python”+”world”
for char in x:
y=char
print(y,’:’)

```Ans:
Output:
h :
e :
l :
l :
o :
t :
o :
:
p :
y :
t :
h :
o :
n :
w :
o :
r :
l :
d :
```

c)

x=”hello world”
print(x[:2],x[-2],x[-2:])
print(x,x[2:4])
print(x[2:-3],x[-4:-2])

```Ans:
he l ld
w ll
llo wo or```

Q.2.Write a short Python code segment that adds up the lengths of all the words in a list and then prints the average (mean) length. Use the final list from previous question to test your program.

Ans:
Code:
a = eval(input(“Enter list: “))
a = 0
for i in a:
n += len(i)
print(“Mean length is: “, n/len(a))

Q.3.Predict the output of the following code snippet?
a = [ 1, 2, 3, 4, 5 ]
print( a[ 3 : 0 : -1 ] )

Ans:
Output: [ 4, 3, 2 ]

Q.4.Predict the output of the following code snippet?
(a)
arr=[1,2,3,4,5,6]
for i in range(1,6):
arr[i-1]=arr[i]
for i in range(0,6)
print(arr[i],end=””)

Ans: Output: 2 3 4 5 6 6

(b)
Numbers=[9,18,27,36]
for Num in Numbers:
for N in range(1,Num%8):
print(N,”#”,end=””)
print()

Ans:
1 #
1 # 2 #
1 # 2 # 3 #

Q.5. Find the errors. State reasons?
(a)
t=(1,”a”,9.2)
t=6

Error tuples are immutable.cannot be changed.

(b)
t=[1,”a”,9.2]
t=6

No error.

(c)
t = [ 1, “a”, 9.2 ]
t = 6

Ans:
Error: Index 4 doesn’t exist

d)
t = ‘hello’
t = “H”

Ans:
Error: Strings are immutable and its characters can’t be changed

e)
for Name in [ Amar, Shveta, Parag ]
IF Name = ‘S’:
print( Name )

Ans:
Error:
· The names are not defined, they should be in quotes, “:” is missing in for loop.
· IF is not a keyword, ‘if’ should be used, single ‘=’ is used for assignment, ‘==’ should be used.

Q6. Assuming words is a valid list of words, the program below tries to print the list in reverse. Does it have an error? If so, why?

for i in range(len(words),0,-1):
print(world[i],end=”)
The range is setted to zero so nothing will be printed. length is positive.

7.What would be the output of following code if ntpl = (“Hello”,”Nita”,”how’s,”life”)?
(a,b,c,d)=ntpl
print(“a is :”,a)
print(“b is :”,b)
print(“c is :”,c)
print(“d is :”,d)
ntpl= (a,b,c,d)
print(ntpl+ntpl,ntpl)

Output:
a is: Hello
b is: Nita
c is: How’s
d is: life ?
Hi Nita

8.What will be the output of the following code?
tuple_a=’a’,’b’
tuple_b=(‘a’,’b’)
print(tuple_a==tuple_b)
(a)0
(b)1
(c)false
(d)True

Ans:
Tuples can be defined in both the value shown above. it will show True (d) option.

9. What will be the output of the following code snippet?
rec = { “Name” : “Python” , “Age” : “20” , “Addr” ; “NJ” , “Country” : “USA”}
id1 = id(rec)
del rec
rec = { “Name ” : “Python” , “Age” : “20” , “Addr ” ;”NJ”, “Country ” : “USA”}
id2=id(rec)
print (id1==id2)
(a ) true
(b) false
(c) 1
(d) exception

(a)True

10. What will be the output of the following code snippet?
my_dict={}
my_dict[(1,2,4)]=8
my_dict[(4,2,1)]=10
my_dict[(1,2)]=12
sum=0
for k in my_dict:
sum +=my_dict[k]
print(sum)
print(my_dict)

30
{(1, 2, 4) : 8, (4, 2, 1) : 10, (1, 2) : 12}

11. Write a method in python to display the elements of list thrice if it is a number and display the element terminated with ‘#’ if it is not a number.

Ans:
Code:
l = [‘41’, ‘DROND’, ‘GIRIRAJ’, ‘13’,’zara’]
for word in l:
if word.isdigit( ): # check if all character are digits
print(word*3)
else:
print(word+’#’) # print word+’#.

12. Name the function/method required to
(i) check if a string contains only uppercase letters
(ii) gives the total length of the list.

Ans:
(i)
x=”ASDFGHJK”
print(x.isupper( )) # True
(ii)
L=[p,q,r]
print(len(L))

### Programming based Questions : Python Revision Tour 2 Solutions

1.Write a program that prompts for a phone number of 10 digits and two dashes, with dashes after the area code and the next three numbers. For example, 017-555-1212 is a legal input. Display if the phone number entered is valid format of not and display if the phone number is valid or not (i.e., contains just the digits and dash at specific places).

```Answer:
i=0
n = input("Enter a 10 digit phone number: ")

if len(n) == 12:

if n == "-" and n == "-":

count = 0

#print(i)
for i in n:

if i.isdigit():

count+=1

if count == 10:

print("Valid Number")
else:

else:

print("Please enter a '-' after the area code and the next numbers")

#print(i)
else:

print("Invalid Length")```

2. Write a program that should prompt the user to type some sentence(s) followed by “enter”. It should then print the original sentence(s) and the following statistics relating to the sentence(s):

```Ans:
a = input("Enter a sentence and type enter at the end: ")

if a[-1: -6: -1][::-1] == "enter":

l=a.split()

print("There are", len(l)-1, "words")

print("There are", len(a)-6, "characters")

alnum = -5

for i in a:

if i.isalnum():

alnum+=1

print((alnum/(len(a)-6))*100, "% of characters are alphanumeric")

else:

print("You did not type enter at the end of your sentence")
```

3. Write a program that takes any two lists L and M of the same size and adds their elements together to form a new list N whose elements are sums of the corresponding elements in L and M. For instance, if L=[3, 1, 4] and M=[1, 5, 9], then N should equal [4, 6, 13]

```Ans:
l = eval(input("Enter a list of numbers: "))

n = eval(input("Enter a list of numbers with the same no of elements as the previous list: "))

a = []

for i in range(len(l)):

a.append(l[i]+n[i])

print(a)```

4.Write a program that rotates the elements of a list so that the element at the first index moves to the second index, the element in the second index moves to the third index, etc., and the element in the last index moves to the first index..

```Ans:
n = eval(input("Enter a list: "))

n.insert(0,n[-1])

del n[-1]

print(n)```

5.Write a short Python code segment that prints the longest word in a list of words.

```Answer:
a = eval(input("Enter a list of strings: "))

large = ''

for i in a:

if len(i)>len(large):

large=i

print(large)```

6. Write a program that creates a list of all the integers less than 100 that are multiples of 3 or 5.

```Answer:
a = []

for i in range(1, 101):

if i%3==0 or i%5==0:

a.append(i)

print(a)```

7.Define two variables first and second so that first = “Jimmy” and second = “Johny”. Write a short Python code segment that swaps the values assigned to these two variables and prints the results.

```Answer:
first = "Jimmy"

second = "Johnny"

first, second = second, first

print(first)

print(second)```

8.Write a Python program that creates a tuple storing first 9 terms of Fibonacci series.

```Answer:
l = [0,1]

a = 0

b = 1

c = 0

for i in range(7):

c = a+b

a = b

b = c

l.append(c)

print(tuple(l))```

9.Create a dictionary whose keys are month names and whose values are the number of days in the corresponding months.

```Answer:

d = {"January":31, "February":28, "March":31, "April":30, "May":31, "June":30, "July":31, "August":31, "September":30, "October":31, "November":30, "December":31}

a = input("Enter the name of the month: ")

for i in d.keys():

if i==a:

print("There are ",d[i],"days in ",a)

print()

print("Months arranged in alphabetical order: ", end="")

b=[]

for i in d.keys():
b.append(i)

b.sort()

print(b)

print()

print("Months with 30 days: ", end="")

for i in d.keys():

if d[i]==30:

print(i, end="")

print()

print()
c = [("February",28)]

for i in d.keys():

if d[i]==30:

c.append((i,30))

for i in d.keys():

if d[i]==31:

c.append((i,31))

print(c)```

10. Write a function called addDict(dict1, dict2) which computes the union of two dictionaries. It should return a new dictionary, with all the items in both its arguments (assumed to be dictionaries). If the same key appears in both arguments, feel free to pick a value from either.

```Answer:

dict1.update(dict2)

print(dict1)

a=eval(input("Enter a dictionary: "))

b=eval(input("Enter another dictionary: "))

11.Write a program to sort a dictionary’s keys using Bubble sort and produce the sorted keys as a list.

```Answer:
a = eval(input("Enter a dictionary: "))

b = a.keys()

c = []

for i in b:

c.append(i)

for i in range(len(c)):

for j in range(len(c)-i-1):

if c[j]>c[j+1]:

c[j],c[j+1]=c[j+1],c[j]

print(c)```

12. Write a program to sort a dictionary’s values using Bubble sort and produce the sorted values as a list.

```Answer:

a=eval(input("Enter a dictionary: "))

b=a.values()

c = []

for i in b:

c.append(i)

for i in range(len(c)):

for j in range(len(c)-i-1):

if c[j]>c[j+1]:

c[j],c[j+1]=c[j+1],c[j]

print(c)```

We are also providing the solutions of all the chapters of Computer Science (Python) in this site. the links of relevant topics are provided below:

Computer Science with Python Class 12 Sumita Arora Solutions – CS Study