#Python program to swap two numbers using third variables.
Explore tagged Tumblr posts
tutorialwing · 2 years ago
Text
Python Program to Swap two Complex Numbers without Using Third Variable
In this article, we will learn about how to write python program to swap two complex numbers without using third variable. Getting Started The task is to swap two complex numbers in python without using third variable. For example, Assume a = 50.1 + 30j and b = 60.3 – 20j, then output should be a = 60.3 – 20j and b = 50.1 + 30j Now, we need to write python program to swap two complex numbers…
Tumblr media
View On WordPress
0 notes
computerguru-blogs · 3 years ago
Text
Write a Program in Python to Swap two numbers?
 Python program to swap two numbers without using third variables and Python program to swap two numbers using third variables Read more.
1 note · View note
python-program · 2 years ago
Video
youtube
Python Program to Swap Two Numbers using third variable @PankajEduTech
0 notes
inlarn · 4 years ago
Text
Write a program to swap two numbers in python. In the Python programming language, there is a program that swaps two numbers. In a Python program, this program can swap values. It is possible to change the value without using the temp variable or the third variable in the Python programming language https://inlarn.com/write-a-program-to-swap-two-numbers-in-python/
0 notes
techletter · 4 years ago
Text
Basics of Python Programming
Getting started with Python is super easy. Even if you don’t have a programming background or you still can be a master in Python and that too in a very short span of time. The only thing needed here is just practice what you learn. The more you practice, the more you get to used to the language syntax and the better programmer you will be. 
Taking input in python is super easy:-
Tumblr media
Taking user input in an interactive way:-
Tumblr media
TAKING MULTIPLE USER INPUTS IN A SINGLE LINE:-
Like any other programming language, Python also provides the programmers with taking multiple user inputs in a single line without paying extra efforts to  "write more to take more". This is done using the  'split()'  method which splits the entered user input at the separator provided as an argument to split() method:   
SYNTAX:   input().split(separator)
Suppose that you have 4 variables a,b,c,d and you want take user input in a single line. You can do it in the following manner:     
a,b,c,d = input().split()
Done...
Now a question comes to your mind that we haven't provoded the separator to the split() method. How'd the split method split the user input?
The answer to this question is that when no parameter is passed as separator, the split() method by default assumes  ' space '   to be the separator.
Try this yourself on IDLE or try to use them in a program and see the outputs.
Tumblr media
Even/Odd Program in Python:-
Python is really an enjoyable language both for beginners as well as professionals. You can write an elegant code and that too in less LOC (Lines Of Code).See the below program where we need to display whether a number entered by user is Odd/Even.
Note: For simplicity, we assume that you are a beginner and the user is intelligent enough to enter only integers (non-zero). 
        ---Code:---
inp = int(input('Enter any integer: '))
print('Its an even no.' if inp % 2 == 0 else 'Its an odd no.')
         ---Output:---
(1)Enter any integer: 7
    Its an odd no.
(2)Enter any integer: 10
    Its an even no.
Tumblr media
SWAPPING in 'P Y T H O N':-
Unlike other programming languages where swapping needs a third variable or require us to do some arithmetic calculations, swapping(interchanging values between two variables) is far far more easier in Python. Its so easy that we can do it in only a single line of code. Suppose that we have 2 variables 'a' and 'b' with some value in them and we want to swap/interchange their values. We can do it in the following easy manner:
      a,b = b,a  
Done..
Check the below image for clear understanding.
Tumblr media
DIVISIBILITY TEST of two no.s in 'P Y T H O N' :
Divisibility test, as we all know, is a test to check whether a no. is perfectly divisible by another no. i.e., on dividing both the numbers whether the remainder is equal to 0. And this test can be done very easily in Python using the   '%' (modulo) operator. The modulo operator, like other arithmetic operators(+, - , *, /) is an operator which is used to get the REMAINDER of division between 2 numbers. Suppose we want to check whether 53 is divisible by 17 or not. All we need to do is just to write the modulo operator in between the 2 no.s and see the output on terminal as follows:          
>>>   53 % 17          
>>>   2      
As can be seen the remainder is not equal to 0. Hence the numbers do not pass the divisibility test. 
Try this test with other numbers yourself on IDLE or try to use them in a program and see the outputs.
Tumblr media
There are countless such examples which speak for the beauty of this language. I hope you people liked this post and will definitely try learning this awesome languuage.
0 notes
margdarsanme · 5 years ago
Text
NCERT Class 12 Computer Science Chapter 3 Lists Manipulation and Implementation
NCERT Class 12 Computer Science Python Solutions for Chapter 3 :: Lists Manipulation and Implementation
 TOPIC-1
Data StructuresShort Answer Type Questions (2 marks)
Question 1:Define a data structure.Answer:A data structure is a group of data which can be processed as a single unit. This group of data may be of similar or dissimilar data types. Data Structures are very useful while programming because they allow processing of the entire group of data as a single unit.
Question 2:Name the two types of data structures and give difference between them.Answer:Data structures are of two types: Linear and Non – Linear.
In a linear data structure, the elements are stored in a sequential order.
In a non linear data structure, no sequential order is followed.
Linear Data Structure Examples: Arrays: Non-Linear Data Structure Examples: Tree, graph lists, stacks, queues, linked lists.
Question 3:Give difference between an array and a list in Python.Answer:An array is defined as a set of contiguous data of similar data type. Python lists are actually arrays of variable length. The elements of a list are of eterogeneous types which means they are of different data types.
Question 4:How are lists implemented in memory?(or)How is memory allocated to a list in Python?Answer:A list in Python is an array that contains elements (pointers to objects) of a specific size only and this is a common feature of all dynamically typed languages. For implementation of a list, a contiguous array of references to other objects is used. Python keeps a pointer to this array and the array’s length is stored in a list head structure. This makes indexing of a list independent of the size of the list or the value of the index. When items are appended or inserted, the array of references is resized.
Question 5:What is sequential allocation of memory? Why do we say that lists are stored sequentially?Answer:A list is a allocated memory in sequential manner. This means that the elements of the list are stored in memory in sequence of their declaration. So, if you want to view the fifth element of the list, you have to first traverse through first four elements of the list. This is called sequential allocation of memory.
TOPIC-2Searching ListsShort Answer Type Questions-I (2 marks)
Question 1:How is linear search different from binary search?Answer:
Binary search requires the input data to be sorted near search doesn’t.
Binary search requires an ordering comparison; linear search only requires equality comparisons
Binary search has complexity 0(log n); linear search has complexity O(n) as discussed earlier.
Binary search requires random access to the data; linear search only requires sequential access (this can be very important – it means a linear search can stream data of arbitrary size).
Short Answer Type Questions-II (2 marks)
Question 1:Accept a list containing integers randomly. Accept any number and display the position at which the number is found in the list.Answer:maxrange = input(“Enter Count of numbers: ’’)marks=[]flag=Falsefor i in range(0, maxrange):marks. append(input(“ ?”))number = inputfEnter number to be searched”)for i in range(0, maxrange):if marks [i]==number:print number,“found at position”,iflag=Trueif flag==False:print number, “not found in list”
Question 2:What will be the status of the following list after the First, Second and Third pass of the slection sort method used for arranging the following elements in descending order?Note : Show the status of all the elements after each pass very clearly underlining the changes.12,14, -54,64,90,24Answer:
Question 3:For a given list of values in descending order, write a method in Python to search for a value with the help of Binary search method. The method should return position of the value and should return -1 if the value not present in the list.Answer:def binarysrch (nums, x):high=len (nums)low=0while low < high:mid=(low+high)/2midval=nums [mid]if midval > x:low = mid + 1elif midval < x:high = midelse:return midreturn -1
TOPIC-3List SortingShort Answer Type Questions-I (2 marks)
Question 1:What is bubble sort?Answer:Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements “bubble” to the top of the list. Because it only uses comparisons to operate on elements, it is also Called a comparison sort.
Question 2:Write an algorithm for selection sort.Answer:Selection sort performs the following steps:
Starting at index 0, search the entire array to find the next smallest or largest value.
Swap the smallest or largest value found with the value at index 0.
Repeat steps 1 & 2 starting from the next index.
Question 3:Explain insertion sort.Answer:Every repetition of insertion sort removes an element from the input data, inserting it into the correct position in the already-sorted list, until no input elements remain. The choice of which element to remove from the input is arbitrary and can be made using almost any choice algorithm.
Short Answer Type Questions-II (2 marks)
Question 1:Write a function that takes a list that is sorted in ascending order and a number as argument. The function should do the following:
Insert the number passed as argument in a sorted list.
Delete the number from the list.
Answer:from bisect import bisectdef listfunc(sortedlist,number) :insert_point = bisect (sortedlist, number)sortedlist.insert(insert_point,number)print “List after Insertion”print sortedlistsortedlist.remove(number)print “List after Deletion”print sortedlistmaxrange = inputfEnter Count of numbers: ”)numlist=[]flag=Falsefor i in range(0, maxrange):numlist.append(input(“ ?”))numlist.sort()number = inputfEnter the number”)listfunc(numlist,number)
Question 2:Consider the following list 95 79 19 43 52 3Write the passes of bubble sort sorting the list in ascending order till the 3rd iteration.Answer:[79,19, 43, 52, 3, 95]-Pass 1[19, 43,52,3,79, 95]-Pass 2[19,43,3, 52, 79, 95]-Pass 3
Question 3:Write a function that takes a sorted list and a number as an argument. Search for the number in the sorted list using binary search.Answer:def binary_search(SORTEDLIST, number):low=0high=len(SORTEDLIST)found=Falsewhile(low<high) and found==False:mid=(int) (low+high/2)if SORTEDLIST[mid]==number:print “Number found at”,midfound=Truebreakelif SORTEDLIST[mid]<number:low=mid+1else:high=mid-1if low >= high:print “Number not found”maxrange = inputfEnter Count of numbers: ”)numlist = []for i in range(0, maxrange):numlist.append(input(“?”))numlist.sort()print “Sorted list”,numlistnumber = inputfEnter the number”)binary_search(numlist,number)
Question 4:In the following list containing integers, sort the list using Insertion sort algorithm. Also show the status of the list after each iteration.15 -5 20 -10 10Answer:def insertion_sort(DATA_LIST):for K in range (1, len(DATA_LIST)):temp=DATA_LIST[K] # ptr=K-1,while(ptr>=0) and DATA_LIST[ptr]>temp:DATA_LIST[ptr+l]=DATA_LIST[ptr]ptr=ptr-1DATA_LIST [ptr+1] =tempprint DATA_LISTDATA_LIST = [15,-5,20,-10,10]print “LIST BEFOR SORTING”,DATAJ.ISTinsertion_sort(DATA_LIST)[-5,15, 20, -10,10][-5,15,20,-10,10]-Pass 1[-10,-5,15,20,10]-Pass 2[-10,-5,10,15, 20]-Pass 3
Question 5:What will be the status of the following after the First, Second and Third pass of the insertion sort method used for arranging the following elements in descending order ?Note: Show the status of all the elements after each pass very clearly underlining the changes.Answer:
Question 6:Consider the following unsorted list:99 78 25 48 51 11Sort the list using selection sort algorithm. Show the status of the list after every iteration.Answer:def selection_sort(DATA_LIST):for i in range(0, len (DATA_LIST)):min = ifor j in range(i + 1, len(DATA_LIST)):if DATA_LIST[j] < DATA_LIST[min]:min = j# swappingtemp= DATA_LIST[min]DATA_LIST[min] = DATA_LIST[i]DATA_LIST [i]=tempprint DATA_LISTDATA_LIST = [99 78 25 48 51 11]print “LIST BEFOR SORTING”,DATA_LISTselection_sort(DATA_LIST)
Question 7:Consider the following unsorted list Neena Meeta Geeta Reeta Seeta Sort the list using selection sort algorithm. Show the status of the list after every iteration.(or)Sort a list containing names of students in ascending order using selection sort.Answer:def selection_sort(DATA_LIST):for i in range(0, len (DATA_LIST)):min = ifor j in range(i + 1, len(DATA_LIST)):if DATA_LIST[j] < DATA_LIST[min]:min = j# swappingtemp= DATA_LIST[min]DATA_LIST[min] = DATA_LIST[i]DATA_LIST[i]=tempprint DATA_LISTNAME_LIST = [‘Neena’,’Beeta’,’Reeta’,’Geeta’,’Seeta’]print “LIST BEFORE SORTING”,NAME_LISTselection_sort(NAME_LIST)LIST BEFORE SORTING [‘Neena’,‘Beeta’,‘Reeta’, ‘Geeta’, ‘Seeta’][‘Beeta’, ‘Neena’, ‘Reeta’, ‘Geeta’, ‘Seeta’]-Pass 1[‘Beeta’, ‘Geeta’, ‘Reeta’, ‘Neena’, ‘Seeta’]-Pass 2[‘Beeta’, ‘Geeta’, ‘Neena’, ‘Reeta’, ‘Seeta’]-Pass 3[‘Beeta’, ‘Geeta’, ‘Neena’, ‘Reeta’, ‘Seeta’]-Pass 4[‘Beeta’, ‘Geeta’, ‘Neena’, ‘Reeta’, ‘Seeta’]-Pass 5
Question 8:A list contains rollno, name and marks of the student. Sort the list in descending order of marks using selection sort algorithm. [CBSE Text Book]Answer:def selection_sort(DATA_LIST):for i in range(0, len (DATA_LIST)):min = ifor j in range(i + 1, len(DATA_LIST)):if DATA_LIST[j][2] > DATA_LIST[min][2]:min = j# swappingDATA_LIST[min] [0] ,DATA_LIST[i] [0] = DATA_LIST[i] [0] ,DATA_LIST[mm] [0] DATA_LIST[min][l],DATA_LIST[i][l] = DATA_LI ST [i] [ 1 ],DATA_LI ST [min] [ 1 ] DATA_LIST[min] [2] ,DATA_LIST[i] [2] = DATA_LIST[i] [2],DATA_LIST[min] [2]print DATA_LISTmaxrange=input(“Enter Number of Students: ”)Students=[]for i in range(maxrange):Details=[]Details. append(input(“Enter roll_no”))Details.append(raw_input(“Enter name”))Details. append(inprft(“Enter marks”))Students.append(Details)print Studentsselection_sort(Students)
Question 9:What will be the status of the following list after the First. Second and Third pass of the insertion sort method used for arranging the following elements in descending order ?12,34,46, -34,90,23Note : Show the status of all the elements after each pass very clearly underlining the changes.Answer:output of diferent passes Pass One[12,34,46,-34,90,23], {}Pass Two[34, 46, -34, 90, 23} , {12}Pass ThreeLISTS MANIPULATION AND IMPLEMENTATION[46, -34, 90, 23} , {12, 34} Pass SixPass Four {23}, {-34,12, 34, 46, 90}[-34, 90, 23} , { 12, 34, 46} Pass SevenPass Five {} , {-34,12, 23, 34, 46, 90}{90,23} , {-34,12,34,46} It is the sorted list.
Long Answer Type Questions (4 marks)
Question 1:Consider the following unsorted list: 90 78 20 46 54 1 Write the list after:
3rd iteration of selection sort
4th iteration of bubble sort
5th iteration of insertion sort Ans. Working :
Answer:Working :
3rd iteration of selection sort: [1,20,46,78,54,90]
4th iteration of bubble sort: [1, 20, 46, 54, 90, 78]
5th iteration of insertion sort: [1, 20, 46, 54, 78, 90
Question 2:Consider the following unsorted list:10 5 55 13 3 49 36Write the position of elements in the list after:(i) 5th iteration of bubble sort(ü) 7th iteration of insertion sort(iii) 4th iteration of selection sortAnswer:Working :
5th iteration of bubble sort: [3, 5,10,13, 36, 55, 49]
Insertion sort doesn’t have the 7th iteration
4th iteration of selection sort: [3, 5,10,13, 55, 49, 36]
Question 3:Write a class CITY in Python with following– CName # String Value specifications :– Pop # Numeric value for Population instance attributes-KM # Numeric value– Ccode # Numeric value– Density #Numeric value for Population DensityMethods:– Dencal() #Method to calculate Density as Pop/KM– Record() #Method to allow user to enter values Ccode, CName, Pop, KM and call DenCal ( ) method– View() #Method to display all the members also display a message “Highly Populated City” if the Density is more than 10000.Answer:class CITY:def_init_(self): self.Ccode = 0self.CName = self. Pop = 0self.KM = 0 self.Density = 0def DenCal (self) :self.Density = self.Pop/self. KMdef Record (self)self Ccode=input (“Enter Ccode”)self.CName=raw_input (“Enter CName”)self.Pop=input (“Enter population”)self.KM=input (“Enter KM”)DenCal(self) //or self.DenCal()def View (self):print Ccode, CName, Pop, KM, Densityif self.Density > 10000:print (“Highly populated city”)# OR print (“Highly populated city”)
Question 4:A list contains Item_code, Item_name, qty and price. Sort the list :
In ascending order of qty using Bubble sort.
In descending order of price using Insertion sort.
Answer:def bubble_sort(DATA_LIST) :i = 0j = 0l = len(DATA_LIST)for i in range(l):print “Bubble Sort Iterations – Asc order of Quantity”for j in range(i+l,l):if DATA_LlST[i][3] > DATA_LIST[j][3]:# swappingDATA_LIST[i][0], DATA_LIST[j] [0]=DATA LIST[j] [0],DATA_LIST[i] [0]DATA_LIST[i][1], DATA_LIST[j][1]=DATA_ LIST[j][l],DATA_LIST[i][l]DATA_LIST[i] [2], DATA_LIST[j] [2]=DATA_ LIST[j][2],DATA_LIST[i][2]DATA_LIST[i][3], DATA_LIST[j][3]=DATA_ LIST[j][3] ,DATA_LIST[i] [3]print DATA_LISTdef insertion_sort(DATA_LIST):for K in range (1, len(DATA_LIST)):temp=DATA_LIST[K][2]ptr=K-1print “Insertion Sort Iterations – Desc order of price”while(ptr>=0) and DATA_LIST[ptr][2] < temp:DATA_LIST[ptr+1] [0]=DATA_LIST[ptr] [0]DATAJHST [ptr+1] [1]=DATA_LIST[ptr] [1]DATA_LIST[ptr+1][2]=DATA_LIST[ptr][2]DATA_LIST[ptr+1] [3]=DATA_LIST[ptr] [3]ptr=ptr-1DATA_LIST[ptr+1][2]=tempprint DATA_LISTmaxrange = input(“Enter Number of Items: “)Items=[]for i in range (maxrange):Details=[]Details. append(input(“Enter Item Code”))Details.append(raw_input(“Enter Item name”))Details.append(float(raw_input(“Enter price”)))Details.append(input(“Enter Quantity”)) Items. append(Details)print “BEFORE SORTING”,Items bubble_sort(Items)insertion_sort(Items)
TOPIC-4Stacks And Queues With ListsVery Short Answer Type Questions (1 mark)
Question 1:Expand the following:
LIFO
FIFO
Answer:
LIFO: Last-In First-Out
FIFO: First-In First-Out
Question 2:Define stack.Answer:A stack is a data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack; the only element that can be removed is the element that was at the top of the stack.
Question 3:Define Queue.Answer:Queue is a first-in, first-out (FIFO) data structure, i.e. the element added first to the queue will be the one to be removed first. Elements are always added to the rear of the queue and removed from the front of the queue.
Question 4:Write all the operations possible in data structure.Answer:The major operations are:
Traversal
Insertion
Deletion
Searching
Question 5:What are the two major queue operations?Answer:Addition of element is known as INSERT operation, also known as enqueuing. It is done using rear terminal position, i.e. tail end. Removal of element is known as DELETE operation, also known as dequeueing.
Short Answer Type Questions-I (2 marks)
Question 1:Write an algorithm to implement push operation.Answer:
Start
Initialize top with -1.
Input the new element.
Increment top by one.
stack[top]=new element
Print “Item Inserted”
Stop
Question 2:Write an algorithm to implement pop operation.Answer:
Start
If the value of top is -1 go to step 3 else go to step 4
Print “Stack Empty” and go to step 7
Deleted item = Stack[top]
Decrement top by 1
print “Item Deleted”
Stop
Question 3:Write an algorithm to implement insertion opera¬tion of queue.Answer:
Start
Check FRONT and REAR value,
if both the values are -1, then FRONT and REAR are incremented by 1
other wise Rear is incremented by one.
queue [Rear]=new element.
Stop
Question 4:Write an algorithm to implement deletion operation of queue.Answer:
Start
Check for underflow situation by checking value of Front=-1
If it is display appropriate message and stop
Otherwise Deleted item=queue [Front]
If Front=Rear then Front=Rear=-1 Otherwise Front is incremented by one
Print “Item Deleted”
Stop
Question 5:For a given list of values in ascending order, write a method in Python to search for a value with the help of Binary Search method. The method should return position of the value and should return -1 if the value not present in the list.Answer:def Binary Search (list, search):lower_bound=0upper_bond=len(list) -1found=falsepos=’x’while lower_bound< =upper_bond:middle_pos=(lower_bound + upper_bond)/2if list [middle_pos] = = search:pos=middlepos found=True breakelif search < list [middle_pos]:upper_bound=middle_pos-l else:lower_bound=middle_pos + 1 if found:print(“The item found”, pos) else:print (“The item not available”)return (-1)
Long Answer Type Questions (4 marks)
Question 1:Write Insert (city) and Delete (City) methods in Python to add City and Romave City considering them to act as Insert and Delete operations of the data structure Queue.Answer:class queue:city=[ ]def Insert (self):a = raw_input(“Enter city”)queue.city append (a)def Delete (self):if (queue, city = = []):print “Queue empty”else:print “Deleted element is”,queue.city[0]queue.city.delete ()ORclass queue:city=[ ]def Insert(self):a=raw_input(“Enter city”)queue.a.append(a)def Delete(self):if (queue.city==[ ]):print (“Queue emtpy”)elseprint (“Deleted element is”,queue, city [0])
Question 2:Define stack class in Python to operate on stack of numbers.Answer: class Stack:def_init_(self):self.s = [ ]def push(self):a = input(“Enter number”)self.s. append(a)def pop(self):self.s.pop()def display (self):l = len(self.s)for I in range(l-1,1,-1):print self.s[i]
Question 3:Write a function to push any student’s information to stack.Answer:def push(stack):s=[]print “STACK BEFORE PUSH” display(stack)s.append(input(“Enter student rollno?”))s.append(raw_input(“Enter student name”))s.append(raw_input(“Enter student grade”))stack, append(s)def display (stack):l=len(stack)print “STACK CONTENTS”for i in range(l-1,-1,-1):print stack[i]stack=[]print “Creating Stack”n = input(“Enter the number of students”)for i in range(n): student = []student.append(input(“Enter student rollno?”))student.append(raw_input(“Enter student name”))student.append(raw_input(“Enter student grade”))stack, append(student) push(stack)display(stack)
Question 4:Write the push operation of stack containing names using class.Answer:class stack:s=[]def push(self):a=r’aw_input(“Enter any name :”)stack.s.append(a)def display(self):l=len(stack.s) for i in range(l-1,-1,-1):print stack.s[i]a=stackOn= input(“Enter no. of names”)for i in range (n):a.push()a.display()
Question 5:Write Insert (Place) and Delete (Place) methods in Python to be add Place and Remove Place considering them to act as Insert and Delete operations of the data structure Queue.Answer:Class queue: place=[]def Insert (self):a=raw_input (“Enter city”)queue.place. append (a)def delete (self):if (queue.place = = []):print “Queue empty”else:print “Deleted element is”, queue, place [0]class queue :place = [ ]def Insert (self) 1a = rawjnput (“Enter place”) queue, a.append (a)def delete (self):if (queue.place==[ ] ):print (“Queue empty”)else:print (“Deleted element is” queue, place [0])queue.place.delete ( )
Question 6:Write the pop operation of stack containing names using class.Answer:class stack:s=[]def push (self):a=raw_input(“Enter any name :”)stack.s.append(a)def pop(self):if (a.s==D):print “Stack Empty”else:print “Deleted element is : ”,a.s.pop()def display (self):l=len(stack.s)print “STACK CONTENTS”for i in range(l-1,-1,-1):print stack.s[i]a=stack()n= input(“Enter no. of names”)for i in range(n):a.push()a.pop()a.display()
Question 7:Write the pop operation of stack containing num-bers using class.Answer:class stack:s=[]def push(self):a=input(“Enter number :”)stack.s.append(a)def pop(self):if (a.s==[]):print “Stack Empty”else:print “Deleted element is : ”,a.s.pop()def display(self):l=len(stack.s) print “STACK CONTENTS”for i in range(l-1,-1,-1):print stack.s[i]a=stack()n= input(“Enter count of numbers”)for i in range (n):a.push()a.pop()a. display ()
Question 8:Write a function to add any customer’s information to queue.Answer:def insert(queue): customer=[]print “QUEUE BEFORE INSERT” display(queue)customer.append(input(“Enter customer number?’’))customer.append(raw_input(“Enter customer name”))customer.append(input(“Enter customer phone number”))queue. append(customer)def display (queue):l=len(queue)fori in range(O.l): print queue[i]queue=[]print “Creating Queue”n=input(“Enter the number of customers”)for i in range(n):customer=[]customer. append(input(“Enter customer number?”))customer.append(rawjnput(“Enter customer name”))customer.append(input(“Enter customer phone number”))queue.append(customer)insert(queue)display(queue)
Question 9:Write the insertion operation of queue containing character using class.Answer:class queue:s=0def insert(self):a=raw_input(“Enter any letter:”)queue.s.append(a)def display (self):l=len(queue.s)print “QUEUE CONTENTS”for i in range(o,l):print queue. s[i]a=queue()n= input(“Enter no. of letters”)for i in range(n): a.insert()ch = raw_input(“Do you want to insert more letters”)if ch==‘y’:a.insert()a.display()
Question 10:Write Add(Fruit) and Remove (Fruit) methods in Python to insert name of a Fruit and to delete name of a Fruit considering them to act as Insert and Delete operations of the data structure Queue.Answer:def que insert (fruit, Rear) :ch=‘y’while ch==‘y’ or ch==‘yes’Frt=input(“Enter a fruit”)Rear=Rear + 1Fruit, append (Frt)print(“Do you wand to Add more”)ch=input ().upper ( )if ch==’N’ or ch==‘No’ :breakreturn reardef quedelete (Fruit, Rear):if not len (fruist):print f(“Fruit + list is empty”)else :Rear = Rear – 1Frt = Fruit.pop( )print(“Fruit is delete from list”)return Rear
Question 11:Write the deletion operation of queue containing characters using class.Answer:class queue:s=0def insert(self):a=raw_input(“Enter any letter:”)queue.s.append(a)def delete(self):if (a.s==[]):print “Queue Empty”else:print “Deleted element is: ”,queue.s[0]del queue.s[0]def display(self): l=len(queue.s)print “QUEUE CONTENTS”for i in range(0,l):print queue.s[i]a=queue()n= input(“Enter no. of letters”)for i in range (n):a.insert()a. delete()a. display ()
Question 12:Write the deletion operation of queue containing numbers using class.Answer:class queue:s=[]def insert(self):a=input(“Enter the number:”)queue.s.append(a)def delete(self):if (a.s==Q):print “Queue Empty”else:print “Deleted element is: ”,queue.s[0]del queue.s[0]def display(self):l=len(queue.s)print “QUEUE CONTENTS”for i in range(0,l):print queue.s[i]a=queue()n= input(“Enter no. of numbers”)for i in range(n):a.insert()a.delete()a.display()
TOPIC-5Applications of StacksVery Short Answer Type Questions (1 mark)
Question 1:Give one example of infix expression.Answer:A + B *C / D
Question 2:Give one example of postfix expression.Answer:ABC*D/+
Question 3:Give one example of prefix expression.Answer:+/*BCDA
Question 4:Convert (A+B)*C in to postfix form.Answer:AB+C*
Short Answer Type Questions-I (2 marks)
Question 1:Evaluate the following postfix notation of expressio,Show status of stack after every operation.12,2,7,34,20,-, +,5, +Answer:
Question 2:Evaluate the following postfix expression. Show the status of stack after execution of each operation separately: 2,13, + , 5, -,6,3,/,5,*,<Answer:Stack contentsResult: 0
Question 3:Evaluate using stack 10, 3,*, 30, 2,*,-Answer:
Question 4:Evaluate the following Postfix expression :20,10,-15,3,/, +, 5, *Answer:
Question 5:Convert A+ (B*C – (D / E A F) * G) * H into postfix form showing stack status after every step.Answer:
Question 6:Convert (True And False) OR (False And True) into postfix form using stack.Answer:
Question 7:What are the applications of queue in computer?Answer:In a single processor multitasking computer, job(s) wait to be processed form a queue. Same happens when we share a printer with many computers.
Compiling a HLL code.
Using download manager, for multiple files also uses queue for ordering the files.
In multiuser OS – job scheduling is done through queue.
Question 8:Evaluate the following postfix notation of expression. Show status of stack after every operation.Answer:Final Result = 1
Question 9:Evaluatethefollowingpostixnotationofexpression. Show status of stack after every operation.12,2, *, 24,20, -, +, 8, –Answer:
Question 10:Give few applications of stack.Answer:
Expression evaluation
Backtracking (game playing, finding paths, exhaustive searching).
Memory management, run-time environment for nested language features.
Short Answer Type Questions-II (2 marks)
Question 1:Write an algorithm to evaluate postfix expression.Answer:Step 1: StartStep 2: Check all symbols from left to right and repeat steps 3 & 4 for each symbol of expression ‘E’ until all symbols are over.
If the symbol is an operand, push it onto stack.
If the symbol is an operator then:
Pop the top two operands from stack and apply an operator in between them.
Evaluate the expression and place the result back on the stack.
Step 3: Set result equal to top element on the stack.Step 4: Stop
Question 2:Write an algorithm to convert infix to postfix.Answer:
Create an empty stack and an empty postfix output string/stream.
Scan the infix input string/stream left to right.
If the current input token is an operand, simply append it to the output string (note the examples above that the operands remain in the same order).
If the current input token is an operator, pop off all operators that have equal or higher precedence and append them to the output string; push the operator onto the stack. The order of popping is the order in the output.
If the current input token is push it onto the stack.
If the current input token is ‘)’, pop off all operators and append them to the output string until a ‘(‘ is popped; discard the ‘(‘.
If the end of the input string is found, pop all operators and append them to the output string.
via Blogger https://ift.tt/3bYPaoy
0 notes
tutorialwing · 2 years ago
Text
Python Program to Swap two Float Numbers without Using Third Variable
In this article, we will learn about how to write python program to swap two float numbers without using third variable. Getting Started The task is to swap two float numbers in python without using third variable. For example, Assume a = 100.0 and b = 200.0, then output should be a = 200.0 and b = 100.0 Now, we need to write python program to swap two float numbers without using third…
Tumblr media
View On WordPress
0 notes
tutorialwing · 2 years ago
Text
Python Program to Swap two Integer Numbers without Using Third Variable
In this article, we will learn about how to write python program to swap two integer numbers without using third variable. Getting Started The task is to swap two numbers in python without using third variable. For example, Assume a = 100 and b = 200, then output should be a = 200 and b = 100 Now, we need to write python program to swap two integer numbers without using third variable. There are…
Tumblr media
View On WordPress
0 notes
tutorialwing · 2 years ago
Text
Python Program to Swap two Numbers without Third Variable
In this article, we will learn about how to write python program to swap two numbers without using third variable. Getting Started The task is to swap two numbers in python without using any other variable. For example, Let’s assume a and b are two numbers where, a = 50 and b = 60. Now, we need to write a python program to swap these two numbers without using third variable. So, output should be…
Tumblr media
View On WordPress
0 notes
margdarsanme · 5 years ago
Text
NCERT Class 12 Computer Science Chapter 3 Lists Manipulation and Implementation
NCERT Class 12 Computer Science Python Solutions for Chapter 3 :: Lists Manipulation and Implementation
 TOPIC-1
Data StructuresShort Answer Type Questions (2 marks)
Question 1:Define a data structure.Answer:A data structure is a group of data which can be processed as a single unit. This group of data may be of similar or dissimilar data types. Data Structures are very useful while programming because they allow processing of the entire group of data as a single unit.
Question 2:Name the two types of data structures and give difference between them.Answer:Data structures are of two types: Linear and Non – Linear.
In a linear data structure, the elements are stored in a sequential order.
In a non linear data structure, no sequential order is followed.
Linear Data Structure Examples: Arrays: Non-Linear Data Structure Examples: Tree, graph lists, stacks, queues, linked lists.
Question 3:Give difference between an array and a list in Python.Answer:An array is defined as a set of contiguous data of similar data type. Python lists are actually arrays of variable length. The elements of a list are of eterogeneous types which means they are of different data types.
Question 4:How are lists implemented in memory?(or)How is memory allocated to a list in Python?Answer:A list in Python is an array that contains elements (pointers to objects) of a specific size only and this is a common feature of all dynamically typed languages. For implementation of a list, a contiguous array of references to other objects is used. Python keeps a pointer to this array and the array’s length is stored in a list head structure. This makes indexing of a list independent of the size of the list or the value of the index. When items are appended or inserted, the array of references is resized.
Question 5:What is sequential allocation of memory? Why do we say that lists are stored sequentially?Answer:A list is a allocated memory in sequential manner. This means that the elements of the list are stored in memory in sequence of their declaration. So, if you want to view the fifth element of the list, you have to first traverse through first four elements of the list. This is called sequential allocation of memory.
TOPIC-2Searching ListsShort Answer Type Questions-I (2 marks)
Question 1:How is linear search different from binary search?Answer:
Binary search requires the input data to be sorted near search doesn’t.
Binary search requires an ordering comparison; linear search only requires equality comparisons
Binary search has complexity 0(log n); linear search has complexity O(n) as discussed earlier.
Binary search requires random access to the data; linear search only requires sequential access (this can be very important – it means a linear search can stream data of arbitrary size).
Short Answer Type Questions-II (2 marks)
Question 1:Accept a list containing integers randomly. Accept any number and display the position at which the number is found in the list.Answer:maxrange = input(“Enter Count of numbers: ’’)marks=[]flag=Falsefor i in range(0, maxrange):marks. append(input(“ ?”))number = inputfEnter number to be searched”)for i in range(0, maxrange):if marks [i]==number:print number,“found at position”,iflag=Trueif flag==False:print number, “not found in list”
Question 2:What will be the status of the following list after the First, Second and Third pass of the slection sort method used for arranging the following elements in descending order?Note : Show the status of all the elements after each pass very clearly underlining the changes.12,14, -54,64,90,24Answer:
Question 3:For a given list of values in descending order, write a method in Python to search for a value with the help of Binary search method. The method should return position of the value and should return -1 if the value not present in the list.Answer:def binarysrch (nums, x):high=len (nums)low=0while low < high:mid=(low+high)/2midval=nums [mid]if midval > x:low = mid + 1elif midval < x:high = midelse:return midreturn -1
TOPIC-3List SortingShort Answer Type Questions-I (2 marks)
Question 1:What is bubble sort?Answer:Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements “bubble” to the top of the list. Because it only uses comparisons to operate on elements, it is also Called a comparison sort.
Question 2:Write an algorithm for selection sort.Answer:Selection sort performs the following steps:
Starting at index 0, search the entire array to find the next smallest or largest value.
Swap the smallest or largest value found with the value at index 0.
Repeat steps 1 & 2 starting from the next index.
Question 3:Explain insertion sort.Answer:Every repetition of insertion sort removes an element from the input data, inserting it into the correct position in the already-sorted list, until no input elements remain. The choice of which element to remove from the input is arbitrary and can be made using almost any choice algorithm.
Short Answer Type Questions-II (2 marks)
Question 1:Write a function that takes a list that is sorted in ascending order and a number as argument. The function should do the following:
Insert the number passed as argument in a sorted list.
Delete the number from the list.
Answer:from bisect import bisectdef listfunc(sortedlist,number) :insert_point = bisect (sortedlist, number)sortedlist.insert(insert_point,number)print “List after Insertion”print sortedlistsortedlist.remove(number)print “List after Deletion”print sortedlistmaxrange = inputfEnter Count of numbers: ”)numlist=[]flag=Falsefor i in range(0, maxrange):numlist.append(input(“ ?”))numlist.sort()number = inputfEnter the number”)listfunc(numlist,number)
Question 2:Consider the following list 95 79 19 43 52 3Write the passes of bubble sort sorting the list in ascending order till the 3rd iteration.Answer:[79,19, 43, 52, 3, 95]-Pass 1[19, 43,52,3,79, 95]-Pass 2[19,43,3, 52, 79, 95]-Pass 3
Question 3:Write a function that takes a sorted list and a number as an argument. Search for the number in the sorted list using binary search.Answer:def binary_search(SORTEDLIST, number):low=0high=len(SORTEDLIST)found=Falsewhile(low<high) and found==False:mid=(int) (low+high/2)if SORTEDLIST[mid]==number:print “Number found at”,midfound=Truebreakelif SORTEDLIST[mid]<number:low=mid+1else:high=mid-1if low >= high:print “Number not found”maxrange = inputfEnter Count of numbers: ”)numlist = []for i in range(0, maxrange):numlist.append(input(“?”))numlist.sort()print “Sorted list”,numlistnumber = inputfEnter the number”)binary_search(numlist,number)
Question 4:In the following list containing integers, sort the list using Insertion sort algorithm. Also show the status of the list after each iteration.15 -5 20 -10 10Answer:def insertion_sort(DATA_LIST):for K in range (1, len(DATA_LIST)):temp=DATA_LIST[K] # ptr=K-1,while(ptr>=0) and DATA_LIST[ptr]>temp:DATA_LIST[ptr+l]=DATA_LIST[ptr]ptr=ptr-1DATA_LIST [ptr+1] =tempprint DATA_LISTDATA_LIST = [15,-5,20,-10,10]print “LIST BEFOR SORTING”,DATAJ.ISTinsertion_sort(DATA_LIST)[-5,15, 20, -10,10][-5,15,20,-10,10]-Pass 1[-10,-5,15,20,10]-Pass 2[-10,-5,10,15, 20]-Pass 3
Question 5:What will be the status of the following after the First, Second and Third pass of the insertion sort method used for arranging the following elements in descending order ?Note: Show the status of all the elements after each pass very clearly underlining the changes.Answer:
Question 6:Consider the following unsorted list:99 78 25 48 51 11Sort the list using selection sort algorithm. Show the status of the list after every iteration.Answer:def selection_sort(DATA_LIST):for i in range(0, len (DATA_LIST)):min = ifor j in range(i + 1, len(DATA_LIST)):if DATA_LIST[j] < DATA_LIST[min]:min = j# swappingtemp= DATA_LIST[min]DATA_LIST[min] = DATA_LIST[i]DATA_LIST [i]=tempprint DATA_LISTDATA_LIST = [99 78 25 48 51 11]print “LIST BEFOR SORTING”,DATA_LISTselection_sort(DATA_LIST)
Question 7:Consider the following unsorted list Neena Meeta Geeta Reeta Seeta Sort the list using selection sort algorithm. Show the status of the list after every iteration.(or)Sort a list containing names of students in ascending order using selection sort.Answer:def selection_sort(DATA_LIST):for i in range(0, len (DATA_LIST)):min = ifor j in range(i + 1, len(DATA_LIST)):if DATA_LIST[j] < DATA_LIST[min]:min = j# swappingtemp= DATA_LIST[min]DATA_LIST[min] = DATA_LIST[i]DATA_LIST[i]=tempprint DATA_LISTNAME_LIST = [‘Neena’,’Beeta’,’Reeta’,’Geeta’,’Seeta’]print “LIST BEFORE SORTING”,NAME_LISTselection_sort(NAME_LIST)LIST BEFORE SORTING [‘Neena’,‘Beeta’,‘Reeta’, ‘Geeta’, ‘Seeta’][‘Beeta’, ‘Neena’, ‘Reeta’, ‘Geeta’, ‘Seeta’]-Pass 1[‘Beeta’, ‘Geeta’, ‘Reeta’, ‘Neena’, ‘Seeta’]-Pass 2[‘Beeta’, ‘Geeta’, ‘Neena’, ‘Reeta’, ‘Seeta’]-Pass 3[‘Beeta’, ‘Geeta’, ‘Neena’, ‘Reeta’, ‘Seeta’]-Pass 4[‘Beeta’, ‘Geeta’, ‘Neena’, ‘Reeta’, ‘Seeta’]-Pass 5
Question 8:A list contains rollno, name and marks of the student. Sort the list in descending order of marks using selection sort algorithm. [CBSE Text Book]Answer:def selection_sort(DATA_LIST):for i in range(0, len (DATA_LIST)):min = ifor j in range(i + 1, len(DATA_LIST)):if DATA_LIST[j][2] > DATA_LIST[min][2]:min = j# swappingDATA_LIST[min] [0] ,DATA_LIST[i] [0] = DATA_LIST[i] [0] ,DATA_LIST[mm] [0] DATA_LIST[min][l],DATA_LIST[i][l] = DATA_LI ST [i] [ 1 ],DATA_LI ST [min] [ 1 ] DATA_LIST[min] [2] ,DATA_LIST[i] [2] = DATA_LIST[i] [2],DATA_LIST[min] [2]print DATA_LISTmaxrange=input(“Enter Number of Students: ”)Students=[]for i in range(maxrange):Details=[]Details. append(input(“Enter roll_no”))Details.append(raw_input(“Enter name”))Details. append(inprft(“Enter marks”))Students.append(Details)print Studentsselection_sort(Students)
Question 9:What will be the status of the following list after the First. Second and Third pass of the insertion sort method used for arranging the following elements in descending order ?12,34,46, -34,90,23Note : Show the status of all the elements after each pass very clearly underlining the changes.Answer:output of diferent passes Pass One[12,34,46,-34,90,23], {}Pass Two[34, 46, -34, 90, 23} , {12}Pass ThreeLISTS MANIPULATION AND IMPLEMENTATION[46, -34, 90, 23} , {12, 34} Pass SixPass Four {23}, {-34,12, 34, 46, 90}[-34, 90, 23} , { 12, 34, 46} Pass SevenPass Five {} , {-34,12, 23, 34, 46, 90}{90,23} , {-34,12,34,46} It is the sorted list.
Long Answer Type Questions (4 marks)
Question 1:Consider the following unsorted list: 90 78 20 46 54 1 Write the list after:
3rd iteration of selection sort
4th iteration of bubble sort
5th iteration of insertion sort Ans. Working :
Answer:Working :
3rd iteration of selection sort: [1,20,46,78,54,90]
4th iteration of bubble sort: [1, 20, 46, 54, 90, 78]
5th iteration of insertion sort: [1, 20, 46, 54, 78, 90
Question 2:Consider the following unsorted list:10 5 55 13 3 49 36Write the position of elements in the list after:(i) 5th iteration of bubble sort(ü) 7th iteration of insertion sort(iii) 4th iteration of selection sortAnswer:Working :
5th iteration of bubble sort: [3, 5,10,13, 36, 55, 49]
Insertion sort doesn’t have the 7th iteration
4th iteration of selection sort: [3, 5,10,13, 55, 49, 36]
Question 3:Write a class CITY in Python with following– CName # String Value specifications :– Pop # Numeric value for Population instance attributes-KM # Numeric value– Ccode # Numeric value– Density #Numeric value for Population DensityMethods:– Dencal() #Method to calculate Density as Pop/KM– Record() #Method to allow user to enter values Ccode, CName, Pop, KM and call DenCal ( ) method– View() #Method to display all the members also display a message “Highly Populated City” if the Density is more than 10000.Answer:class CITY:def_init_(self): self.Ccode = 0self.CName = self. Pop = 0self.KM = 0 self.Density = 0def DenCal (self) :self.Density = self.Pop/self. KMdef Record (self)self Ccode=input (“Enter Ccode”)self.CName=raw_input (“Enter CName”)self.Pop=input (“Enter population”)self.KM=input (“Enter KM”)DenCal(self) //or self.DenCal()def View (self):print Ccode, CName, Pop, KM, Densityif self.Density > 10000:print (“Highly populated city”)# OR print (“Highly populated city”)
Question 4:A list contains Item_code, Item_name, qty and price. Sort the list :
In ascending order of qty using Bubble sort.
In descending order of price using Insertion sort.
Answer:def bubble_sort(DATA_LIST) :i = 0j = 0l = len(DATA_LIST)for i in range(l):print “Bubble Sort Iterations – Asc order of Quantity”for j in range(i+l,l):if DATA_LlST[i][3] > DATA_LIST[j][3]:# swappingDATA_LIST[i][0], DATA_LIST[j] [0]=DATA LIST[j] [0],DATA_LIST[i] [0]DATA_LIST[i][1], DATA_LIST[j][1]=DATA_ LIST[j][l],DATA_LIST[i][l]DATA_LIST[i] [2], DATA_LIST[j] [2]=DATA_ LIST[j][2],DATA_LIST[i][2]DATA_LIST[i][3], DATA_LIST[j][3]=DATA_ LIST[j][3] ,DATA_LIST[i] [3]print DATA_LISTdef insertion_sort(DATA_LIST):for K in range (1, len(DATA_LIST)):temp=DATA_LIST[K][2]ptr=K-1print “Insertion Sort Iterations – Desc order of price”while(ptr>=0) and DATA_LIST[ptr][2] < temp:DATA_LIST[ptr+1] [0]=DATA_LIST[ptr] [0]DATAJHST [ptr+1] [1]=DATA_LIST[ptr] [1]DATA_LIST[ptr+1][2]=DATA_LIST[ptr][2]DATA_LIST[ptr+1] [3]=DATA_LIST[ptr] [3]ptr=ptr-1DATA_LIST[ptr+1][2]=tempprint DATA_LISTmaxrange = input(“Enter Number of Items: “)Items=[]for i in range (maxrange):Details=[]Details. append(input(“Enter Item Code”))Details.append(raw_input(“Enter Item name”))Details.append(float(raw_input(“Enter price”)))Details.append(input(“Enter Quantity”)) Items. append(Details)print “BEFORE SORTING”,Items bubble_sort(Items)insertion_sort(Items)
TOPIC-4Stacks And Queues With ListsVery Short Answer Type Questions (1 mark)
Question 1:Expand the following:
LIFO
FIFO
Answer:
LIFO: Last-In First-Out
FIFO: First-In First-Out
Question 2:Define stack.Answer:A stack is a data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack; the only element that can be removed is the element that was at the top of the stack.
Question 3:Define Queue.Answer:Queue is a first-in, first-out (FIFO) data structure, i.e. the element added first to the queue will be the one to be removed first. Elements are always added to the rear of the queue and removed from the front of the queue.
Question 4:Write all the operations possible in data structure.Answer:The major operations are:
Traversal
Insertion
Deletion
Searching
Question 5:What are the two major queue operations?Answer:Addition of element is known as INSERT operation, also known as enqueuing. It is done using rear terminal position, i.e. tail end. Removal of element is known as DELETE operation, also known as dequeueing.
Short Answer Type Questions-I (2 marks)
Question 1:Write an algorithm to implement push operation.Answer:
Start
Initialize top with -1.
Input the new element.
Increment top by one.
stack[top]=new element
Print “Item Inserted”
Stop
Question 2:Write an algorithm to implement pop operation.Answer:
Start
If the value of top is -1 go to step 3 else go to step 4
Print “Stack Empty” and go to step 7
Deleted item = Stack[top]
Decrement top by 1
print “Item Deleted”
Stop
Question 3:Write an algorithm to implement insertion opera¬tion of queue.Answer:
Start
Check FRONT and REAR value,
if both the values are -1, then FRONT and REAR are incremented by 1
other wise Rear is incremented by one.
queue [Rear]=new element.
Stop
Question 4:Write an algorithm to implement deletion operation of queue.Answer:
Start
Check for underflow situation by checking value of Front=-1
If it is display appropriate message and stop
Otherwise Deleted item=queue [Front]
If Front=Rear then Front=Rear=-1 Otherwise Front is incremented by one
Print “Item Deleted”
Stop
Question 5:For a given list of values in ascending order, write a method in Python to search for a value with the help of Binary Search method. The method should return position of the value and should return -1 if the value not present in the list.Answer:def Binary Search (list, search):lower_bound=0upper_bond=len(list) -1found=falsepos=’x’while lower_bound< =upper_bond:middle_pos=(lower_bound + upper_bond)/2if list [middle_pos] = = search:pos=middlepos found=True breakelif search < list [middle_pos]:upper_bound=middle_pos-l else:lower_bound=middle_pos + 1 if found:print(“The item found”, pos) else:print (“The item not available”)return (-1)
Long Answer Type Questions (4 marks)
Question 1:Write Insert (city) and Delete (City) methods in Python to add City and Romave City considering them to act as Insert and Delete operations of the data structure Queue.Answer:class queue:city=[ ]def Insert (self):a = raw_input(“Enter city”)queue.city append (a)def Delete (self):if (queue, city = = []):print “Queue empty”else:print “Deleted element is”,queue.city[0]queue.city.delete ()ORclass queue:city=[ ]def Insert(self):a=raw_input(“Enter city”)queue.a.append(a)def Delete(self):if (queue.city==[ ]):print (“Queue emtpy”)elseprint (“Deleted element is”,queue, city [0])
Question 2:Define stack class in Python to operate on stack of numbers.Answer: class Stack:def_init_(self):self.s = [ ]def push(self):a = input(“Enter number”)self.s. append(a)def pop(self):self.s.pop()def display (self):l = len(self.s)for I in range(l-1,1,-1):print self.s[i]
Question 3:Write a function to push any student’s information to stack.Answer:def push(stack):s=[]print “STACK BEFORE PUSH” display(stack)s.append(input(“Enter student rollno?”))s.append(raw_input(“Enter student name”))s.append(raw_input(“Enter student grade”))stack, append(s)def display (stack):l=len(stack)print “STACK CONTENTS”for i in range(l-1,-1,-1):print stack[i]stack=[]print “Creating Stack”n = input(“Enter the number of students”)for i in range(n): student = []student.append(input(“Enter student rollno?”))student.append(raw_input(“Enter student name”))student.append(raw_input(“Enter student grade”))stack, append(student) push(stack)display(stack)
Question 4:Write the push operation of stack containing names using class.Answer:class stack:s=[]def push(self):a=r’aw_input(“Enter any name :”)stack.s.append(a)def display(self):l=len(stack.s) for i in range(l-1,-1,-1):print stack.s[i]a=stackOn= input(“Enter no. of names”)for i in range (n):a.push()a.display()
Question 5:Write Insert (Place) and Delete (Place) methods in Python to be add Place and Remove Place considering them to act as Insert and Delete operations of the data structure Queue.Answer:Class queue: place=[]def Insert (self):a=raw_input (“Enter city”)queue.place. append (a)def delete (self):if (queue.place = = []):print “Queue empty”else:print “Deleted element is”, queue, place [0]class queue :place = [ ]def Insert (self) 1a = rawjnput (“Enter place”) queue, a.append (a)def delete (self):if (queue.place==[ ] ):print (“Queue empty”)else:print (“Deleted element is” queue, place [0])queue.place.delete ( )
Question 6:Write the pop operation of stack containing names using class.Answer:class stack:s=[]def push (self):a=raw_input(“Enter any name :”)stack.s.append(a)def pop(self):if (a.s==D):print “Stack Empty”else:print “Deleted element is : ”,a.s.pop()def display (self):l=len(stack.s)print “STACK CONTENTS”for i in range(l-1,-1,-1):print stack.s[i]a=stack()n= input(“Enter no. of names”)for i in range(n):a.push()a.pop()a.display()
Question 7:Write the pop operation of stack containing num-bers using class.Answer:class stack:s=[]def push(self):a=input(“Enter number :”)stack.s.append(a)def pop(self):if (a.s==[]):print “Stack Empty”else:print “Deleted element is : ”,a.s.pop()def display(self):l=len(stack.s) print “STACK CONTENTS”for i in range(l-1,-1,-1):print stack.s[i]a=stack()n= input(“Enter count of numbers”)for i in range (n):a.push()a.pop()a. display ()
Question 8:Write a function to add any customer’s information to queue.Answer:def insert(queue): customer=[]print “QUEUE BEFORE INSERT” display(queue)customer.append(input(“Enter customer number?’’))customer.append(raw_input(“Enter customer name”))customer.append(input(“Enter customer phone number”))queue. append(customer)def display (queue):l=len(queue)fori in range(O.l): print queue[i]queue=[]print “Creating Queue”n=input(“Enter the number of customers”)for i in range(n):customer=[]customer. append(input(“Enter customer number?”))customer.append(rawjnput(“Enter customer name”))customer.append(input(“Enter customer phone number”))queue.append(customer)insert(queue)display(queue)
Question 9:Write the insertion operation of queue containing character using class.Answer:class queue:s=0def insert(self):a=raw_input(“Enter any letter:”)queue.s.append(a)def display (self):l=len(queue.s)print “QUEUE CONTENTS”for i in range(o,l):print queue. s[i]a=queue()n= input(“Enter no. of letters”)for i in range(n): a.insert()ch = raw_input(“Do you want to insert more letters”)if ch==‘y’:a.insert()a.display()
Question 10:Write Add(Fruit) and Remove (Fruit) methods in Python to insert name of a Fruit and to delete name of a Fruit considering them to act as Insert and Delete operations of the data structure Queue.Answer:def que insert (fruit, Rear) :ch=‘y’while ch==‘y’ or ch==‘yes’Frt=input(“Enter a fruit”)Rear=Rear + 1Fruit, append (Frt)print(“Do you wand to Add more”)ch=input ().upper ( )if ch==’N’ or ch==‘No’ :breakreturn reardef quedelete (Fruit, Rear):if not len (fruist):print f(“Fruit + list is empty”)else :Rear = Rear – 1Frt = Fruit.pop( )print(“Fruit is delete from list”)return Rear
Question 11:Write the deletion operation of queue containing characters using class.Answer:class queue:s=0def insert(self):a=raw_input(“Enter any letter:”)queue.s.append(a)def delete(self):if (a.s==[]):print “Queue Empty”else:print “Deleted element is: ”,queue.s[0]del queue.s[0]def display(self): l=len(queue.s)print “QUEUE CONTENTS”for i in range(0,l):print queue.s[i]a=queue()n= input(“Enter no. of letters”)for i in range (n):a.insert()a. delete()a. display ()
Question 12:Write the deletion operation of queue containing numbers using class.Answer:class queue:s=[]def insert(self):a=input(“Enter the number:”)queue.s.append(a)def delete(self):if (a.s==Q):print “Queue Empty”else:print “Deleted element is: ”,queue.s[0]del queue.s[0]def display(self):l=len(queue.s)print “QUEUE CONTENTS”for i in range(0,l):print queue.s[i]a=queue()n= input(“Enter no. of numbers”)for i in range(n):a.insert()a.delete()a.display()
TOPIC-5Applications of StacksVery Short Answer Type Questions (1 mark)
Question 1:Give one example of infix expression.Answer:A + B *C / D
Question 2:Give one example of postfix expression.Answer:ABC*D/+
Question 3:Give one example of prefix expression.Answer:+/*BCDA
Question 4:Convert (A+B)*C in to postfix form.Answer:AB+C*
Short Answer Type Questions-I (2 marks)
Question 1:Evaluate the following postfix notation of expressio,Show status of stack after every operation.12,2,7,34,20,-, +,5, +Answer:
Question 2:Evaluate the following postfix expression. Show the status of stack after execution of each operation separately: 2,13, + , 5, -,6,3,/,5,*,<Answer:Stack contentsResult: 0
Question 3:Evaluate using stack 10, 3,*, 30, 2,*,-Answer:
Question 4:Evaluate the following Postfix expression :20,10,-15,3,/, +, 5, *Answer:
Question 5:Convert A+ (B*C – (D / E A F) * G) * H into postfix form showing stack status after every step.Answer:
Question 6:Convert (True And False) OR (False And True) into postfix form using stack.Answer:
Question 7:What are the applications of queue in computer?Answer:In a single processor multitasking computer, job(s) wait to be processed form a queue. Same happens when we share a printer with many computers.
Compiling a HLL code.
Using download manager, for multiple files also uses queue for ordering the files.
In multiuser OS – job scheduling is done through queue.
Question 8:Evaluate the following postfix notation of expression. Show status of stack after every operation.Answer:Final Result = 1
Question 9:Evaluatethefollowingpostixnotationofexpression. Show status of stack after every operation.12,2, *, 24,20, -, +, 8, –Answer:
Question 10:Give few applications of stack.Answer:
Expression evaluation
Backtracking (game playing, finding paths, exhaustive searching).
Memory management, run-time environment for nested language features.
Short Answer Type Questions-II (2 marks)
Question 1:Write an algorithm to evaluate postfix expression.Answer:Step 1: StartStep 2: Check all symbols from left to right and repeat steps 3 & 4 for each symbol of expression ‘E’ until all symbols are over.
If the symbol is an operand, push it onto stack.
If the symbol is an operator then:
Pop the top two operands from stack and apply an operator in between them.
Evaluate the expression and place the result back on the stack.
Step 3: Set result equal to top element on the stack.Step 4: Stop
Question 2:Write an algorithm to convert infix to postfix.Answer:
Create an empty stack and an empty postfix output string/stream.
Scan the infix input string/stream left to right.
If the current input token is an operand, simply append it to the output string (note the examples above that the operands remain in the same order).
If the current input token is an operator, pop off all operators that have equal or higher precedence and append them to the output string; push the operator onto the stack. The order of popping is the order in the output.
If the current input token is push it onto the stack.
If the current input token is ‘)’, pop off all operators and append them to the output string until a ‘(‘ is popped; discard the ‘(‘.
If the end of the input string is found, pop all operators and append them to the output string.
via Blogger https://ift.tt/3bYPaoy
0 notes
margdarsanme · 5 years ago
Text
NCERT Class 12 Computer Science Chapter 3 Lists Manipulation and Implementation
NCERT Class 12 Computer Science Python Solutions for Chapter 3 :: Lists Manipulation and Implementation
 TOPIC-1
Data StructuresShort Answer Type Questions (2 marks)
Question 1:Define a data structure.Answer:A data structure is a group of data which can be processed as a single unit. This group of data may be of similar or dissimilar data types. Data Structures are very useful while programming because they allow processing of the entire group of data as a single unit.
Question 2:Name the two types of data structures and give difference between them.Answer:Data structures are of two types: Linear and Non – Linear.
In a linear data structure, the elements are stored in a sequential order.
In a non linear data structure, no sequential order is followed.
Linear Data Structure Examples: Arrays: Non-Linear Data Structure Examples: Tree, graph lists, stacks, queues, linked lists.
Question 3:Give difference between an array and a list in Python.Answer:An array is defined as a set of contiguous data of similar data type. Python lists are actually arrays of variable length. The elements of a list are of eterogeneous types which means they are of different data types.
Question 4:How are lists implemented in memory?(or)How is memory allocated to a list in Python?Answer:A list in Python is an array that contains elements (pointers to objects) of a specific size only and this is a common feature of all dynamically typed languages. For implementation of a list, a contiguous array of references to other objects is used. Python keeps a pointer to this array and the array’s length is stored in a list head structure. This makes indexing of a list independent of the size of the list or the value of the index. When items are appended or inserted, the array of references is resized.
Question 5:What is sequential allocation of memory? Why do we say that lists are stored sequentially?Answer:A list is a allocated memory in sequential manner. This means that the elements of the list are stored in memory in sequence of their declaration. So, if you want to view the fifth element of the list, you have to first traverse through first four elements of the list. This is called sequential allocation of memory.
TOPIC-2Searching ListsShort Answer Type Questions-I (2 marks)
Question 1:How is linear search different from binary search?Answer:
Binary search requires the input data to be sorted near search doesn’t.
Binary search requires an ordering comparison; linear search only requires equality comparisons
Binary search has complexity 0(log n); linear search has complexity O(n) as discussed earlier.
Binary search requires random access to the data; linear search only requires sequential access (this can be very important – it means a linear search can stream data of arbitrary size).
Short Answer Type Questions-II (2 marks)
Question 1:Accept a list containing integers randomly. Accept any number and display the position at which the number is found in the list.Answer:maxrange = input(“Enter Count of numbers: ’’)marks=[]flag=Falsefor i in range(0, maxrange):marks. append(input(“ ?”))number = inputfEnter number to be searched”)for i in range(0, maxrange):if marks [i]==number:print number,“found at position”,iflag=Trueif flag==False:print number, “not found in list”
Question 2:What will be the status of the following list after the First, Second and Third pass of the slection sort method used for arranging the following elements in descending order?Note : Show the status of all the elements after each pass very clearly underlining the changes.12,14, -54,64,90,24Answer:
Question 3:For a given list of values in descending order, write a method in Python to search for a value with the help of Binary search method. The method should return position of the value and should return -1 if the value not present in the list.Answer:def binarysrch (nums, x):high=len (nums)low=0while low < high:mid=(low+high)/2midval=nums [mid]if midval > x:low = mid + 1elif midval < x:high = midelse:return midreturn -1
TOPIC-3List SortingShort Answer Type Questions-I (2 marks)
Question 1:What is bubble sort?Answer:Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements “bubble” to the top of the list. Because it only uses comparisons to operate on elements, it is also Called a comparison sort.
Question 2:Write an algorithm for selection sort.Answer:Selection sort performs the following steps:
Starting at index 0, search the entire array to find the next smallest or largest value.
Swap the smallest or largest value found with the value at index 0.
Repeat steps 1 & 2 starting from the next index.
Question 3:Explain insertion sort.Answer:Every repetition of insertion sort removes an element from the input data, inserting it into the correct position in the already-sorted list, until no input elements remain. The choice of which element to remove from the input is arbitrary and can be made using almost any choice algorithm.
Short Answer Type Questions-II (2 marks)
Question 1:Write a function that takes a list that is sorted in ascending order and a number as argument. The function should do the following:
Insert the number passed as argument in a sorted list.
Delete the number from the list.
Answer:from bisect import bisectdef listfunc(sortedlist,number) :insert_point = bisect (sortedlist, number)sortedlist.insert(insert_point,number)print “List after Insertion”print sortedlistsortedlist.remove(number)print “List after Deletion”print sortedlistmaxrange = inputfEnter Count of numbers: ”)numlist=[]flag=Falsefor i in range(0, maxrange):numlist.append(input(“ ?”))numlist.sort()number = inputfEnter the number”)listfunc(numlist,number)
Question 2:Consider the following list 95 79 19 43 52 3Write the passes of bubble sort sorting the list in ascending order till the 3rd iteration.Answer:[79,19, 43, 52, 3, 95]-Pass 1[19, 43,52,3,79, 95]-Pass 2[19,43,3, 52, 79, 95]-Pass 3
Question 3:Write a function that takes a sorted list and a number as an argument. Search for the number in the sorted list using binary search.Answer:def binary_search(SORTEDLIST, number):low=0high=len(SORTEDLIST)found=Falsewhile(low<high) and found==False:mid=(int) (low+high/2)if SORTEDLIST[mid]==number:print “Number found at”,midfound=Truebreakelif SORTEDLIST[mid]<number:low=mid+1else:high=mid-1if low >= high:print “Number not found”maxrange = inputfEnter Count of numbers: ”)numlist = []for i in range(0, maxrange):numlist.append(input(“?”))numlist.sort()print “Sorted list”,numlistnumber = inputfEnter the number”)binary_search(numlist,number)
Question 4:In the following list containing integers, sort the list using Insertion sort algorithm. Also show the status of the list after each iteration.15 -5 20 -10 10Answer:def insertion_sort(DATA_LIST):for K in range (1, len(DATA_LIST)):temp=DATA_LIST[K] # ptr=K-1,while(ptr>=0) and DATA_LIST[ptr]>temp:DATA_LIST[ptr+l]=DATA_LIST[ptr]ptr=ptr-1DATA_LIST [ptr+1] =tempprint DATA_LISTDATA_LIST = [15,-5,20,-10,10]print “LIST BEFOR SORTING”,DATAJ.ISTinsertion_sort(DATA_LIST)[-5,15, 20, -10,10][-5,15,20,-10,10]-Pass 1[-10,-5,15,20,10]-Pass 2[-10,-5,10,15, 20]-Pass 3
Question 5:What will be the status of the following after the First, Second and Third pass of the insertion sort method used for arranging the following elements in descending order ?Note: Show the status of all the elements after each pass very clearly underlining the changes.Answer:
Question 6:Consider the following unsorted list:99 78 25 48 51 11Sort the list using selection sort algorithm. Show the status of the list after every iteration.Answer:def selection_sort(DATA_LIST):for i in range(0, len (DATA_LIST)):min = ifor j in range(i + 1, len(DATA_LIST)):if DATA_LIST[j] < DATA_LIST[min]:min = j# swappingtemp= DATA_LIST[min]DATA_LIST[min] = DATA_LIST[i]DATA_LIST [i]=tempprint DATA_LISTDATA_LIST = [99 78 25 48 51 11]print “LIST BEFOR SORTING”,DATA_LISTselection_sort(DATA_LIST)
Question 7:Consider the following unsorted list Neena Meeta Geeta Reeta Seeta Sort the list using selection sort algorithm. Show the status of the list after every iteration.(or)Sort a list containing names of students in ascending order using selection sort.Answer:def selection_sort(DATA_LIST):for i in range(0, len (DATA_LIST)):min = ifor j in range(i + 1, len(DATA_LIST)):if DATA_LIST[j] < DATA_LIST[min]:min = j# swappingtemp= DATA_LIST[min]DATA_LIST[min] = DATA_LIST[i]DATA_LIST[i]=tempprint DATA_LISTNAME_LIST = [‘Neena’,’Beeta’,’Reeta’,’Geeta’,’Seeta’]print “LIST BEFORE SORTING”,NAME_LISTselection_sort(NAME_LIST)LIST BEFORE SORTING [‘Neena’,‘Beeta’,‘Reeta’, ‘Geeta’, ‘Seeta’][‘Beeta’, ‘Neena’, ‘Reeta’, ‘Geeta’, ‘Seeta’]-Pass 1[‘Beeta’, ‘Geeta’, ‘Reeta’, ‘Neena’, ‘Seeta’]-Pass 2[‘Beeta’, ‘Geeta’, ‘Neena’, ‘Reeta’, ‘Seeta’]-Pass 3[‘Beeta’, ‘Geeta’, ‘Neena’, ‘Reeta’, ‘Seeta’]-Pass 4[‘Beeta’, ‘Geeta’, ‘Neena’, ‘Reeta’, ‘Seeta’]-Pass 5
Question 8:A list contains rollno, name and marks of the student. Sort the list in descending order of marks using selection sort algorithm. [CBSE Text Book]Answer:def selection_sort(DATA_LIST):for i in range(0, len (DATA_LIST)):min = ifor j in range(i + 1, len(DATA_LIST)):if DATA_LIST[j][2] > DATA_LIST[min][2]:min = j# swappingDATA_LIST[min] [0] ,DATA_LIST[i] [0] = DATA_LIST[i] [0] ,DATA_LIST[mm] [0] DATA_LIST[min][l],DATA_LIST[i][l] = DATA_LI ST [i] [ 1 ],DATA_LI ST [min] [ 1 ] DATA_LIST[min] [2] ,DATA_LIST[i] [2] = DATA_LIST[i] [2],DATA_LIST[min] [2]print DATA_LISTmaxrange=input(“Enter Number of Students: ”)Students=[]for i in range(maxrange):Details=[]Details. append(input(“Enter roll_no”))Details.append(raw_input(“Enter name”))Details. append(inprft(“Enter marks”))Students.append(Details)print Studentsselection_sort(Students)
Question 9:What will be the status of the following list after the First. Second and Third pass of the insertion sort method used for arranging the following elements in descending order ?12,34,46, -34,90,23Note : Show the status of all the elements after each pass very clearly underlining the changes.Answer:output of diferent passes Pass One[12,34,46,-34,90,23], {}Pass Two[34, 46, -34, 90, 23} , {12}Pass ThreeLISTS MANIPULATION AND IMPLEMENTATION[46, -34, 90, 23} , {12, 34} Pass SixPass Four {23}, {-34,12, 34, 46, 90}[-34, 90, 23} , { 12, 34, 46} Pass SevenPass Five {} , {-34,12, 23, 34, 46, 90}{90,23} , {-34,12,34,46} It is the sorted list.
Long Answer Type Questions (4 marks)
Question 1:Consider the following unsorted list: 90 78 20 46 54 1 Write the list after:
3rd iteration of selection sort
4th iteration of bubble sort
5th iteration of insertion sort Ans. Working :
Answer:Working :
3rd iteration of selection sort: [1,20,46,78,54,90]
4th iteration of bubble sort: [1, 20, 46, 54, 90, 78]
5th iteration of insertion sort: [1, 20, 46, 54, 78, 90
Question 2:Consider the following unsorted list:10 5 55 13 3 49 36Write the position of elements in the list after:(i) 5th iteration of bubble sort(ü) 7th iteration of insertion sort(iii) 4th iteration of selection sortAnswer:Working :
5th iteration of bubble sort: [3, 5,10,13, 36, 55, 49]
Insertion sort doesn’t have the 7th iteration
4th iteration of selection sort: [3, 5,10,13, 55, 49, 36]
Question 3:Write a class CITY in Python with following– CName # String Value specifications :– Pop # Numeric value for Population instance attributes-KM # Numeric value– Ccode # Numeric value– Density #Numeric value for Population DensityMethods:– Dencal() #Method to calculate Density as Pop/KM– Record() #Method to allow user to enter values Ccode, CName, Pop, KM and call DenCal ( ) method– View() #Method to display all the members also display a message “Highly Populated City” if the Density is more than 10000.Answer:class CITY:def_init_(self): self.Ccode = 0self.CName = self. Pop = 0self.KM = 0 self.Density = 0def DenCal (self) :self.Density = self.Pop/self. KMdef Record (self)self Ccode=input (“Enter Ccode”)self.CName=raw_input (“Enter CName”)self.Pop=input (“Enter population”)self.KM=input (“Enter KM”)DenCal(self) //or self.DenCal()def View (self):print Ccode, CName, Pop, KM, Densityif self.Density > 10000:print (“Highly populated city”)# OR print (“Highly populated city”)
Question 4:A list contains Item_code, Item_name, qty and price. Sort the list :
In ascending order of qty using Bubble sort.
In descending order of price using Insertion sort.
Answer:def bubble_sort(DATA_LIST) :i = 0j = 0l = len(DATA_LIST)for i in range(l):print “Bubble Sort Iterations – Asc order of Quantity”for j in range(i+l,l):if DATA_LlST[i][3] > DATA_LIST[j][3]:# swappingDATA_LIST[i][0], DATA_LIST[j] [0]=DATA LIST[j] [0],DATA_LIST[i] [0]DATA_LIST[i][1], DATA_LIST[j][1]=DATA_ LIST[j][l],DATA_LIST[i][l]DATA_LIST[i] [2], DATA_LIST[j] [2]=DATA_ LIST[j][2],DATA_LIST[i][2]DATA_LIST[i][3], DATA_LIST[j][3]=DATA_ LIST[j][3] ,DATA_LIST[i] [3]print DATA_LISTdef insertion_sort(DATA_LIST):for K in range (1, len(DATA_LIST)):temp=DATA_LIST[K][2]ptr=K-1print “Insertion Sort Iterations – Desc order of price”while(ptr>=0) and DATA_LIST[ptr][2] < temp:DATA_LIST[ptr+1] [0]=DATA_LIST[ptr] [0]DATAJHST [ptr+1] [1]=DATA_LIST[ptr] [1]DATA_LIST[ptr+1][2]=DATA_LIST[ptr][2]DATA_LIST[ptr+1] [3]=DATA_LIST[ptr] [3]ptr=ptr-1DATA_LIST[ptr+1][2]=tempprint DATA_LISTmaxrange = input(“Enter Number of Items: “)Items=[]for i in range (maxrange):Details=[]Details. append(input(“Enter Item Code”))Details.append(raw_input(“Enter Item name”))Details.append(float(raw_input(“Enter price”)))Details.append(input(“Enter Quantity”)) Items. append(Details)print “BEFORE SORTING”,Items bubble_sort(Items)insertion_sort(Items)
TOPIC-4Stacks And Queues With ListsVery Short Answer Type Questions (1 mark)
Question 1:Expand the following:
LIFO
FIFO
Answer:
LIFO: Last-In First-Out
FIFO: First-In First-Out
Question 2:Define stack.Answer:A stack is a data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack; the only element that can be removed is the element that was at the top of the stack.
Question 3:Define Queue.Answer:Queue is a first-in, first-out (FIFO) data structure, i.e. the element added first to the queue will be the one to be removed first. Elements are always added to the rear of the queue and removed from the front of the queue.
Question 4:Write all the operations possible in data structure.Answer:The major operations are:
Traversal
Insertion
Deletion
Searching
Question 5:What are the two major queue operations?Answer:Addition of element is known as INSERT operation, also known as enqueuing. It is done using rear terminal position, i.e. tail end. Removal of element is known as DELETE operation, also known as dequeueing.
Short Answer Type Questions-I (2 marks)
Question 1:Write an algorithm to implement push operation.Answer:
Start
Initialize top with -1.
Input the new element.
Increment top by one.
stack[top]=new element
Print “Item Inserted”
Stop
Question 2:Write an algorithm to implement pop operation.Answer:
Start
If the value of top is -1 go to step 3 else go to step 4
Print “Stack Empty” and go to step 7
Deleted item = Stack[top]
Decrement top by 1
print “Item Deleted”
Stop
Question 3:Write an algorithm to implement insertion opera¬tion of queue.Answer:
Start
Check FRONT and REAR value,
if both the values are -1, then FRONT and REAR are incremented by 1
other wise Rear is incremented by one.
queue [Rear]=new element.
Stop
Question 4:Write an algorithm to implement deletion operation of queue.Answer:
Start
Check for underflow situation by checking value of Front=-1
If it is display appropriate message and stop
Otherwise Deleted item=queue [Front]
If Front=Rear then Front=Rear=-1 Otherwise Front is incremented by one
Print “Item Deleted”
Stop
Question 5:For a given list of values in ascending order, write a method in Python to search for a value with the help of Binary Search method. The method should return position of the value and should return -1 if the value not present in the list.Answer:def Binary Search (list, search):lower_bound=0upper_bond=len(list) -1found=falsepos=’x’while lower_bound< =upper_bond:middle_pos=(lower_bound + upper_bond)/2if list [middle_pos] = = search:pos=middlepos found=True breakelif search < list [middle_pos]:upper_bound=middle_pos-l else:lower_bound=middle_pos + 1 if found:print(“The item found”, pos) else:print (“The item not available”)return (-1)
Long Answer Type Questions (4 marks)
Question 1:Write Insert (city) and Delete (City) methods in Python to add City and Romave City considering them to act as Insert and Delete operations of the data structure Queue.Answer:class queue:city=[ ]def Insert (self):a = raw_input(“Enter city”)queue.city append (a)def Delete (self):if (queue, city = = []):print “Queue empty”else:print “Deleted element is”,queue.city[0]queue.city.delete ()ORclass queue:city=[ ]def Insert(self):a=raw_input(“Enter city”)queue.a.append(a)def Delete(self):if (queue.city==[ ]):print (“Queue emtpy”)elseprint (“Deleted element is”,queue, city [0])
Question 2:Define stack class in Python to operate on stack of numbers.Answer: class Stack:def_init_(self):self.s = [ ]def push(self):a = input(“Enter number”)self.s. append(a)def pop(self):self.s.pop()def display (self):l = len(self.s)for I in range(l-1,1,-1):print self.s[i]
Question 3:Write a function to push any student’s information to stack.Answer:def push(stack):s=[]print “STACK BEFORE PUSH” display(stack)s.append(input(“Enter student rollno?”))s.append(raw_input(“Enter student name”))s.append(raw_input(“Enter student grade”))stack, append(s)def display (stack):l=len(stack)print “STACK CONTENTS”for i in range(l-1,-1,-1):print stack[i]stack=[]print “Creating Stack”n = input(“Enter the number of students”)for i in range(n): student = []student.append(input(“Enter student rollno?”))student.append(raw_input(“Enter student name”))student.append(raw_input(“Enter student grade”))stack, append(student) push(stack)display(stack)
Question 4:Write the push operation of stack containing names using class.Answer:class stack:s=[]def push(self):a=r’aw_input(“Enter any name :”)stack.s.append(a)def display(self):l=len(stack.s) for i in range(l-1,-1,-1):print stack.s[i]a=stackOn= input(“Enter no. of names”)for i in range (n):a.push()a.display()
Question 5:Write Insert (Place) and Delete (Place) methods in Python to be add Place and Remove Place considering them to act as Insert and Delete operations of the data structure Queue.Answer:Class queue: place=[]def Insert (self):a=raw_input (“Enter city”)queue.place. append (a)def delete (self):if (queue.place = = []):print “Queue empty”else:print “Deleted element is”, queue, place [0]class queue :place = [ ]def Insert (self) 1a = rawjnput (“Enter place”) queue, a.append (a)def delete (self):if (queue.place==[ ] ):print (“Queue empty”)else:print (“Deleted element is” queue, place [0])queue.place.delete ( )
Question 6:Write the pop operation of stack containing names using class.Answer:class stack:s=[]def push (self):a=raw_input(“Enter any name :”)stack.s.append(a)def pop(self):if (a.s==D):print “Stack Empty”else:print “Deleted element is : ”,a.s.pop()def display (self):l=len(stack.s)print “STACK CONTENTS”for i in range(l-1,-1,-1):print stack.s[i]a=stack()n= input(“Enter no. of names”)for i in range(n):a.push()a.pop()a.display()
Question 7:Write the pop operation of stack containing num-bers using class.Answer:class stack:s=[]def push(self):a=input(“Enter number :”)stack.s.append(a)def pop(self):if (a.s==[]):print “Stack Empty”else:print “Deleted element is : ”,a.s.pop()def display(self):l=len(stack.s) print “STACK CONTENTS”for i in range(l-1,-1,-1):print stack.s[i]a=stack()n= input(“Enter count of numbers”)for i in range (n):a.push()a.pop()a. display ()
Question 8:Write a function to add any customer’s information to queue.Answer:def insert(queue): customer=[]print “QUEUE BEFORE INSERT” display(queue)customer.append(input(“Enter customer number?’’))customer.append(raw_input(“Enter customer name”))customer.append(input(“Enter customer phone number”))queue. append(customer)def display (queue):l=len(queue)fori in range(O.l): print queue[i]queue=[]print “Creating Queue”n=input(“Enter the number of customers”)for i in range(n):customer=[]customer. append(input(“Enter customer number?”))customer.append(rawjnput(“Enter customer name”))customer.append(input(“Enter customer phone number”))queue.append(customer)insert(queue)display(queue)
Question 9:Write the insertion operation of queue containing character using class.Answer:class queue:s=0def insert(self):a=raw_input(“Enter any letter:”)queue.s.append(a)def display (self):l=len(queue.s)print “QUEUE CONTENTS”for i in range(o,l):print queue. s[i]a=queue()n= input(“Enter no. of letters”)for i in range(n): a.insert()ch = raw_input(“Do you want to insert more letters”)if ch==‘y’:a.insert()a.display()
Question 10:Write Add(Fruit) and Remove (Fruit) methods in Python to insert name of a Fruit and to delete name of a Fruit considering them to act as Insert and Delete operations of the data structure Queue.Answer:def que insert (fruit, Rear) :ch=‘y’while ch==‘y’ or ch==‘yes’Frt=input(“Enter a fruit”)Rear=Rear + 1Fruit, append (Frt)print(“Do you wand to Add more”)ch=input ().upper ( )if ch==’N’ or ch==‘No’ :breakreturn reardef quedelete (Fruit, Rear):if not len (fruist):print f(“Fruit + list is empty”)else :Rear = Rear – 1Frt = Fruit.pop( )print(“Fruit is delete from list”)return Rear
Question 11:Write the deletion operation of queue containing characters using class.Answer:class queue:s=0def insert(self):a=raw_input(“Enter any letter:”)queue.s.append(a)def delete(self):if (a.s==[]):print “Queue Empty”else:print “Deleted element is: ”,queue.s[0]del queue.s[0]def display(self): l=len(queue.s)print “QUEUE CONTENTS”for i in range(0,l):print queue.s[i]a=queue()n= input(“Enter no. of letters”)for i in range (n):a.insert()a. delete()a. display ()
Question 12:Write the deletion operation of queue containing numbers using class.Answer:class queue:s=[]def insert(self):a=input(“Enter the number:”)queue.s.append(a)def delete(self):if (a.s==Q):print “Queue Empty”else:print “Deleted element is: ”,queue.s[0]del queue.s[0]def display(self):l=len(queue.s)print “QUEUE CONTENTS”for i in range(0,l):print queue.s[i]a=queue()n= input(“Enter no. of numbers”)for i in range(n):a.insert()a.delete()a.display()
TOPIC-5Applications of StacksVery Short Answer Type Questions (1 mark)
Question 1:Give one example of infix expression.Answer:A + B *C / D
Question 2:Give one example of postfix expression.Answer:ABC*D/+
Question 3:Give one example of prefix expression.Answer:+/*BCDA
Question 4:Convert (A+B)*C in to postfix form.Answer:AB+C*
Short Answer Type Questions-I (2 marks)
Question 1:Evaluate the following postfix notation of expressio,Show status of stack after every operation.12,2,7,34,20,-, +,5, +Answer:
Question 2:Evaluate the following postfix expression. Show the status of stack after execution of each operation separately: 2,13, + , 5, -,6,3,/,5,*,<Answer:Stack contentsResult: 0
Question 3:Evaluate using stack 10, 3,*, 30, 2,*,-Answer:
Question 4:Evaluate the following Postfix expression :20,10,-15,3,/, +, 5, *Answer:
Question 5:Convert A+ (B*C – (D / E A F) * G) * H into postfix form showing stack status after every step.Answer:
Question 6:Convert (True And False) OR (False And True) into postfix form using stack.Answer:
Question 7:What are the applications of queue in computer?Answer:In a single processor multitasking computer, job(s) wait to be processed form a queue. Same happens when we share a printer with many computers.
Compiling a HLL code.
Using download manager, for multiple files also uses queue for ordering the files.
In multiuser OS – job scheduling is done through queue.
Question 8:Evaluate the following postfix notation of expression. Show status of stack after every operation.Answer:Final Result = 1
Question 9:Evaluatethefollowingpostixnotationofexpression. Show status of stack after every operation.12,2, *, 24,20, -, +, 8, –Answer:
Question 10:Give few applications of stack.Answer:
Expression evaluation
Backtracking (game playing, finding paths, exhaustive searching).
Memory management, run-time environment for nested language features.
Short Answer Type Questions-II (2 marks)
Question 1:Write an algorithm to evaluate postfix expression.Answer:Step 1: StartStep 2: Check all symbols from left to right and repeat steps 3 & 4 for each symbol of expression ‘E’ until all symbols are over.
If the symbol is an operand, push it onto stack.
If the symbol is an operator then:
Pop the top two operands from stack and apply an operator in between them.
Evaluate the expression and place the result back on the stack.
Step 3: Set result equal to top element on the stack.Step 4: Stop
Question 2:Write an algorithm to convert infix to postfix.Answer:
Create an empty stack and an empty postfix output string/stream.
Scan the infix input string/stream left to right.
If the current input token is an operand, simply append it to the output string (note the examples above that the operands remain in the same order).
If the current input token is an operator, pop off all operators that have equal or higher precedence and append them to the output string; push the operator onto the stack. The order of popping is the order in the output.
If the current input token is push it onto the stack.
If the current input token is ‘)’, pop off all operators and append them to the output string until a ‘(‘ is popped; discard the ‘(‘.
If the end of the input string is found, pop all operators and append them to the output string.
from Blogger http://www.margdarsan.com/2020/09/ncert-class-12-computer-science-chapter_27.html
0 notes