PRIP 2.1 Sumita Arora Solutions | Class 12 Computer Science

Here are PRIP 2.1 Sumita Arora Solutions for class 12 Computer Science. To view Sumita Arora solutions for all chapters, visit here.

Q.1: What is a string slice ?  If a = “blueberry” evaluate the following:    
(a) a[2:3] 
    (b) a[2:] 
    (c)a[:3] 
    (d) a[:] 
    (e) a[-1:-3] 
    (f) a[:-1] 
    (g) a[1:1]

Answer:

Note:
a = "blueberry"# in a[left:right] left is included but right is excluded 
# if a[1:4] printed it will include characters from 1 to 3 and not 4


Code:
print(a[2:3]) # at 2 char is 'u' and from 2 to 2 (3 - 1) hence, it will print 'u'  
print(a[2:])  # from 2 to the end of string i.e. from u to end of string
print(a[:3])  # from start of string to 2 (3 - 1)
print(a[:])   # from start of string to end of string
print(a[-1:-3]) # nothing will be printed because -1 > -3  and in a[left:right] left has to be  less than right
print(a[:-1]) # from start of string to -1-1 means 2nd last character 'r'
print(a[1:1]) # as start and end both are same noting will be printed


Output:
1. u
2. ueberry
3. blu
4. blueberry
5.
6. blueberr
7.
Q.2: Define what we mean by traversal of a string. Write a program that inputs a word (as a string, of course) and prints back the word without like this :the word without the vowels, like this:

If input word is "nectarine" then output should be 'nctrn'.
If input word is "blueberry" then output should be 'blbrry'.

Answer:

Note:
In many problems it becomes necessary to process a string through each character. It starts at the beginning, select each character one by one, and continue until the end. This pattern of processing is called a traversal.


Code:
str = input("Enter String ")          # input the string from user
vowels = ['a','e','i','o','u']        # create list of vowels
output_str = ''                       # create empty string
for s in str:                         # traverse over string str
    if s not in vowels:               # check if char 's' is not present in vowels list
        output_str +=s                # if yes append char s to newly created string output_str
print(output_str)                     # print modified string    


Output:
Enter String blueberry
blbrry
Q.3: Change above program to surround the vowels with parentheses instead of not showing them.

For input word is "nectarine", the output should be 'n(e)ct(a)r(i)n(e)'
For input word is "blueberry", the output should be 'bl(u)(e)b(e)rry'

Answer:

Code:
str = input("Enter String ")          # input the string from user
vowels = ['a','e','i','o','u']        # create list of vowels
output_str = ''                       # create empty string
for s in str:                         # traverse over string str
    if s in vowels:               # check if char 's' is present in vowels list
        output_str +='({})'.format(s) # if yes append char s to newly created string output_str with 
    else:
        output_str +=s                #else append s without parentheses
print(output_str)                     # print modified string   


output:
Enter String blueberry
bl(u)(e)b(e)rry
Q.4: Read the following pieces of code. Determine whether they will be executed successful not. If yes, show the result that would be printed. If not, explain why not.
a) 
myTuple1 = (1,2,3) 
myTuple1.append(4)
print(myTuple1)

b)
myTuple2 = (1,2,3)
myTuple3 = (4) 
print(myTuple2 + myTuple3)

c)
myList=[0,3,4,1] 
myList.remove(3)
print(myList)

Answer:

a) 
myTuple1 = (1,2,3) 

myTuple1.append(4)
print(myTuple1)

Output:

AttributeError: 'tuple' object has no attribute 'append'
tuples are unchangeable
once tuple is created they can't be modified


b)

myTuple2 = (1,2,3)
myTuple3 = (4) 
print(myTuple2 + myTuple3)

Output:

TypeError: can only concatenate tuple (not "int") to tuple
myTuple3 is of type int because tuple consist of only 1 element which is of int type
and concatenation of tuple and int is not possible


c)

myList=[0,3,4,1] 
myList.remove(3)
print(myList)

Output:
[0, 4, 1]
list.remove() takes element to be removed from list as parameter
as 3 passed in as a parameter, 3 is removed from list
Q.5: Beside each expression, write “LEGAL” if the expression is legal python code, or “ERROR” if the expression would cause an error. 
Assume that myList, myTuple, and myString are a list, a tuple, and a string, respectively, 
and all contain at least one element.
1. myList = myList + [4]
2. myList.append(4)
3. del myList[0]
4. myTuple = myTuple + (4)
5. myTuple.append(4)
6. del myTuple[0]
7. myString = myString + "4"
8. myString.append(4)
9. del myString[0]

Answer:

1. myList = myList + [4]
   Ans:  LEGAL
   Code: myList = [1,2,3]
         myList = myList + [4]
         print(myList) 
   Output: [1, 2, 3, 4]   
    
2. myList.append(4)
   Ans: LEGAL
   Code: myList.append(4)
          print(myList)
   Output: [1, 2, 3, 4, 4]

3. del myList[0]
    Ans: LEGAL
    Code: del myList[0]
            print(myList)
    Output: [2, 3, 4, 4]
    
4. myTuple = myTuple + (4)
    Ans: ERROR
    Code: myTuple = (1,2,3)
    Output: TypeError: can only concatenate tuple (not "int") to tuple

5. myTuple.append(4)
    Ans: ERROR    
    Reason: AttributeError: 'tuple' object has no attribute 'append'
          #A tuple is a collection which is ordered and unchangeable.

6. del myTuple[0]
    Ans: ERROR    
    Reason: TypeError: 'tuple' object doesn't support item deletion

7. myString = myString + "4"
    Ans: LEGAL    
    Code:myString = 'ComputerTutor'
         myString = myString + "4"
         print(myString)
    output: #ComputerTutor4

8. myString.append(4)
   Ans: ERROR
   Reason: #AttributeError: 'str' object has no attribute 'append'

9. del myString[0]
   Ans: ERROR
   Reason: #TypeError: 'str' object doesn't support item deletion
Q.6: Consider the following code: what is the value of a at the end ?a = [1, 2, 3] 
a[2] = 0
a[a[2]]= 5 
a[1:2] = []

Answer:

Output:
Final value of a = [5, 0]


Explanation:
a = [1, 2, 3] 
a[2] = 0   # update a[2] to 0 i.e. 3 will be replaced by 0
print(a)   # [1, 2, 0]  

a[a[2]]= 5 # update a[a[2]] = a[0] = 5  i.e. 1 will be replaced by 5
print(a)   #[5, 2, 0]

a[1:2] = [] # from 1 to 1 (2 - 1) i.e. a[1] = [] 
print(a)   # [5, 0]
Q.7: Write a program that accepts a list and removes the value at index 0 from the list.The program must actually modify the list passed in, 
and not just create a second list with the first item removed. 
You may assume the list you are given, will have at least one element.
For example:
for input word is a = [1, 2, 3, 4], the output should be [2, 3, 4]

Answer:

Code:
input_str = input("Enter list elements space separated : ") # inputs the list as string
input_list = list(map(int ,input_str.split()))              # split string and convert it into a list of integers
del input_list[0]                                           # delete element at index 0
print(input_list)                                           # print modified list


Output:
Enter list elements space separated : 1 2 3
[2, 3]
Q.8: Assume each of the following lines is entered in the IDLE shell one at a time.Circle any of the lines that produces an error. 
If no errors are found then write what is printed (from a and b).
a = [[[ 1,2,3,4,5,],[6,7,8]],9] 
a[-1] = 200 
b = a[:] 
b[0][0][3] = 17 
print(a) 
print(b)

Answer:

Code:
a = [[[ 1,2,3,4,5],[6,7,8]],9] #initial
a[-1] = 200 # last element changed to 200
b = a[:]    # all elements of a copied to b
b[0][0][3] = 17 
# 0th element of b = [[ 1,2,3,4,5],[6,7,8]]
# 0th element of [[ 1,2,3,4,5],[6,7,8]] = [ 1,2,3,4,5,]
# 3rd element of [ 1,2,3,4,5] = 4 
# 4 will be replaced by 17

print(a) 
print(b)

# making copy of a list simply by typing b = a leads to problem
# b will only be a reference to a, and changes made in b will automatically also be made in a.


Output:
[[[1, 2, 3, 17, 5], [6, 7, 8]], 200]
[[[1, 2, 3, 17, 5], [6, 7, 8]], 200]
Q.9: Write a program that inputs two tuples and creates a third that contains all elements of the first followed by all elements of the second. (you may use other data types such as lists etc to make your program work)

Answer:

Code:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
tuple3 = tuple1 +  tuple2 # concatenate  tuple1 & tuple2   
print(tuple3)


Output:
(1, 2, 3, 4, 5, 6)
Q.10: Arrays in Python are implemented through lists. Write a program that sorts an array of integers in ascending order.

Answer:

this problem can be easily solved by using inbuilt function in list called sort()

Code:
a = [3, 4, 1, 5, 8, 2]
a.sort()
print("Output using inbuilt function : {}".format(a))

Output:
Output using inbuilt function : [1, 2, 3, 4, 5, 8]

To understand logic of sorting two more methods are given:

Method 1:
a = [3, 4, 1, 5, 8, 2]
n = len(a)
for i in range(n):         #traverse through array
    for j in range(n):   
        if(a[i]<a[j]):     # check if a[i] < a[j] if true swap a[i] a[j]
            temp = a[i]
            a[i] = a[j]
            a[j] = temp
print("Output of simple approach : {}".format(a))

Output:
Output of simple approach : [1, 2, 3, 4, 5, 8]


Method 2:
# bubble sort   
# each element is comapired with remaining elements and
#if current element is greater than its next element they get swapped
# with each iteration largest element in remaining array will shifted to last
a = [3, 4, 1, 5, 8, 2]
n = len(a)

for i in range(n-1): 
    for j in range(0, n-i-1):  #in each iteration range is reduced by 1
            # Swap if a[j] (current element) is greater than a[j+1] (next element)  
        if a[j] > a[j+1] : 
            temp = a[j]
            a[j] = a[j+1]
            a[j+1] = temp
print("Output of bubble sort approach : {}".format(a))

Output:
Output of bubble sort approach : [1, 2, 3, 4, 5, 8]
Q.11: In context to previous program, that if you need to sort elements of a tuple? Is it possible ?How can you make it happen?

Answer:

if we try sorting tuple same as list we will get error like 
TypeError: 'tuple' object does not support item assignment

Reason: tuples are immutable i.e. they can't be changed

to sort tuple we can follow two methods:
1. covert tuple to list sort it and again convert it to tuple
2. use built in sorted() function to sort tuple directly
    sorted() will return sorted tuple 


Method 1:

a_tuple = (3, 4, 1, 5, 8, 2)
a_list = list(a_tuple)
n = len(a_list)
for i in range(n):         #traverse through array
    for j in range(n):   
        if(a_list[i]<a_list[j]):     # check if a[i] < a[j] if true swap a[i] a[j]
            temp = a_list[i]
            a_list[i] = a_list[j]
            a_list[j] = temp
a_tuple = tuple(a_list)
print("Output of tuple to list approach : {}".format(a_tuple))

Output:

Output of tuple to list approach : (1, 2, 3, 4, 5, 8)


Method 2:
a_tuple = (3, 4, 1, 5, 8, 2)
output_tuple = sorted(a_tuple)
print("Output of sorted method approach : {}".format(tuple(output_tuple)))

Output:

Output of sorted method approach : (1, 2, 3, 4, 5, 8)
Q.12: Write a program that reverses a 2D array of integers, implemented as nested list, in the order of 0th element of every inner list.

Answer:

Since the question is confusing and there is no fix expected output we are providing two different approaches which gives different output

Method 1:
a = [[1,2,3],
     [4,5,6],
     [7,8,9]]

row = len(a)   # calculate number of rows
col = len(a[0])# calculate number of cols
n = row*col//2 # total number of swaps required
count = 0

for r in range(row): # iterate rows
    for c in range(col): #iterate columns

        if count<=n:     # if number of swaps less than n
            temp = a[r][c] # then swap
            a[r][c] = a[row-1-r][col-1-c]
            a[row-1-r][col-1-c] = temp
            count+=1     # increment the swap counter

# Code for printing 2D array    
for i in  range(row) :  
    for j in range(col) : 
        print(a[i][j],end= ' '); 
    print(); 


Output: 
9 8 7 
6 5 4 
3 2 1
Method 2:
a = [[1,2,3],
     [4,5,6],
     [7,8,9]]
row = len(a)
col = len(a[0])

for i in range(row) : # traverse through each row
   left = 0; # Initialize start
   right = col - 1; # Initialize end

    while (left < right) :   # Till start < end, swap the element at start and end  
        # Swap the elements 
        temp = a[i][left]
        a[i][left] = a[i][right] 
        a[i][right] = temp
        left += 1; #Increment start
        right -= 1;   #decrement end

# Code for printing 2D array
for i in  range(row) : 
    for j in range(col) : 
        print(a[i][j],end= ' '); 
    print();


Output:
3 2 1
6 5 4
9 8 7

Clear Doubts with Computer Tutor
In case you’re facing problems in understanding concepts, writing programs, solving questions, want to learn fun facts | tips | tricks or absolutely anything around computer science, feel free to join CTs learner-teacher community: students.computertutor.in

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You cannot copy content of this page