Chapter 10 : Tuples and Dictionaries | class 11th | Ncert solution for computer

NCERT Solutions for Class 11 Science Computer science Chapter 10 – Tuples And Dictionaries

Page No 223:

Question 1:

Consider the following tuples, tuple1 and tuple2:

​tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)

Find the output of the following statements:

  1. print(tuple1.index(45))
  2. print(tuple1.count(45))
  3. print(tuple1 + tuple2)
  4. print(len(tuple2))
  5. print(max(tuple1))
  6. print(min(tuple1))
  7. print(sum(tuple2))
  8. print(sorted (tuple1))
    print(tuple1)

ANSWER:

i. The ‘index()’ function returns the index of the first occurrence of the element in a tuple.
OUTPUT:


ii. The ‘count()’ function returns the numbers of times the given element appears in the tuple.
OUTPUT:
3

iii. ‘+’ operator concatenate the two tuples.
OUTPUT: 
(23, 1, 45, 67, 45, 9, 55, 45, 100, 200)

iv. The ‘len()’ function returns the number of elements in the given tuple.
OUTPUT:
2

v. The ‘max()’ function returns the largest element of the tuple.
OUTPUT:
67

vi. The ‘min()’ function returns the smallest element of the tuple.
OUTPUT:
1

vii. The ‘sum()’ function returns the sum of all the elements of the tuple.
OUTPUT:
300

viii. The ‘sorted()’ function takes element in the tuple and return a new sorted list. It doesn’t make any changes to the original tuple. Hence, print(tuple1) will print the original tuple1 i.e. (23, 1, 45, 67, 45, 9, 55, 45)
OUTPUT: 
[1, 9, 23, 45, 45, 45, 55, 67]
(23, 1, 45, 67, 45, 9, 55, 45)
 

Page No 224:

Question 2:

Consider the following dictionary stateCapital: 

stateCapital = {“AndhraPradesh”:”Hyderabad”,”Bihar”:”Patna”,”Maharashtra”:”Mumbai”, “Rajasthan”:”Jaipur”}
Find the output of the following statements:

  1. print(stateCapital.get(“Bihar”))
  2. print(stateCapital.keys())
  3. print(stateCapital.values())
  4. print(stateCapital.items())
  5. print(len(stateCapital))
  6. print(“Maharashtra” in stateCapital)
  7. print(stateCapital.get(“Assam”))
  8. del stateCapital[“Andhra Pradesh”]
    print(stateCapital)

ANSWER:

  1. Patna: ‘get() function returns the value corresponding to the key passed as an argument.
  2. dict_keys([‘AndhraPradesh’, ‘Bihar’, ‘Maharashtra’, ‘Rajasthan’]): ‘keys()’ function returns the list of the keys in the dictionary.
  3. dict_values([‘Hyderabad’, ‘Patna’, ‘Mumbai’, ‘Jaipur’]): ‘values()’ function returns the list of the values in the dictionary.
  4. dict_items([(‘AndhraPradesh’, ‘Hyderabad’), (‘Bihar’, ‘Patna’), (‘Maharashtra’, ‘Mumbai’), (‘Rajasthan’, ‘Jaipur’)]): ‘items()’ function returns the list of tuples in key value pair.
  5. 4: ‘len()’ functions return the length or number of key:value pairs of the dictionary passed as the argument.
  6. True: ‘in’ is a membership operator which returns true if a key is present in the dictionary.
  7. None:  ‘get()’ function returns ‘None’ if the key is not present in the dictionary.
  8. del stateCapital[“Andhra Pradesh”] will return an error as the key ‘Andhra Pradesh’ is not present in the dictionary. (‘Andhra Pradesh’ and ‘AndhraPradesh’ are different). However, if the key is present it will delete the key:value pair from the dictionary. If the statement is del stateCapital[“AndhraPradesh”], print(stateCapital) will then print the remaining key: value pair. {‘Bihar’: ‘Patna’, ‘Maharashtra’: ‘Mumbai’, ‘Rajasthan’: ‘Jaipur’}

Page No 224:

Question 3:

“Lists and Tuples are ordered”. Explain.

ANSWER:

In Lists and Tuples, the items are retained in the order in which they are inserted. The elements can always be accessed based on their position. The element at the position or ‘index’ 0 will always be at index 0. Therefore, the Lists and Tuples are said to be ordered collections.

Page No 224:

Question 4:

With the help of an example show how can you return more than one value from a function.

ANSWER:

In tuple, more than one value can be returned from a function by ‘packing’ the values. The tuple can be then ‘unpacked’ into the variables by using the same number of variables on the left-hand side as there are elements in a tuple. 
Example:

Program: 
#Function to compute area and perimeter of the square.
def square(r):
    area = r * r
    perimeter = 4 * r
    #Returns a tuple having two elements area and perimeter, i.e. two variables are packed in a tuple
    return (area, perimeter)
    ​#end of function

side = int(input(“Enter the side of the square: “))
#The returned value from the function is unpacked into two variables area and perimeter
area, perimeter = square(side)
print(“Area of the square is:”,area)
print(“The perimeter of the square is:”,perimeter)


OUTPUT:
Enter the side of the square: 4
Area of the square is: 16
The perimeter of the square is: 16 

Page No 224:

Question 5:

What advantages do tuples have over lists?

ANSWER:

The advantages of tuples over the lists are as follows:

  1. Tuples are faster than lists.
  2. Tuples make the code safe from any accidental modification. If a data is needed in a program which is not supposed to be changed, then it is better to put it in ‘tuples’ than in ‘list’.
  3. Tuples can be used as dictionary keys if it contains immutable values like strings, numbers or another tuple. ‘Lists’ can never be used as dictionary keys as ‘lists’ are mutable.

Page No 224:

Question 6:

 When to use tuple or dictionary in Python. Give some examples of programming situations mentioning their usefulness.

ANSWER:

Tuples are used to store the data which is not intended to change during the course of execution of the program. For example, if the name of months is needed in a program, then the same can be stored in the tuple as generally, the names will either be iterated for a loop or referenced sometimes during the execution of the program.

Dictionary is used to store associative data like student’s roll no. and the student’s name. Here, the roll no. will act as a key to find the corresponding student’s name. The position of the data doesn’t matter as the data can easily be searched by using the corresponding key. 

Page No 224:

Question 7:

Prove with the help of an example that the variable is rebuilt in case of immutable data types.

ANSWER:

When a variable is assigned to the immutable data type, the value of the variable cannot be changed in place. Therefore, if we assign any other value to the variable, the interpreter creates a new memory location for that value and then points the variable to the new memory location. This is the same process in which we create a new variable. Thus, it can be said that the variable is rebuilt in case of immutable data types on every assignment.

Program to represent the same:
#Define a variable with immutable datatypes as value
var = 50
#Checking the memory location of the variable
print(“Before: “,id(var))
#Assign any other value
var = 51
#Checking the memory location of the variable
print(“After: “,id(var))


OUTPUT:
Before: 10916064
After: 10916096


It can be seen that the memory location a variable is pointing after the assignment is different. The variable is entirely new and it can be said that the variable is rebuilt.

Page No 224:

Question 8:

TypeError occurs while statement 2 is running. Give reason. How can it be corrected?

>>> tuple1 = (5)    #statement 1
>>> len(tuple1)     #statement 2

ANSWER:

The ‘statement 1’ is creating a variable, tuple1 which is of ‘int’ data type. The ‘statement 2’ is checking for the length of the variable, but the argument passed is an ‘int’ data type. The ‘len() function can return the length only when the object is a sequence or a collection. This is the reason for the type error. 

The error can be corrected by adding one comma after ‘5’ in statement 1, as this will create a tuple and as a tuple is a collection, ‘len() function will not return an error. The correct statement will be: 
>>> tuple1 = (5,)    
>>> len(tuple1)   

Page No 224:

Question 1:

 Write a program to read email IDs of n number of students and store them in a tuple. Create two new tuples, one to store only the usernames from the email IDs and second to store domain names from the email ids. Print all three tuples at the end of the program. [Hint: You may use the function split()]
 

ANSWER:

Program:
#Program to read email id of n number of students. Store these numbers in a tuple.
#Create two new tuples, one to store only the usernames from the email IDs and second to store domain names from the email ids.
emails = tuple()
username = tuple()
domainname = tuple()
#Create empty tuple ’emails’, ‘username’ and domain-name
n = int(input(“How many email ids you want to enter?: “))
for i in range(0,n):
    emid = input(“> “)
    #It will assign emailid entered by user to tuple ’emails’
    emails = emails +(emid,)
    #This will split the email id into two parts, username and domain and return a list
    spl = emid.split(“@”)
    #assigning returned list first part to username and second part to domain name

    username = username + (spl[0],)
    domainname = domainname + (spl[1],)

print(“\nThe email ids in the tuple are:”)
#Printing the list with the email ids
print(emails)

print(“\nThe username in the email ids are:”)
#Printing the list with the usernames only
print(username)

print(“\nThe domain name in the email ids are:”)
#Printing the list with the domain names only
print(domainname)


OUTPUT:
How many email ids you want to enter?: 3
> abcde@gmail.com
> test1@meritnation.com
> testing@outlook.com

The email ids in the tuple are:
(‘abcde@gmail.com’, ‘test1@meritnation.com’, ‘testing@outlook.com’)

The username in the email ids are:
(‘abcde’, ‘test1’, ‘testing’)

The domain name in the email ids are:
(‘gmail.com’, ‘meritnation.com’, ‘outlook.com’)

Page No 224:

Question 2:

Write a program to input names of n students and store them in a tuple. Also, input  name from the user and find if this student is present in the tuple or not. 
We can accomplish these by: 
(a) writing a user defined function
(b) using the built-in function

ANSWER:

a) Program:
#Program to input names of n students and store them in a tuple.
#Input a name from the user and find if this student is present in the tuple or not.
#Using a user-defined function

#Creating user defined function
def searchStudent(tuple1,search):
    for a in tuple1:
        if(a == search):
            print(“The name”,search,”is present in the tuple”)
            return
    print(“The name”,search,”is not found in the tuple”)

name = tuple()
#Create empty tuple ‘name’ to store the values
n = int(input(“How many names do you want to enter?: “))
for i in range(0,n):
    num = input(“> “)
    #It will assign emailid entered by user to tuple ‘name’
    name = name + (num,)

print(“\nThe names entered in the tuple are:”)
print(name)

#Asking the user to enter the name of the student to search
search = input(“\nEnter the name of the student you want to search? “)
#Calling the search Student function
searchStudent(name,search)


OUTPUT:
How many names do you want to enter?: 3
> Amit
> Sarthak
> Rajesh

The names entered in the tuple are:
(‘Amit’, ‘Sarthak’, ‘Rajesh’)

Enter the name of the student you want to search? Amit
The name Amit is present in the tuple


b) Program:
#Program to input names of n students and store them in a tuple.
#Input a name from the user and find if this student is present in the tuple or not.
#Using a built-in function

name = tuple()
#Create empty tuple ‘name’ to store the values
n = int(input(“How many names do you want to enter?: “))
for i in range(0, n):
    num = input(“> “)
    #it will assign emailid entered by user to tuple ‘name’
    name = name + (num,)

print(“\nThe names entered in the tuple are:”)
print(name)

search=input(“\nEnter the name of the student you want to search? “)

#Using membership function to check if name is present or not
if search in name:
    print(“The name”,search,”is present in the tuple”)
else:
    print(“The name”,search,”is not found in the tuple”)


OUTPUT:
How many names do you want to enter?: 3
> Amit
> Sarthak
> Rajesh

The names entered in the tuple are:
(‘Amit’, ‘Sarthak’, ‘Rajesh’)

Enter the name of the student you want to search? Animesh
The name Animesh is not present in the tuple

Page No 225:

Question 3:

Write a Python program to find the highest 2 values in a dictionary.

ANSWER:

Program:
#Write a Python program to find the highest 2 values in a dictionary
#Defining a dictionary
dic = {“A”:12,”B”:13,”C”:9,”D”:89,”E”:34,”F”:17,”G”:65,”H”:36,”I”:25,”J”:11}

#Creating an empty list to store all the values of the dictionary
lst = list()

#Looping through each values and storing it in list
for a in dic.values():
    lst.append(a)

#Sorting the list in ascending order, it will store the highest value at the last index
lst.sort()

#Printing the highest and second highest value using negative indexing of the list
print(“Highest value:”,lst[-1])
print(“Second highest value:”,lst[-2])


OUTPUT:
Highest value: 89
Second highest value: 65

Page No 225:

Question 4:

Write a Python program to create a dictionary from a string.
Note: Track the count of the letters from the string.
Sample string  : ‘w3resource’
Expected output : {‘3’: 1, ‘s’: 1, ‘r’: 2, ‘u’: 1, ‘w’: 1, ‘c’: 1, ‘e’: 2, ‘o’: 1}

ANSWER:

Program:
#Count the number of times a character appears in a given string
st = input(“Enter a string: “)

dic = {}
#creates an empty dictionary

for ch in st:
    if ch in dic:
#if next character is already in the dictionary
        dic[ch] += 1
    else:
#if ch appears for the first time
        dic[ch] = 1

#Printing the count of characters in the string
print(dic)


OUTPUT:
Enter a string: meritnation
{‘m’: 1, ‘e’: 1, ‘r’: 1, ‘i’: 2, ‘t’: 2, ‘n’: 2, ‘a’: 1, ‘o’: 1}

Page No 225:

Question 5:

Write a program to input your friends’ names and their Phone Numbers and store them in the dictionary as the key-value pair. Perform the following operations on the dictionary:
a) Display the name and phone number of all your friends
b) Add a new key-value pair in this dictionary and display the modified dictionary
c) Delete a particular friend from the dictionary
d) Modify the phone number of an existing friend
e) Check if a friend is present in the dictionary or not
f) Display the dictionary in sorted order of names

ANSWER:

Program: 
dic = {}
#Creates an empty dictionary

#While loop to provide the options repeatedly
#it will exit when the user enters 7
while True:
    print(“1. Add New Contact”)
    print(“2. Modify Phone Number of Contact”)
    print(“3. Delete a Friend’s contact”)
    print(“4. Display all entries”)
    print(“5. Check if a friend is present or not”)
    print(“6. Display in sorted order of names”)
    print(“7. Exit”)
    inp = int(input(“Enter your choice(1-7): “))

    #Adding a contact
    if(inp == 1):
        name = input(“Enter your friend name: “)
        phonenumber = input(“Enter your friend’s contact number: “)
        dic[name] = phonenumber
        print(“Contact Added \n\n”)
    #Modifying a contact if the entered name is present in the dictionary
    elif(inp == 2):
        name = input(“Enter the name of friend whose number is to be modified: “)
        if(name in dic):
            phonenumber = input(“Enter the new contact number: “)        
            dic[name] = phonenumber
            print(“Contact Modified\n\n”)
        else:
            print(“This friend’s name is not present in the contact list”)
    #Deleting a contact if the entered name is present in the dictionary
    elif(inp == 3):
        name = input(“Enter the name of friend whose contact is to be deleted: “)
        if(name in dic):
            del dic[name]
            print(“Contact Deleted\n\n”)
        else:
            print(“This friend’s name is not present in the contact list”)
    #Displaying all entries in the dictionary
    elif(inp == 4):
        print(“All entries in the contact”)
        for a in dic:
            print(a,”\t\t”,dic[a])
        print(“\n\n\n”)
    #Searching a friend name in the dictionary
    elif(inp == 5):
        name = input(“Enter the name of friend to search: “)
        if(name in dic):
            print(“The friend”,name,”is present in the list\n\n”)
        else:
            print(“The friend”,name,”is not present in the list\n\n”)
    #Displaying the dictionary in the sorted order of the names
    elif(inp == 6):
        print(“Name\t\t\tContact Number”)
        for i in sorted(dic.keys()):
            print(i,”\t\t\t”,dic[i])
        print(“\n\n”)
    #Exit the while loop if user enters 7
    elif(inp == 7):
        break
    #Displaying the invalid choice when any other values are entered
    else:
        print(“Invalid Choice. Please try again\n”)


OUTPUT:

1. Add New Contact

2. Modify Phone Number of Contact

3. Delete a Friend’s contact

4. Display all entries

5. Check if a friend is present or not

6. Display in sorted order of names

7. Exit

Enter your choice(1-7): 1

Enter your friend name: Mohit

Enter your friend’s contact number: 98765*****

Contact Added 

1. Add New Contact

2. Modify Phone Number of Contact

3. Delete a Friend’s contact

4. Display all entries

5. Check if a friend is present or not

6. Display in sorted order of names

7. Exit

Enter your choice(1-7): 1

Enter your friend name: Mohan

Enter your friend’s contact number: 98764*****

Contact Added 

1. Add New Contact

2. Modify Phone Number of Contact

3. Delete a Friend’s contact

4. Display all entries

5. Check if a friend is present or not

6. Display in sorted order of names

7. Exit

Enter your choice(1-7): 6

Name Contact Number

Mohan   98764*****

Mohit   98765*****

1. Add New Contact

2. Modify Phone Number of Contact

3. Delete a Friend’s contact

4. Display all entries

5. Check if a friend is present or not

6. Display in sorted order of names

7. Exit

Enter your choice(1-7): 7

Read More

Chapter 9 : Lists | class 11th | Ncert solution for computer

NCERT Solutions for Class 11 Science Computer science Chapter 9 – Lists

Page No 204:

Question 1:

What will be the output of the following statements?

i)  list1 = [12,32,65,26,80,10] 
  list1.sort() 
  print(list1)

ii) list1 = [12,32,65,26,80,10] 
  sorted(list1) 
  print(list1)

iii)list1 = [1,2,3,4,5,6,7,8,9,10]
  list1[::-2]
  list1[:3] + list1[3:]

iv)list1 = [1,2,3,4,5] 
  list1[len(list1)-1]

ANSWER:


i) The sort() method will sort the list in ascending order in place.
OUTPUT:
[10, 12, 26, 32, 65, 80]


ii) The sorted() function takes a list as a parameter and creates a new list consisting of the same elements arranged in sorted order. It doesn’t change the list which is passed as a parameter itself.
OUTPUT: 
[12, 32, 65, 26, 80, 10]

iii) The statement in line 2 has a negative step size. This means that the list will be traversed in reversed order with step size 2.
OUTPUT: [10, 8, 6, 4, 2]
The statement in line 3 will print the complete list. i.e. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

iv) This will print the last element of the list. i.e. 5 

list1[len(list1)-1]

list1[5-1]
list1[4]
5

Page No 204:

Question 2:

Consider the following list myList. What will be the elements of myList after the following two operations: 
  myList = [10,20,30,40]
  i. myList.append([50,60])
  ii. myList.extend([80,90])
 

ANSWER:

i) append() function takes only one argument and inserts the element to the end of the list. Here, the argument is a list containing the element 50, 60. Therefore, the output will be: [10, 20, 30, 40, [50, 60]]

ii) extend() function takes a list as an argument and appends each element of the list in the same order. The final output will be: [10, 20, 30, 40, [50, 60],80,90]

Page No 205:

Question 3:

What will be the output of the following code segment:

myList = [1,2,3,4,5,6,7,8,9,10]
for i in range(0,len(myList)):
    if i%2 == 0:
        print(myList[i])
 

ANSWER:

Here, the elements of the list will be printed which are at index such that index%2==0. The index of the list can be represented as:
 

 Element12345678910
 Index 0123456789


Therefore, the output will be the elements at index 0, 2, 4, 6, 8 i.e.
1
3
5
7
9

Page No 205:

Question 4:

What will be the output of the following code segment: 

  1. myList = [1,2,3,4,5,6,7,8,9,10] 
    del myList[3:] 
    print(myList)
  2. myList = [1,2,3,4,5,6,7,8,9,10] 
    del myList[:5] 
    print(myList)
  3. myList = [1,2,3,4,5,6,7,8,9,10]
    del myList[::2]
    print(myList)

ANSWER:

  1. The statement in line 2 will delete the elements from index 3 to the last index of the list. Therefore, the output will be [1, 2, 3].
  2. The statement in line 2 will delete the elements from start (index 0) to index 4 of the list. Therefore, the output will be [6, 7, 8, 9, 10]
  3. The statement in line 2 will delete the elements from the start to the end of the list with step size 2. i.e it will delete elements starting from index 0, then index 2, index 4, index 6 … and so on.
    The output will be the remaining elements i.e. [2, 4, 6, 8, 10]

Page No 205:

Question 5:

 Differentiate between functions of list. append() and extend().

ANSWER:

The append() function takes a single element as an argument and appends it to the list. The argument can be any datatype, even a list. The argument will be added as a single element. 
>>>list1 = [10, 20, 30]
>>>list1.append(40)


list1 will now be [10, 20, 30, 40]

>>>list1 = [10, 20, 30]
>>>list1.append([40, 50])


Here [40, 50] is a list which will be considered as a single argument, and will be added to the list at index 3. ‘list1’ will now be [10, 20, 30, [40, 50]]

The extend() function takes any iterable data type (e.g. list, tuple, string, dictionary) as an argument and adds all the elements of the list passed as an argument to the end of the given list. This function can be used to add more than one element in the list in a single statement.

>>> list1 = [2, 4, 5, 6]
>>> list1.extend((2, 3, 4, 5))
>>> print(list1)


OUTPUT:
[2, 4, 5, 6, 2, 3, 4, 5]

Page No 205:

Question 6:

Consider a list:   list1 = [6,7,8,9]
What is the difference between the following operations on list1:
  a. list1 * 2
  b. list1 *= 2
  c. list1 = list1 * 2

ANSWER:

  1. The statement will print the elements of the list twice, i.e [6, 7, 8, 9, 6, 7, 8, 9]. However, list1 will not be altered.
  2. This statement will change the list1 and assign the list with repeated elements i.e [6, 7, 8, 9, 6, 7, 8, 9] to list1. 
  3. This statement will also have same result as the statement ‘list1 *= 2’. The list with repeated elements i.e [6, 7, 8, 9, 6, 7, 8, 9] will be assigned to list1. 

Page No 205:

Question 7:

The record of a student (Name, Roll No.,Marks in five subjects and percentage of marks) is stored in the following list:
  stRecord = [‘Raman’,’A-36′,[56,98,99,72,69],  78.8]

Write Python statements to retrieve the following information from the list stRecord.

  1. Percentage of the student
  2. Marks in the fifth subject
  3. Maximum marks of the student
  4. Roll no. of the student
  5. Change the name of the student from ‘Raman’ to ‘Raghav’

ANSWER:

List NameNameRoll No. Marks in 5 Subjects Percentage
stRecordRamanA-36[56, 98, 99, 72, 69]78.8
Index012[0, 1, 2, 3, 4] index of the list at index 23

Here, we can see that the ‘name’ is stored at index 0, ‘roll no’ at index 1, ‘marks of the 5 subjects’ is stored at index 2 in a list which contains 5 elements, and ‘percentage’ at index 3

  1. Percentage: stRecord[3]
  2. Marks in 5th Subject: stRecord[2][4]
  3. Maximum Marks of the Student: max(stRecord[2])
  4. Roll no. of the student: stRecord[1]
  5. Change the name from Raman to Raghav: stRecord[0] = “Raghav”

Page No 205:

Question 1:

Write a program to find the number of times an element occurs in the list.

ANSWER:

Program:
#defining a list
list1 = [10, 20, 30, 40, 50, 60, 20, 50, 10, 30, 50, 30, 24, 45]

#printing the list for the user
print(“The list is:”,list1)

#asking the element to count
inp = int(input(“Which element occurrence would you like to count? “))

#using the count function
count = list1.count(inp)

#printing the output
print(“The count of element”,inp,”in the list is:”,count)


OUTPUT:
The list is: [10, 20, 30, 40, 50, 60, 20, 50, 10, 30, 50, 30, 24, 45]
which element occurrence would you like to count? 10
The count of element 10 in the list is: 2

Page No 205:

Question 2:

Write a program to read a list of n integers (positive as well as negative). Create two new lists,  one having all positive numbers and the other having all negative numbers from the given list. Print all three lists.

ANSWER:

Program:
#Defining empty list
list1 = list()

#Getting the input of number of elements to be added in the list
inp = int(input(“How many elements do you want to add in the list? (Element can be both positive and negative) “))

#Taking the input of elements to be added
for i in range(inp):
    a = int(input(“Enter the elements: “))
    list1.append(a)
    
#Printing the list
print(“The list with all the elements: “,list1)

#Defining list2 and list3 to store positive and negative elements of the list
list2 = list()
list3 = list()

#Looping through list to segregate positive and negative numbers
for j in range(inp):
    if list1[j] < 0:
        #Appending negative elements to list3
        list3.append(list1[j])
    else:
        #Appending positive elements to list2
        list2.append(list1[j])


print(“The list with positive elements: “,list2)
print(“The list with negative elements: “,list3)


OUTPUT:
How many elements do you want to add in the list? (Element can be both positive and negative) 5
Enter the elements: -1
Enter the elements: -2
Enter the elements: -3
Enter the elements: 4
Enter the elements: 5
The list with all the elements:  [-1, -2, -3, 4, 5]
The list with positive elements:  [4, 5]
The list with negative elements:  [-1, -2, -3]

Page No 206:

Question 3:

 Write a function that returns the largest element of the list passed as parameter.

ANSWER:

The function can be written in two ways:
1. Using max() function of the list
2. Using for loop to iterate every element and checking for the maximum value 

Program 1:
#Using max() function to find largest number
def largestNum(list1):
    l = max(list1)
    return l

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

#Using largestNum function to get the function   
max_num = largestNum(list1)

#Printing all the elements for the list
print(“The elements of the list”,list1)

#Printing the largest num 
print(“\nThe largest number of the list:”,max_num)


OUTPUT:
The elements of the list [1, 2, 3, 4, 5, 6, 7, 8, 9]

The largest number of the list: 9​


Program 2:
​#Without using max() function of the list
def largestNum(list1):
    length = len(list1)
    num = 0
    for i in range(length):
        if(i == 0 or list1[i] > num):
            num = list1[i]
    return num


list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

#Using largestNum function to get the function   
max_num = largestNum(list1)

#Printing all the elements for the list
print(“The elements of the list”,list1)

#Printing the largest num 
print(“\nThe largest number of the list:”,max_num)


OUTPUT:
The elements of the list [1, 2, 3, 4, 5, 6, 7, 8, 9]

The largest number of the list: 9​

Page No 206:

Question 4:

Write a function to return the second largest number from a list of numbers.

ANSWER:

Program:
def secLargestNum(list1):
    #Sorting the list in ascending order
    list1.sort()
    
    #Returning the second last index of list1
    #List with negative indexing will start from the end in reverse order with -1 as the index of the last element
    secondLast = list1[-2]
    
    
    #or len(list1)-2 can be used which will return second last element
    ​#secondLast = list1[len(list1)-2]
    return secondLast

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

#Using secLargestNum function to get the function   
sec_num = secLargestNum(list1)

#Printing all the elements for the list
print(“The elements of the list”,list1)

#Printing the second largest num 
print(“\nThe second-largest number of the list:”,sec_num)


OUTPUT:
The elements of the list [1, 2, 3, 4, 5, 6, 7, 8, 9]

The second-largest number of the list: 8

Page No 206:

Question 5:

Write a program to read a list of n integers and find their median. 
The median value of a list of values is the middle one when they are arranged in order. If there are two middle values then take their average. 
Hint: You can use a built-in function to sort the list
 

ANSWER:

Program:
def medianValue(list1):
    #Sorting the list
    list1.sort()
    #Checking the last index
    indexes = len(list1)
    if(indexes%2 == 0):
        #if the number of elements is even, then we have to find average of two middle values
        num1 = (indexes) // 2 #first middle element
        num2 = (indexes // 2) + 1 #second middle element
        #Calculating median as average of the two
        med = (list1[num1 – 1] + list1[num2 – 1]) / 2
        return med
    else:
        #if number of elements is odd, then we have to return the element at middle index

        middle = (indexes – 1) // 2
        med = list1[middle]
        return med

#defining empty list
list1 = list()
#Getting input of number of elements to be added in the list
inp = int(input(“How many elements do you want to add in the list? “))
#Getting the input of elements from user
for i in range(inp):
    a = int(input(“Enter the elements: “))
    list1.append(a)
#Printing the list
print(“The median value is”,medianValue(list1))


OUTPUT:
How many elements do you want to add in the list? 6
Enter the elements: 1
Enter the elements: 2
Enter the elements: 3
Enter the elements: 4
Enter the elements: 5
Enter the elements: 6
The median value is 3.5

Page No 206:

Question 6:

Write a program to read a list of elements. Modify this list so that it does not contain any duplicate elements, i.e., all elements occurring multiple times in the list should appear only once.

ANSWER:

Program:
#function to remove the duplicate elements
def removeDup(list1):
    #Checking the length of list for ‘for’ loop
    length = len(list1)
    #Defining a new list for adding unique elements
    newList = []
    for a in range(length):
        #Checking if an element is not in the new List
        #This will reject duplicate values

        if list1[a] not in newList:
            newList.append(list1[a])
    return newList

#Defining empty list
list1 = []

#Asking for number of elements to be added in the list
inp = int(input(“How many elements do you want to add in the list? “))

#Taking the input from user
for i in range(inp):
    a = int(input(“Enter the elements: “))
    list1.append(a)
    
#Printing the list
print(“The list entered is:”,list1)

#Printing the list without any duplicate elements
print(“The list without any duplicate element is:”,removeDup(list1))


OUTPUT:
How many elements do you want to add in the list? 6
Enter the elements: 1
Enter the elements: 1
Enter the elements: 2
Enter the elements: 2
Enter the elements: 3
Enter the elements: 4
The list entered is: [1, 1, 2, 2, 3, 4]
The list without any duplicate element is: [1, 2, 3, 4]

Page No 206:

Question 7:

Write a program to read a list of elements. Input an element from the user that has to be inserted in the list. Also input the position at which it is to be inserted. Write a user defined function to insert the element at the desired position in the list.

ANSWER:

Program:
def addElements(list1):
    newList = list1
    
    #Asking the user if he want to add any element to the list
    inp = input(“Do you want to add any new element to the list? (Y/N) “)
    
    #if user input is yes
    if(inp == ‘Y’ or inp == ‘y’):
        elem = int(input(“Enter the element: “))
        index = int(input(“Enter the index at which you would like to add the element: “))
        
        #Using insert() function to add the element at particular index
        newList.insert(index,elem)
        print(“***Element added***”)
        addElements(newList) #Calling the addElement function again to check if new element should be added
    return newList    
        
#Defining empty list
list1 = []
    
#Getting input for the number of elements to be added in the list
inp = int(input(“How many elements do you want to add in the list? “))

#Taking the input from user
for i in range(inp):
    a = int(input(“Enter the elements: “))
    list1.append(a)
    
#Printing the list
print(“The list entered is:”,list1)

#Calling the addElement function to get a confirmation about adding the element to the list and then returning the modified list
modList = addElements(list1)
print(“The modified list is: “,modList)


OUTPUT:
How many elements do you want to add in the list? 6
Enter the elements: 33
Enter the elements: 44
Enter the elements: 55
Enter the elements: 66
Enter the elements: 77
Enter the elements: 12
The list entered is: [33, 44, 55, 66, 77, 12]
Do you want to add any new element to the list? (Y/N) y
Enter the element: 11
Enter the index at which you would like to add the element: 0
***Element added***
Do you want to add any new element to the list? (Y/N) n
The modified list is:  [11, 33, 44, 55, 66, 77, 12]

Page No 206:

Question 8:

Write a program to read elements of a list.
a) The program should ask for the position of the element to be deleted from the list. Write a function to delete the element at the desired position in the list.
b) The program should ask for the value of the element to be deleted from the list. Write a function to delete the element of this value from the list.

ANSWER:

a) Program:
def deleteElements():
    global list1
    #Asking the user if he want to delete any element from the list
    inp = input(“Do you want to delete any element from the list? (Y/N) “)
    #if user input is yes
    if(inp == ‘Y’ or inp == ‘y’):
        elem = int(input(“Enter the element which you would like to delete: “))
        #Using remove() function to remove the element
        for a in list1:
            if(a == elem):
                list1.remove(elem)
        print(“The element is deleted from the list. “)
        deleteElements()
    else:
        print(“The elements in the list”,list1)

#Defining empty list
list1 = []
#Taking the number of elements to be added as input
inp = int(input(“How many elements do you want to add in the list? “))

#Taking the input from user
for i in range(inp):
    a = int(input(“Enter the elements: “))
    list1.append(a)
    
#Printing the list
print(“The list entered is:”,list1)

#The function delete element is called
deleteElements()


OUTPUT:
How many elements do you want to add in the list? 10
Enter the elements: 1
Enter the elements: 2
Enter the elements: 9
Enter the elements: 8
Enter the elements: 4
Enter the elements: 5
Enter the elements: 7
Enter the elements: 11
Enter the elements: 13
Enter the elements: 15
The list entered is: [1, 2, 9, 8, 4, 5, 7, 11, 13, 15]
Do you want to delete any element from the list? (Y/N) Y
Enter the element which you would like to delete: 11
The element is deleted from the list. 
Do you want to delete any element from the list? (Y/N) n
The elements in the list [1, 2, 9, 8, 4, 5, 7, 13, 15]


b) Program:
def deleteElementsAtIndex():
    global list1
#Asking the user if he want to delete any element from the list
    inp = input(“Do you want to delete any element from the list? (Y/N) “)
#if user input is yes
    if(inp == ‘Y’ or inp == ‘y’):
        index = int(input(“Enter the index of the element you would like to delete: “))
#Using pop() function to remove the element at desired index
        if(index < len(list1)):
            list1.pop(index)
            print(“The element is deleted from the list. “)
        else:
            print(“The index is out of range.”)
        
        deleteElementsAtIndex()
    else:
        print(“The elements in the list”,list1)

#Defining empty list
list1 = list()
#Taking the number of elements to be added as input
inp = int(input(“How many elements do you want to add in the list? “))

#Taking the input from user
for i in range(inp):
    a = int(input(“Enter the elements: “))
    list1.append(a)
    
#Printing the list
print(“The list entered is:”,list1)

#The function deleteElementsAtIndex is called to delete the element after taking user input
deleteElementsAtIndex()


OUTPUT:
How many elements do you want to add in the list? 7
Enter the elements: 1
Enter the elements: 2
Enter the elements: 3
Enter the elements: 7
Enter the elements: 6
Enter the elements: 5
Enter the elements: 4
The list entered is: [1, 2, 3, 7, 6, 5, 4]
Do you want to delete any element from the list? (Y/N) y
Enter the index of the element you would like to delete: 3
The element is deleted from the list. 
Do you want to delete any element from the list? (Y/N) n
The elements in the list [1, 2, 3, 6, 5, 4]

Page No 206:

Question 9:

 Read a list of n elements. Pass this list to a function which reverses this list in-place without creating a new list.

ANSWER:

Program:
def reverseList():
    global list1
    #Using reverse() function to reverse the list in place
    #This will not create any new list
    list1.reverse()
    print(“Reversed List:”,list1)
    
#Defining empty list
list1 = list()
#Getting input for number of elements to be added in the list
inp = int(input(“How many elements do you want to add in the list? “))

#Taking the input from user
for i in range(inp):
    a = int(input(“Enter the elements: “))
    list1.append(a)
    
#Printing the list
print(“The list entered is:”,list1)

#The function reverseList is called to reverse the list
reverseList()


OUTPUT:
How many elements do you want to add in the list? 6
Enter the elements: 1
Enter the elements: 2
Enter the elements: 4
Enter the elements: 5
Enter the elements: 9
Enter the elements: 3
The list entered is: [1, 2, 4, 5, 9, 3]
Reversed List: [3, 9, 5, 4, 2, 1]

Read More

Chapter 8 : Strings | class 11th | Ncert solution for computer

Class 11 Computer Science – NCERT Book Exercise Solution

Chapter 8. Strings


1. Consider the following string mySubject:

mySubject = “Computer Science”

What will be the output of the following string operations :

i. print(mySubject[0:len(mySubject)])

Answer: Computer Science

ii. print(mySubject[-7:-1])

Answer: Scienc

iii. print(mySubject[::2])

Answer: Cmue cec

iv. print(mySubject[len(mySubject)-1])

Answer: e

v. print(2*mySubject)

Answer: Computer ScienceComputer Science

vi. print(mySubject[::-2])

Answer: eniSrtpo

vii. print(mySubject[:3] + mySubject[3:])

Answer: Computer Science

viii. print(mySubject.swapcase())

Answer: cOMPUTER sCIENCE

ix. print(mySubject.startswith(‘Comp’))

Answer: True

x. print(mySubject.isalpha())

Answer: False

2. Consider the following string myAddress:

myAddress = “WZ-1,New Ganga Nagar,New Delhi”

What will be the output of following string operations :

i. print(myAddress.lower())

Answer: wz-1,new ganga nagar,new delhi

ii. print(myAddress.upper())

Answer: WZ-1,NEW GANGA NAGAR,NEW DELHI

iii. print(myAddress.count(‘New’))

Answer: 2

iv. print(myAddress.find(‘New’))

Answer: 5

v. print(myAddress.rfind(‘New’))

Answer: 21

vi. print(myAddress.split(‘,’))

Answer: [‘WZ-1’, ‘New Ganga Nagar’, ‘New Delhi’]

vii. print(myAddress.split(‘ ‘))

Answer: [‘WZ-1,New’, ‘Ganga’, ‘Nagar,New’, ‘Delhi’]

viii. print(myAddress.replace(‘New’,’Old’))

Answer: WZ-1,Old Ganga Nagar,Old Delhi

ix. print(myAddress.partition(‘,’))

Answer: (‘WZ-1’, ‘,’, ‘New Ganga Nagar,New Delhi’)

x. print(myAddress.index(‘Agra’))

Answer: ValueError: substring ‘Agra’ not found


Programming Problems

1. Write a program to input line(s) of text from the user until enter is pressed. Count the total number of characters in the text (including white spaces),total number of alphabets, total number of digits, total number of special symbols and total number of words in the given text. (Assume that each word is separated by one space).

Answer: Function to count characters, alphabets, digits, special symbols and total number of words

def counter(string):
    alpha = 0
    space = 0
    digit = 0
    symbol = 0

    noofchars = len(string)
    
    for ch in string:
        if ch.isalpha():
            alpha = alpha + 1
        elif ch.isdigit():
            digit = digit + 1
        elif ch.isspace():
            space = space + 1
        else:
            symbol = symbol + 1
    print("Number of characters : ", noofchars)
    print("Number of alphabets : ", alpha)
    print("Number of digits : ", digit)
    print("Number of symbols : ", symbol)
    print("Number of spaces : ", space)
    print("Number of words : ", space + 1)


sentence = input("Enter a sentence : ")
counter(sentence)

Output :

Enter a sentence : hello 259 & how ^ you @; ,
Number of characters : 26
Number of alphabets : 11
Number of digits : 3
Number of symbols : 5
Number of spaces : 7
Number of words : 8


2. Write a user defined function to convert a string with more than one word into title case string where string is passed as parameter. (Title case means that the first letter of each word is capitalised)

Answer: convert a string into the title case

def titlecase(string):
    return string.title()


sentence = input("Enter a sentence : ")
newstr = titlecase(sentence)
print(newstr)

Output:

Enter a sentence : my cs tutorial dot in
My Cs Tutorial Dot In


3. Write a function deleteChar() which takes two parameters one is a string and other is a character. The function should create a new string after deleting all occurrences of the character from the string and return the new string.

Answer: Function to Delete Specified Character from a String

def deleteChar(string, character):
    newstring = ""
    for ch in string:
        if ch != character:
            newstring += ch
    return newstring

string = input("Enter a string : ")
char = input("Enter character want to delete : ")

newstr = deleteChar(string, char)

print("After deleting, string is =>")
print(newstr)

Output:

Enter a string : hello my dear students
Enter character want to delete : e

After deleting, string is =>
hllo my dar studnts


4. Input a string having some digits. Write a function to return the sum of digits present in this string.

Answer: Function to return the sum of digits present in this string

def sumofdigits(string):
    sum = 0
    for ch in string:
        if ch.isdigit():
            sum = sum + int(ch)
    return sum


string = "my 23 cs 85 tutorial25"
print("Sum of digits ", sumofdigits(string))

Output:

Sum of digits 25


5. Write a function that takes a sentence as an input parameter where each word in the sentence is separated by a space. The function should replace each blank with a hyphen and then return the modified sentence.

Answer: Function to replace each space of sentence with hyphen.

#Question 5 : replace space with hypen

def replacespace(sentence):
    newstr =""
    for ch  in sentence:
        if ch.isspace():
            newstr = newstr + "-"
        else:
            newstr = newstr + ch
    return newstr


sentence = input("Enter a sentence : ")
newsentence = replacespace(sentence)
print(newsentence)

Method – II

#Method - II Using String Function

def replacespace2(sentence):
    return sentence.replace(' ','-')

sentence = input("Enter a sentence : ")
newsentence = replacespace2(sentence)
print(newsentence)

Output

Enter a sentence : my cs tutorial
my-cs-tutorial

Read More

Chapter 7 : Functions | class 11th | Ncert solution for computer

Class 11 Computer Science Ch 7 Functions in Python NCERT Book Exercise Solution

Chapter – 7 : Functions in Python



• In programming, functions are used to achieve modularity and reusability.

• Function can be defined as a named group of instructions that are executed when the function is invoked or called by its name. Programmers
can write their own functions known as user defined functions.

• The Python interpreter has a number of functions built into it. These are the functions that are frequently used in a Python program. Such functions are known as built-in functions.

• An argument is a value passed to the function during function call which is received in a parameter defined in function header.

• Python allows assigning a default value to the parameter.

• A function returns value(s) to the calling function using return statement.

• Multiple values in Python are returned through a Tuple.

• Flow of execution can be defined as the order in which the statements in a program are executed.

• The part of the program where a variable is accessible is defined as the scope of the variable.

• A variable that is defined outside any particular function or block is known as a global variable. It can be accessed anywhere in the program.

• A variable that is defined inside any function or block is known as a local variable. It can be accessed only in the function or block where it is defined. It exists only till the function executes or remains active.

• The Python standard library is an extensive collection of functions and modules that help the programmer in the faster development of programs.

• A module is a Python file that contains definitions of multiple functions.

• A module can be imported in a program using import statement.

• Irrespective of the number of times a module is imported, it is loaded only once.

• To import specific functions in a program from a module, from statement can be used.


NCERT Book Exercise Solution – Ch 7 : Functions

1. Observe the following programs carefully, and identify the error:

a) Identify the error

def create (text, freq):
    for i in range (1, freq):
        print text
create(5) #function call

Answer: – Error 1 : print text :- in this statement () is missing. Correct statement is print(text)

Error 2 : create(5) in this statement missing of one argument.

Correct statement is

create(5, ‘mycstutorial.in’)


b) Identify the error:

from math import sqrt,ceil
def calc():
    print cos(0)
calc() #function call

Answer: – Missing of parentheses () in print statement.

Invalid call of cos() function. Function cos() not imported.

print(sqrt(4))

print(ceil(234.876))


c) Identify the error

12345mynum =9defadd9():    mynum =mynum +9    printmynumadd9() #function call 

Answer: – Missing of parentheses () in print statement.

Correct Statement is

print(mynum)


d) Identify the error

def findValue( vall = 1.1, val2, val3):
    final = (val2 + val3)/ vall
    print(final)
findvalue() #function call  

Answer: – In function header def findValue(), non-default argument can not be allowed after the default argument.


e) Identify the error

def greet():
    return("Good morning")
greet() = message #function call  

Answer: – Function call statement is written wrong.

It should be

message = greet()


2. How is math.ceil(89.7) different from math.floor(89.7)?

Answer: – math.ceil(x) vs math.floor(x)

math.ceil(x) : Return the ceiling of x, the smallest integer greater than or equal to x.

math.floor(x) : Return the floor of x, the largest integer less than or equal to x.

math.ceil() vs math.floor()

3. Out of random() and randint(), which function should we use to generate random numbers between 1 and 5. Justify.

Answer: – randint() function of random module returns the number between start to end.

Example :


4. How is built-in function pow() function different from function math.pow() ? Explain with an example.

Answer: – pow() is an built-in function while math.pow() function defined under the math module. Both function is used to calculate x**y i.e. x raised to power y.

When x and y are integer and given as argument to pow() and math.pow() :

pow( x, y) function returns the value as integer type, while math.pow(x, y) function returns float type value.

pow() vs math.pow()

5. Using an example show how a function in Python can return multiple values.

Answer: – A function in python can return multiple values in the form of tuple.

123456789defcalcsquare(x, y, z):    t =x**2, y**2, z**2    returntsq =calcsquare(3,4,5)print(sq)a, b, c =calcsquare(3,4,5)print(a, b, c)

6. Differentiate between following with the help of an example:

a) Argument and Parameter

Answer: – Argument : Variable / Value / Expression which is written inside the parenthesis at the time of function call to passed to the function is called Argument.

Parameter: Variable written inside the parenthesis in the function header is called parameter.

An argument is a value passed to the function during the function call which is received in corresponding parameter defined in function header.

0102030405060708091011#function headerdefsumSquares(n): #n is the parameter    sum=0    fori inrange(1,n+1):        sum=sum+i    print("The sum of first",n,"natural numbers is: ",sum)num =int(input("Enter the value for n: "))#num is an argument referring to the value input by the usersumSquares(num) #function call

b) Global and Local variable.

Answer: – A variable that has global scope is known as a global variable and a variable that has a local scope is known as a local variable.

Global Variable : In Python, a variable that is defined outside any function or any block is known as a global variable. It can be accessed in any functions defined onwards. Any change made to the global variable will impact all the functions in the program where that variable can be accessed.

Local Variable : A variable that is defined inside any function or a block is known as a local variable. It can be accessed only in the function or a block where it is defined. It exists only till the function executes.

Output:

Accessing num = 5
num reassigned = 10
Accessing num outside myfunc1 10

Read More

Chapter 6 : Flow of Control | class 11th | Ncert solution for computer

NCERT Solutions Class 11 Computer Science Chapter 6 – Flow of Control

Question1. What is the difference between else and elif construct of if statement?

Answer:

Elseelif
Else is a part of if statement.The elif is short for else if.
Else statement is executed whenever the if statement is getting false.Elif executed block of code whenever one of the condition evaluate true.
Example:If(a<b)Print “a less than b”ElsePrint “ a is not less than b” Example:If num> 0;Print “positive number”Elifnum == 0;Print “zero”Else:Print “negative number”  

Question 2. What is the purpose of range() function? Give one example.

Answer:

Function range() is used for creating a list containing the integer values in sequence from start value to stop value. Sometimes it is used for generating the number sequentially in for loop.

Example:

Question 3. Differentiate between break and continue statements using examples.

Answer:

Break StatementContinue Statement
Break statement is to break the loop.Continue statement is used to to continue the loop
Break statement is used with switch statementContinue statement is not used with switch statements
Keyword: breakKeyword: continue

Question 4. What is an infinite loop? Give one example.

Answer:

  • Infinite loop execute when while condition never become false
  • If condition remain true. the loop will never get terminated.
  • The control enters in loop and keeps repeating the same block code and loop never end.

Example:

a = 1

while a==1:

b = input(“what’s your birthdate?”)

print(“your birthdate is ”, b)

Output:

What’s your birthdate?

13

your birthdate is 13

What’s your birthdate?

14

your birthdate is 14

What’s your birthdate?

15

your birthdate is 15

What’s your birthdate?

16

your birthdate is 16

:

:

:

Question 5. Find the output of the following program segments:

(i) a = 110

while a > 100:

print(a)

a  -= 2

Output: 110

108

106

104

(ii) for i in range(20,30,2):

print(i)

Output: 20
22
24
26
28

(iii) country = ‘INDIA’

for i in country:

print (i)

Output:

I
N
D
I
A

(iv) i = 0; sum = 0

while i < 9:

if i % 4 == 0:

sum = sum + i

i = i + 2

print (sum)

Output: 12

  1. v) for x in range(1,4):

for y in range(2,5):

if x * y > 10:

break

print (x * y)

Output:

2
3
4
4
6
8
6
9

(v) var = 7

whilevar> 0:

print (‘Current variable value: ‘, var)

var = var -1

if var == 3:

break

else:

if var == 6:

var = var -1

continue

print (“Good bye!”)

Output:

Current variable value:  7
Current variable value:  5
Good bye!
Current variable value:  4

Programming Exercises

Question 1. Write a program that takes the name and age of the user as input and displays a message whether the user is eligible to apply for a driving license or not. (the eligible age is 18 years).

Answer:

Question 2. Write a function to print the table of a given number. The number has to be entered by the user.

Answer:

Question 3. Write a program that prints minimum and maximum of five numbers entered by the user.

Answer:

Question 4. Write a program to check if the year entered by the user is a leap year or not.

Question 5. Write a program to generate the sequence: –5, 10, –15, 20, –25….. upto n, where n is an integer input by the user.

Question 6. Write a program to find the sum of 1+ 1/8 + 1/27.

Answer:

Question 7.Write a program to find the sum of digits of an integer number, input by the user.

Answer:

Question 8. Write a function that checks whether an input number is a palindrome or not. [Note: A number or a string is called palindrome if it appears same when written in reverse order also. For example, 12321 is a palindrome while 123421 is not a palindrome]

Program:

rev = 0
n = int(input(“Enter the number: “))
temp = n

while temp > 0:
digit = (temp % 10)
rev = (rev * 10) + digit
temp = temp // 10

if(n == rev):
print(“The number is a palindrome.”)
else:
print(“The  number is not a palindrome.”)

output:

Enter the number: 5665

The number is a palindrome.

Question 9. Write a program to print the following patterns

Answer:

(i)

(ii)

(iii)

(iv)

Question 10:Write a program to find the grade of a student when grades are allocated as given in the table below. Percentage of the marks obtained by the student is input to the program.

Percentage of Marks Grade
Above 90%A
80% to 90%B
70% to 80%C
60% to 70%D
Below 60%E

Answer:

Program:

OUTPUT:

n = float(input(‘Enter the percentage of the student: ‘))

if(n > 90):
print(“Grade A”)
elif(n > 80):
print(“Grade B”)
elif(n > 70):
print(“Grade C”)
elif(n >= 60):
print(“Grade D”)
else:
print(“Grade E”)

OUTPUT:

Enter the percentage of the number: 91

Grade A

Read More

Chapter 5 Getting Started with Python | class 11th | Ncert solution for computer

NCERT Solutions Class 11 Computer Science Chapter 5 Getting Started with Python

Question 1. Which of the following identifier names are invalid and why?

i Serial_no.                     v Total_Marks

ii 1st_Room                   vi total-Marks

iii Hundred$                   vii _Percentage

iv Total Marks                viii True

Answer:

i) Serial_no. :- Invalid

Reason- (.) is not allowed in identifier

ii) 1st_Room :- Invalid

Reason- identifier can’t start with number

iii) Hundred$ :-  Invalid

Reason- We can’t use special symbol $ in identifier

iv) Total Marks :- Invalid

Reason- We can’t use space between in identifier

v) Total_Marks :- Valid

Reason- We can use underscore between in identifier

vi) total-Marks :- Invalid

Reason- We can’t use hyphen between in identifier

vii) _Percentage:- Invalid

Reason- Identifier can’t begin with underscore

viii) True :- Invalid

Reason- We can’t use keyword as a identifier

Question 2. Write the corresponding Python assignment statements:

a) Assign 10 to variable length and 20 to variable breadth.

b) Assign the average of values of variables length and breadth to a variable sum.

c) Assign a list containing strings ‘Paper’, ‘Gel Pen’, and ‘Eraser’ to a variable stationery.

d) Assign the strings ‘Mohandas’, ‘Karamchand’, and ‘Gandhi’ to variables first, middle and last.

e) Assign the concatenated value of string variables first, middle and last to variable fullname. Make sure to incorporate blank spaces appropriately between different parts of names.

Answer:

a) Assign 10 to variable length and 20 to variable breadth.

length = 10

breadth = 20

b) Assign the average of values of variables length and breadth to a variable sum.

Sum = (length + breadth)/2

c) Assign a list containing strings ‘Paper’, ‘Gel Pen’, and ‘Eraser’ to a variable stationery.

Stationary=[‘Paper’ ,  ‘Gel Pen’ , ‘Eraser’

d) Assign the strings ‘Mohandas’, ‘Karamchand’, and ‘Gandhi’ to variables first, middle and last.

first = ‘Mohandas’

middle= ‘Karamchand’

last= ‘Gandhi’

e) Assign the concatenated value of string variables first, middle and last to variable fullname. Make sure to incorporate blank spaces appropriately between different parts of names.

fullname = first +” “+ middle +” “+ last

Question 3. Write logical expressions corresponding to the following statements in Python and evaluate the expressions (assuming variables num1, num2, num3, first, middle, last are already having meaningful values):

a) The sum of 20 and –10 is less than 12.

b) num3 is not more than 24.

c) 6.75 is between the values of integers num1 and num2.

d) The string ‘middle’ is larger than the string ‘first’ and smaller than the string ‘last’.

e) List Stationery is empty.

Answer:

STATEMENTLOGICAL EXPRESSIONS
The sum of 20 and –10 is less than 12.(20 + (-10)) < 12
num3 is not more than 24.num3 <= 24   or not(num3 > 24)
6.75 is between the values of integers num1 and num2.(6.75 >= num1) and (6.75 <= num2)
The string ‘middle’ is larger than the string ‘first’ and smaller than the string ‘last’.(middle > first) and (middle < last)
List Stationery is empty.len(Stationery) == 0

Question 4. Add a pair of parentheses to each expression so that it evaluates to True.

a) 0 == 1 == 2

b) 2 + 3 == 4 + 5 == 7

c) 1 < -1 == 3 > 4

Answer:

EXPRESSIONEXPRESSION WITH PARENTHESIS
0 == 1 == 2(0 == (1 == 2))
2 + 3 == 4 + 5 == 7(2 + (3 == 4 )+ 5) == 7
1 < -1 == 3 > 4(1 < -1 ) == (3 > 4)

Question 5. Write the output of the following:

a) num1 = 4

num2 = num1 + 1

num1 = 2

print (num1, num2)

b) num1, num2 = 2, 6

num1, num2 = num2, num1 + 2

print (num1, num2)

c) num1, num2 = 2, 3

num3, num2 = num1, num3 + 1

print (num1, num2, num3)

Answer:

a) num1 = 4

num2 = num1 + 1

num1 = 2

Output: 2,5

b) num1, num2 = 2, 6

num1, num2 = num2, num1 + 2

print (num1, num2)

Output: 6,4

c) num1, num2 = 2, 3

num3, num2 = num1, num3 + 1

print (num1, num2, num3)

Output: error

Question 6. Which data type will be used to represent the following data values and why?

a) Number of months in a year

b) Resident of Delhi or not

c) Mobile number

d) Pocket money

e) Volume of a sphere

f) Perimeter of a square

g) Name of the student

h) Address of the student

Answer:

DATA VALUESDATA TYPESREASON
Number of months in a yearIntegerNumber of months contain only number values (integer).
Resident of Delhi or notBooleanIt gives the answer in the form of true and false
Mobile numberIntegerMobile number only contain integer number value
Pocket moneyFloatMoney can be count as 100rs 50 paisa(100.50)
Volume of a sphereFloatThe volume can be calculated in the decimal point
Perimeter of a squareFloatThe perimeter can be calculated in the decimal point
Name of the studentStringName is a set of character, hence data type of name of student is string
Address of the studentStringAddress is a set of character, hence data type of address of student is string

Question 7. Give the output of the following when num1 = 4, num2 = 3, num3 = 2

a) num1 += num2 + num3

print (num1)

b) num1 = num1 ** (num2 + num3)

print (num1)

c) num1 **= num2 + num3

d) num1 = ‘5’ + ‘5’

print(num1)

e) print(4.00/(2.0+2.0))

f) num1 = 2+9*((3*12)-8)/10

print(num1)

g) num1 = 24 // 4 // 2

print(num1)

h) num1 = float(10)

print (num1)

i) num1 = int(‘3.14’)

print (num1)

j) print(‘Bye’ == ‘BYE’)

k) print(10 != 9 and 20 >= 20)

l) print(10 + 6 * 2 ** 2 != 9//4 -3 and 29

>= 29/9)

m) print(5 % 10 + 10 < 50 and 29 <= 29)

n) print((0 < 6) or (not(10 == 6) and

(10<0)))

Answer:

a) num1 += num2 + num3

print (num1)

Output:9

b) num1 = num1 ** (num2 + num3)

print (num1)

Output:1024

c) num1 **= num2 + num3

Output:1024

d) num1 = ‘5’ + ‘5’

print(num1)

Output:55

e) print(4.00/(2.0+2.0))

Output:1.0

f) num1 = 2+9*((3*12)-8)/10

print (num1)

Output:27.2

g) num1 = 24 // 4 // 2

print(num1)

Output:3

h) num1 = float(10)

print (num1)

Output:10.0

i) num1 = int(‘3.14’)

print (num1)

Output: error

j) print(‘Bye’ == ‘BYE’)

Output: False

k) print(10 != 9 and 20 >= 20)

Output:True

l) print(10 + 6 * 2 ** 2 != 9//4 -3 and 29

>= 29/9)

Output: True

m) print(5 % 10 + 10 < 50 and 29 <= 29)

Output: True

n) print((0 < 6) or (not(10 == 6) and

(10<0)))

Output: True

Question 8. Categorise the following as syntax error, logical error or runtime error:

a) 25 / 0

b) num1 = 25; num2 = 0; num1/num2

Answer:

a) 25 / 0 :- Runtime Error, because of divisible by zero

b) num1 = 25; num2 = 0; num1/num2 :- Runtime Error, because of divisible by zero

Question 9. A dartboard of radius 10 units and the wall it is hanging on are represented using a two-dimensional coordinate system, with the board’s center at coordinate (0,0). Variables x and y store the x-coordinate and the y-coordinate of a dart that hits the dartboard. Write a Python expression using variables x and y that evaluates to True if the dart hits (is within) the dartboard, and then evaluate the expression for these dart coordinates:

a) (0,0)

b) (10,10)

c) (6, 6)

d) (7,8)

Question 10. Write a Python program to convert temperature in degree Celsius to degree Fahrenheit. If water boils at 100 degree C and freezes as 0 degree C, use the program to find out what is the boiling point and freezing point of water on the Fahrenheit scale. (Hint: T(°F) = T(°C) × 9/5 + 32)

Answer:

deffar_conv(t):

x=t*9/5 + 32

return x

print(far_conv(100))

Question 11. Write a Python program to calculate the amount payable if money has been lent on simple interest. Notes Ch 5.indd 117 08-Apr-19 12:35:13 PM 2020-21 118 Computer Science – Class xi Principal or money lent = P, Rate of interest = R% per annum and Time = T years. Then Simple Interest (SI) = (P x R x T)/ 100. Amount payable = Principal + SI. P, R and T are given as input to the program.

Answer:

principal=int(input(“P=”))

rate=int(input(“I=”))

time=int(input(“T=”))

defamount_pay(principal,rate,time):

simple_intrest=(principal*rate*time)/100

TOTAL_amount=Print+simple_intrest

returnTOTAL_amount

print(“Total Payble amount”)

print(amount_pay(principal,rate,time))

Question 12.Write a program to calculate in how many days a work will be completed by three persons A, B and C together. A, B, C take x days, y days and z days respectively to do the job alone. The formula to calculate the number of days if they work together is xyz/(xy + yz + xz) days where x, y, and z are given as input to the program.

Answer:

x=int(input(“x=”))

y=int(input(“Y=”))

z=int(input(“Y=”))

defwork_days(x,y,z):

days=x*y*z/(x*y+y*z+z*x)

return days

print(“Work will complet(in days)”)

print(work_days(x,y,z))

Question 13. Write a program to enter two integers and perform all arithmetic operations on them.

Answer:

a=int(input(“Enter First Number: “))

b=int(input(“Enter Second Number: “))

defAddtion(a,b):

returna+b

def subtraction(a,b):

return a-b

def multiplication(a,b):

return a*b

def division(a,b):

return a/b

print(“Addtion of {0} & {1} is : “.format(a,b))

print(Addtion(a,b))

print(“subtraction of {0} & {1} is : “.format(a,b))

print(subtraction(a,b))

print(“multiplicationof {0} & {1} is : “.format(a,b))

print(multiplication(a,b))

print(“division of {0} & {1} is : “.format(a,b))

print(division(a,b))

Question14. Write a program to swap two numbers using a third variable.

Answer:

first_number=int(input(“Enter First Number: “))

second_number=int(input(“Enter Second Number: “))

def swap(first_number,second_number):

third_variable=first_number

first_number=second_number

second_number=third_variable

returnfirst_number,second_number

print(swap(first_number,second_number))

Question 15. Write a program to swap two numbers without using a third variable.

Answer:

first_number=int(input(“Enter First Number: “))

second_number=int(input(“Enter Second Number: “))

def swap(first_number,second_number):

first_number,second_number=second_number,first_number

returnfirst_number,second_number

print(swap(first_number,second_number))

Question 16. Write a program to repeat the string ‘‘GOOD MORNING” n times. Here ‘n’ is an integer entered by the user.

Answer:

n=int(input(“Enter Number: “))

fori in range(n):

print(“GOOD MORINING “)

Question 17. Write a program to find average of three numbers.

Answer:

x=int(input(“Enter First Number: “))

y=int(input(“Enter Second Number: “))

z=int(input(“Enter Third Number: “))

def  average(x,y,z):

avg=x+y+z/3

returnavg

print(“Average : “)

print(average(x,y,z))

Question 18. The volume of a sphere with radius r is 4/3πr3. Write a Python program to find the volume of spheres with radius 7cm, 12cm, 16cm, respectively.

Answer:

defvolume_sphere(r):

pi=3.1415926535897931

volume=4.0/3.0*pi* r**3

return volume

print(“volume of spheres with radius 7cm”)

print(volume_sphere(7))

print(“volume of spheres with radius 12cm”)

print(volume_sphere(12))

print(“volume of spheres with radius 16cm”)

print(volume_sphere(16))

Question 19. Write a program that asks the user to enter their name and age. Print a message addressed to the user that tells the user the year in which they will turn 100 years old.

Answer:

fromdatetime import datetime

name = input(‘Name \n’)

age = int(input(‘Age  \n’))

defhundred_year(age):

hundred = int((100-age) + datetime.now().year)

return hundred

x=hundred_year(age)

print (‘Hello %s.  You will turn 100 years old in %s.’ % (name,x))

Question 20. The formula E = mc2 states that the equivalent energy (E) can be calculated as the mass (m) multiplied by the speed of light (c = about 3×108 m/s) squared. Write a program that accepts the mass of an object and determines its energy.

Answer:

m=int(input(“Enter Mass in Kg: “))

def Einstein(m):

c=299792458

e= m*c**2

return e

print(“Equivalent energy (E): “)

print(Einstein(m))

Question 21. Presume that a ladder is put upright against a wall. Let variables length and angle store the length of the ladder and the angle that it forms with the ground as it leans against the wall. Write a Python program to compute the height reached by the ladder on the wall for the following values of length and angle:

a)16 feet and 75 degrees

b)20 feet and 0 degrees

c)24 feet and 45 degrees

d)24 feet and 80 degrees

Answer:

import math

defheight_reched(length,degrees):

radian=math.radians(degrees)

sin=math.sin(radian)

height=round(length*sin,2)

return height

print(” height reached by the ladder on the wall for the  length is 16 feet and 75 degrees “)

print(height_reched(16,75))

print(” height reached by the ladder on the wall for the  length is 20 feet and 0 degrees “)

print(height_reched(20,0))

print(” height reached by the ladder on the wall for the  length is 24 feet and 45 degrees “)

print(height_reched(24,45))

print(” height reached by the ladder on the wall for the  length is 24 feet and 80 degrees “)

print(height_reched(24,80))

Read More

Chapter 4 : Introduction to Problem Solving | class 11th | Ncert solution for computer

NCERT Class 11 Computer Science Solution

Chapter 4 Introduction to Problem Solving

1. Write pseudocode that reads two numbers and divide one by another and display the quotient.

2. Two friends decide who gets the last slice of a cake by flipping a coin five times. The first person to win three flips wins the cake. An input of 1 means player 1 wins a flip, and a 2 means player 2 wins a flip. Design an algorithm to determine who takes the cake?

3. Write the pseudocode to print all multiples of 5 between 10 and 25 (including both 10 and 25).

4. Give an example of a loop that is to be executed a certain number of times.

5. Suppose you are collecting money for something. You need 200 in all. You ask your parents, uncles and aunts as well as grandparents. Different people may give either 10, 20 or even 50. You will collect till the total becomes 200. Write the algorithm.

6. Write the pseudocode to print the bill depending upon the price and quantity of an item. Also print Bill GST, which is the bill after adding 5% of tax in the total bill.

7. Write pseudocode that will perform the following:
a) Read the marks of three subjects: Computer Science, Mathematics and Physics, out of 100
b) Calculate the aggregate marks
c) Calculate the percentage of marks

8. Write an algorithm to find the greatest among two different numbers entered by the user.

9. Write an algorithm that performs the following:
Ask a user to enter a number. If the number is between 5 and 15, write the word GREEN. If the number is between 15 and 25, write the word BLUE. if the number is between 25 and 35, write the word ORANGE. If it is any other number, write that ALL COLOURS ARE BEAUTIFUL.

10. Write an algorithm that accepts four numbers as input and find the largest and smallest of them.

11. Write an algorithm to display the total water bill charges of the month depending upon the number of units
consumed by the customer as per the following criteria:
• for the first 100 units @ 5 per unit
• for next 150 units @ 10 per unit
• more than 250 units @ 20 per unit
Also add meter charges of 75 per month to calculate the total water bill .

12. What are conditionals? When they are required in a program?

13. Match the pairs

Answer:

14. Following is an algorithm for going to school or college. Can you suggest improvements in this to include other options?
Reach_School_Algorithm
a) Wake up
b) Get ready
c) Take lunch box
d) Take bus
e) Get off the bus
f) Reach school or college

15. Write a pseudocode to calculate the factorial of a number ( Hint: Factorial of 5, written as 5! =5 × 4× 3× 2×1) .

16. Draw a flowchart to check whether a given number is an Armstrong number. An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 33 + 73 + 1**3 = 371.

17. Following is an algorithm to classify numbers as “Single Digit”, “Double Digit” or “Big”.
Classify_Numbers_Algo
INPUT Number
IF Number < 9
“Single Digit”
Else If Number < 99
“Double Digit”
Else
“Big”

Verify for (5, 9, 47, 99, 100 200) and correct the algorithm if required

18. For some calculations, we want an algorithm that accepts only positive integers upto 100.

Accept_1to100_Algo
INPUT Number
IF (0<= Number) AND (Number <= 100)
ACCEPT
Else
REJECT

a) On what values will this algorithm fail?
b) Can you improve the algorithm?

Read More

Chapter 3 Emerging Trends | class 11th | Ncert solution for computer

NCERT Solutions Class 11 Computer Science Chapter 3 Emerging Trends

Question 1: List some of the cloud-based services that you are using at present.

Answer:

  • Platform as a Service (PaaS) –

It is use for performing Online Coding.

  • Infrastructure as a Service (IaaS) –

It is a web services. Ex. Amazon web service

  • Software as a Service (SaaS) –

SaaS is web based software. Ex . Google map

Question 2: What do you understand by the Internet of Things? List some of its potential applications.

Answer:

Internet of things are related with the human, object, things, animals, car, door, etc. The all things, objects, or living things are immerse with sensor, software, hardware or network for exchanging a data between other devices via same network. With the help of IOT now we can convert our all daily appliances to smart appliances.

List some of its potential applications:

  • Health care (patient monitoring system, hand sanitizations)
  • Industry (Facility management, quality control)
  • Domestic appliances (Automatic power off/on control , door locker)
  • Agriculture (smart farm by using IOT sensor)
  • Transportation (Vehicle tracking)

Question3. Write short notes on the following:

a) Cloud Computing

b) Big data and its Characteristics

Answer:

a) Cloud computing:

Cloud computing is a service which is used to send data over the internet or cloud.

Simply, cloud is a service provider. There are so many Cloud Service Provider Companies are    there. Some of them provide free service and some are paid. We can also stored the the data in our cloud.

Basically, internet and cloud is somewhat same. There are three types of cloud services are there:

  • SaaS: Software as a service provides services via internet for distribution. With the help of Saas an independent one can interacts with the other clients for administrate the application.
  • Paas: With the help of Platform as a service we can able to perform developing running, debugging like coding operation. Paas is generally used for online coding.
  • Iaas: Infrastructure as service provide a web service throughout the internet . Example: Amazon web service

b) Big data and its Characteristics:
As a name suggest it is about huge data manipulation including both structured and unstructured. By using big data we can increase the quality of a data, optimize the data, and manipulate data easily. We know that, in todays, we are all exchanging a data through mobile via internet. In result, the large volume of data is generated and it may be critical also. This data is known as big data. The unstructured data like social media post, chat massages, images, etc. with big volume are very fluently managed by the specialized tools of big data.
Following are the characteristics of big data:

1) Volume:
We know that the big data itself is huge in size. Volume of a big data is related with the size of data
2) Velocity:
The velocity of big data is directly related with how much data is created And getting structured in a stroke from different sources.
3) Verity:
When we browsing, searching or do internet surfing. At that we are dealing with different types of data like music, images, text, videos etc.  Some of them are structured, semi structured or unstructured. Big data can daily with different type of verities of data.
4) Veracity:

It is defined a correctness of data. The data which will be stored, it must be meaningful. Because interpreting incorrect data may cause wrong result.

Question 4. Explain the following along with their applications.

a) Artificial Intelligence

b) Machine Learning

Answer:

a) Artificial Intelligence:

In general term, AI is defined as to make a machine smart as it can do the task better than human. AI means to put a human intelligent into machine. Ai works like a human being. We have to trained our machine with information and knowledge. And machine also learnt from them. As well as from its past experience. As named suggest, we have to put intelligent artificially into the machine
Here are the some example of AI:

  • Siri
  • Google voice
  • Alexa,Etc

b) Machine Learning

Machine learning is a part or application of artificial intelligence. Machine learning provide ability to teach, learn, expertise the machine without any human efforts. Four basic steps are there for building a machine learning application:

  1. Select and prepare :

Firstly, we have to prepare a training dataset with respective data for particular machine learning model.

  1. Choose an algorithm:

Then we have to choose a appropriate algorithm. It tells as how our machine learning model processes our model flow. There are two types of algorithms: Labeled and unlabeled

  1. Training:

It is all about the checking, running, comparing and adjusting a result with the required output.

  1. Improving the model:

The last step is improving quality, correctness, efficiency of a model with respect to time and size.

Question 5. Differentiate between cloud computing and grid computing with suitable examples.

Answer:

Cloud computingGrid computing
Cloud computing is client server architectureGrid  computing is distributed server architecture
 In cloud computing, resources are used in centralized patternIn grid computing, resources are used in collaborative pattern
Cloud service is a paid servicegrid service is a free service
It is more flexibleIt is less flexible
Example: Salesforce, hubspotExample: Bluegrid, DISCOM

Question 6. Justify the following statement: “Storage of data is cost-effective and time saving in cloud computing.”

Answer:

While working on internet or  any system,  we create different types of files and folders, etc.  This data is stored in our local hard disk. But now a days the volume of data are increased  day by day. At the time our local hard disks and a primary storage is not sufficient for storage. And when you go for purchasing external memory or external disk for storing a data, it requires lot of money. When this type of situation occurs, to overcome the situation we can use cloud computing.  In cloud computing we have to just purchase a service not storage. So it will be effective than previous. In cloud computing we just need internet service and revenant data. Hence storage data is cost effective and time saving in cloud computing.

Question 7. What is on-demand service? How it is provided in cloud computing?

Answer:

On-demand service is like a gate and drop service.  Whenever the customer required cloud service for particular time he or she can purchase it and whenever the task is completed, he or she can drop the service. On demand service provides services to the customer or client according to their needs. Example: If a company XYZ want a service for a particular project and for a particular time only. At that time they would be purchase  this service and dropout after the completion of project.

Question8. Write examples of the following:

  1. a) Government provided cloud computing platform
  2. b) Large scale private cloud service providers and the services they provide

Answer:

  1. a) Government provided cloud computing platform : MeghRaj is cloud service which is provided by government.
  2. b) Large scale private cloud service providers and the services they provide : the most commonly large scale private cloud platform is AWS. Amazon Web Service is Iaas (Infrastructure as a service) cloud platform

Question9. A company interested in cloud computing is looking for a provider who offers a set of basic services, such as virtual server provisioning and on demand storage that can be combined into a platform for deploying and running customized applications. What type of cloud computing model fits these requirements?

  1. a) Platform as a Service
  2. b) Software as a Service
  3. c) Application as a Service
  4. d) Infrastructure as a Service

Answer: “Infrastructure as a service” provides a platform for deploying and running customized application.

Question10. If the government plans to make a smart school by applying IoT concepts, how can each of the following be implemented in order to transform a school into IoT-enabled smart school?

  1. a) e-textbooks
  2. b) Smart boards
  3. c) Online Tests
  4. d) Wifi sensors on classrooms doors
  5. e) Sensors in buses to monitor their location
  6. f) Wearables (watches or smart belts) for attendance monitoring.

Answer:

e-textbooks : By using IOT we can available digital book to student for get access from anytime and anywhere.

Smart boards: With the help of IOT we can make a school board work like a tablet. Instead of chalk we can use wireless pen and our hand as a duster.

Online Tests: We can take test virtually. And observe the student via camera and facial       We can also check the answer digitally.

Wifi sensors on classrooms doors: With the help of IOT we can make our door smart. For example, whenever the student enters in classroom, automatically his/her attendance noted.

Sensors in buses to monitor their location: for the safety purpose of student w can track the student via GPS sensor which is monitarized by their parents.

Wearables (watches or smart belts) for attendance monitoring: with the help of wireless sensor, we can track the attendance of students through their watches. Whenever the student enters in classroom the attendance will get marked.

Question 11. Five friends plan to try a startup. However, they have a limited budget and limited computer infrastructure. How can they avail the benefits of cloud services to launch their startup?

Answer:

Cloud service applies charges only for service no for storage and resource. Once we purchase any service, it will be for a lifetime. And we can store a large amount of data into it. Infrastructure as a service is a best service for a startup plans

Question 12. Governments provide various scholarships to students of different classes. Prepare a report on how blockchain technology can be used to promote accountability, transparency and efficiency in distribution of scholarships?

Answer:

Question 13. How are IoT and WoT related?

Answer:

IOT is a internet of thing which is related with things like object which we will use daily. And WoT is web of things which is responsible to connect those IOT things to the web and communicate with the help of various devices like sensor.

Question 14. Match the columns:

Column AColumn B
1. You got a reminder to take medicationA. Smart Parking
2. You got an SMS alert that you forgot to lock the doorB. Smart wearable
3. You got an SMS alert that parking space is available near your blockC. Home Automation
4. You turned off your LED TV from your wrist watchD. Smart Health

Answer:

1. You got a reminder to take medicationD. Smart Health
2. You got an SMS alert that you forgot to lock the doorC. Home Automation
3. You got an SMS alert that parking space is available near your blockA. Smart Parking
4. You turned off your LED TV from your wrist watchB. Smart wearable
Read More

Chapter 2 : Encoding Schemes and Number System | class 11th | Ncert solution for computer

NCERT Solutions Class 11 Computer Science Chapter 2 Encoding Schemes and Number System

Question 1:  Write base values of binary, octal and hexadecimal number system.

Answer:

NUMBER SYSTEMBASE VALUE
Binary number system2
Octal number system8
hexadecimal number system16

Question 2:  Give full form of ASCII and ISCII.

Answer:

  • The full form of ASCII is American Standard Code for Information
  • The full form of ISCII is Indian Script Code for Information Interchange.

Question 3:   Try the following conversions.

(i) (514)8 = (?)10         (iv) (4D9)16 = (?)10

(ii) (220)8 = (?)2          (v) (11001010)2 = (?)10

(iii) (76F)16 = (?)10    (vi) (1010111)2 = (?)10

Answer:

  • (514)8 = (?)10
Digits51   4
Position21   0
Weight828180

Therefore,

                  Decimal number = 5×82 + 1×8+ 4×8

                                      = 5×64 + 1×8 + 4× 1

                                      = 320 + 8 + 4

= (332)10

  • (220)8 = (?)2
Octal Digits22   0
Binary value    (3 bits)010010   000

Therefore,

                  Binary number = (010010000)2

  • (76F)16 = (?)10
Digits76  F(15)
Position21   0
Weight162161160

Therefore,

Decimal number = 7×162 + 6×16+ F×16

                         = 7×256 + 6×16 + F× 1

                                      = 1792 + 96 + 15

                                         = (1903)10

  • (4D9)16 = (?)10
Digits4D  9
Position21   0
Weight162161160

Therefore,

Decimal number = 4×162 + 13×16+ 9×16

                         = 4×256 + 13×16 + 9× 1

                                      = 1024 + 208 + 9

                                         = (1241)10

  • (11001010)2 = (?)10
Digits11001010
Position76543210
Weight2726252423222120

 Therefore,

Decimal number = 1×27+ 1×26+0×25 +0×24 +1×23 +0×22 +1×21 +0×20

                         = 128+64 +8 + 2

                                      = (202)10

  • (1010111)2 = (?)10
Digits1010111
Position6543210
Weight26252423222120

Therefore,

Decimal number = 1×26+ 0×25+1×24 +0×23 +1×22 +1×21 +1×20

                         = 64 +16 + 4+ 2 +1

                                      = (87)10

Question 4: Do the following conversions from decimal number to other number systems.

(i) (54)10 = (?)2          (iv) (889)10 = (?)8

(ii) (120)10 = (?)2        (v) (789)10 = (?)16

(iii) (76)10 = (?)8        (vi) (108)10 = (?)16

Answer:

Question 5: Express the following octal numbers into their equivalent decimal numbers.

(i) 145

(ii) 6760

(iii) 455

(iv) 10.75

Answer:

(i) 145

Digits14   5
Position21   0
Weight828180

Therefore,

 Decimal number = 1×82 +4×8+ 5×8

                                      =1×64 + 4×8 + 5× 1

                                      =64 + 32 + 5

= (101)10

(ii) 6760

Digits676  0
Position321  0
Weight838281    80

Therefore,

Decimal number = 6×83 +7×82 +6×8+ 0×8

                                      =6×512 + 7×64 +6×8 + 0× 1

                                      =3072 + 448 + 48+0

= (3568)10

(i) 455

Digits45   5
Position21   0
Weight828180

Therefore,

Decimal number = 4×82 +5×8+ 5×8

                                      =4×64 + 5×8 + 5× 1

                                      =256 + 40 + 5

= (301)10

(iv) 10.75

Digits10   75
Position10   -1-2
Weight81808-18-2

 Therefore,

Decimal number = 1×81+0×80+7×8-1+5×8-2 

                                        =1×8+0×1+7×0.125+5×0.015625

                                        =8+0+0.875+0.078125

= (8.953125)10

Question 6:  Express the following decimal numbers into hexadecimal numbers. (i) 548 (ii) 4052 (iii) 58 (iv) 100.25

Read More

Chapter 1 : Computer System | class 11th | Ncert solution for computer

NCERT Solution Class 11 Computer Science Chapter 1 – Computer System

1.) Name the software required to make a computer functional. Write down its two primary services?

Ans: To make a computer functional operating system is required. The two services of primary services:

1) Operating system provides services for building and running the application.

2) Operating system provide user interface to the user for enable interaction between computer and  user.

2.) How does the computer understand a program written in high level language?

Ans: Computer understands only machine level language (0 and 1). High level language is a simple English type language written in some symmetric format. To convert high level language into machine language there is need of compiler which can be understood by computer.

3.) Why is the execution time of the machine code less than that of source code?

Ans: We know that computer readable language is machine language. So there is no need to convert machine language whereas Source codes are written in high level language. So there is need to convert it into machine language first. Hence, the execution time of machine language is less than source code.

4.) What is the need of RAM? How does it differ from ROM?

Ans:  RAM (random access memory) is used for quickly accessing a data. RAM is a temporary storage memory and it stores the active using data. Whereas ROM is a read only memory and it is a permanent storage device. Data in RAM is erased when power goes off whereas in ROM data remain as it is.

5.) What is the need for secondary memory?

Ans:  Secondary memory provides a large storage facility as well as it is very cheap .There is a need of secondary storage because it is a permanent storage device. Unlike ROM and RAM secondary memory doesn’t have limited storage.

6.) How do different components of the computer communicate with each other?

Ans: Component of a computer communicate with each other with the help of system bus. System bus provides the facility to transfer the data as well as memory address between one component to another.

7.) Draw the block diagram of a computer system. Briefly write about the functionality of each component.

Ans:

INPUT UNIT :

Input unit has following function:

  • Input unit takes a data instruction from the user for further processing.
  • We know that computer understand machine language. Input unit converts the data to the machine language (machine readable form)

They are various types of input devices are available like keyboard, scanner, mouse, touch screen devices, etc.

CENTRAL PROCESSING UNIT:

CPU i.e.  Central processing unit is responsible for performing all tasks of computer. CPU is like a heart of computer.CPU consists of 3 units:

  • Primary memory
  • Control unit
  • Arithmetic logic unit

ALU:

Arithmetic and logical unit responsible for performing all arithmetic operation like addition, subtraction, multiplication and division .It also responsible for conduct merging, sorting like all sorting techniques .All the calculations of the data perform by ALU.

Control unit:

Control unit is used to control the signals. Control unit receives the instruction, data, and information from input devices and converts it into control signals.

Primary memory:

There are two types of primary memory

  • RAM
  • ROM

RAM:

  • RAM means random access memory.
  • It is a volatile storage.
  • The data stored in RAM temporary.
  • RAM stores the data of active task.

 ROM :

  • ROM mans read only memory.
  • The data stored in ROM is permanent.
  • It cannot be erased during the power cut off.
  • It is a non volatile memory.

OUTPUT UNIT:

An output device is one of the components of computer. output devices is responsible to convert machine code into the human readable form. Monitor, printer etc. are output devices.  The output given by the computer can be in any type like text, graphics, audio, video etc

8.) What is the primary role of system bus? Why data bus is is bidirectional while address bus is unidirectional?

Ans :  To transfer the data, address, control signal between the computer there is a need of system bus. With the help of system bus components of a computer can communicate with each other. Data bus is bidirectional because of two-way transfer process. IT transfers the data among CPU,memory and other peripheral devices. Address bus is unidirectional because whenever the data written in the memory, CPU placed the data on data bus. After that address bus provide specific address to   write the data.

9.) Differentiate between proprietary software and freeware software. Name two software for each type.

Ans:

Proprietary softwareFreeware software
Proprietary software is software which is not available freely or publically.Freeware software are available anywhere publically.
To get Proprietary software there is a need of authenticate licenseTo get freeware software there is no need of authenticate license
To get Proprietary software we must have to pay for itfree software are free of charge
Example: adobe flash player, winRARExample: Linux, vlc player

10.) Write the main difference between microcontroller Notes and microprocessor. Why do smart home appliances have a microcontroller instead of microprocessor embedded in them?

Ans:

MICRO CONTROLLERMICRO PROCESSOR
Micro controller used for perform particular taskMicro processor used for intensive processing
Micro controller does not  have capacity to perform multiple  taskMicro processor have capacity to perform multiple  task
Size of micro controller: 8bit,16 bit,32 bitSize of micro processor: 64 bit,32 bit
Micro controller is cheaper in costMicro processor is expensive
MICRO CONTROLLER consumed less powerMICRO processor consumed more power
Application: microwave ovenApplication: computer, laptop

Smart home appliances have a micro controller because it consumed less electricity. As well as it is very low in cost. Microcontroller requires very less space, it does not require CPU and other peripheral devices.

11.) Mention the different types of data that you deal with while browsing the Internet.

Ans:

Different types of data while browsing the Internet:

Structured: the data which is stored in most organized way is known as structured data

Unstructured: the data which is not stored in organized way is known as unstructured data

Semi structured: the data lies in between the structured and unstructured data is known as semi structured data

12.) Categories the following data as structured, semi structured and unstructured:

  • Newspaper
  • Cricket Match Score
  • HTML Page
  • Patient records in a hospital

Ans:

STRUCTUREDSEMI STRUCTUREDUNSTRUCTURED
Patient record in hospitalCricket match scoreHtml pagenewspaper

13.) Name the input or output device used to do the following:

a) To output audio

b) To enter textual data

c) To make hard copy of a text file

d) To display the data or information

e) To enter audio-based command

f) To build 3D models

g) To assist a visually-impaired individual in entering data

Ans:

a) To output audio – Speaker

b) To enter textual data – Keyboard

c) To make hard copy of a text file – Printer

d) To display the data or information – Monitor

e) To enter audio-based command – Mic

f) To build 3D models – 3D Printer

g) To assist a visually-impaired individual in entering data – Braille keyboards

14.) Identify the category (system, application, programming tool) of the following software:

a) Compiler

b) Assembler

c) Ubuntu

d) Text editor

Ans:

a) Compiler – Programming tool

b) Assembler – Programming tool

c) Ubuntu – System

d) Text editor – Application

Read More