Ammar Python Assignment

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067

ENROLLMENT NO = 18021180065

PYTHON ASSIGNMENT
LIST AND LINKED LIST

1. Consider a list (list = []).


You can perform the following commands:
• insert i e: Insert integer at position .
• print: Print the list.
• remove e: Delete the first occurrence of integer .
• append e: Insert integer at the end of the list.
• sort: Sort the list.
• pop: Pop the last element from the list.
• reverse: Reverse the list.
Initialize your list and read in the value of followed by lines of commands
where each command will be of the types listed above. Iterate through
each command in order and perform the corresponding operation on
your list.

CODE:

l=[3,2,1,4]
l.insert(1,6)
print(l)
l.remove(6)
print(l)
l.append(6)
print(l)
l.sort()
print(l)
l.pop()
print(l)
l.reverse()
print(l)
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

2. Implement a linked list and perform the following operation on


linkedlist.
1. Append the value at end
2. Append the value in starting position
3. Insert the element in between at a specified position
4. Delete first node
5. Remove the the element at a specified position
6. Display the linkedlist

CODE:
class Node:
def __init__(self,data):
self.data=data
self.next=None

class LinkedList:
def __init__(self):
self.start=None

def insert_at_beg(self,value):
newNode = Node(value)
temp= self.start
self.start = newNode
self.start.next = temp

def insert_at_last(self,value):
newNode = Node(value)
if(self.start == None):
self.start = newNode
else:
temp = self.start
while(temp.next!=None):
temp = temp.next
temp.next= newNode

def insert_after_node(self,prev_node,data):
newNode = Node(data)

if(not prev_node):
print("Node not found")
else:
temp = prev_node.next
prev_node.next = newNode
newNode.next = temp
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

def delete_at_first(self):
if(self.start == None):
print("Linked List is empty")
else:

self.start = self.start.next

def delete_at_last(self):
if(self.start == None):
print("List is empty")
else:
temp= self.start
while(temp.next.next!=None):
temp= temp.next
temp.next= None

def viewList(self):
if(self.start==None):
print("List is empty")
else:
temp = self.start
while(temp!=None):
print(temp.data,end=" ")
temp = temp.next
def len_list_iterative(self):
temp = self.start
count = 0
while(temp!=None):
count = count+1
temp = temp.next
return count

def len_recursive(self,node):
if node is None:
return 0
return 1+ self.len_recursive(node.next)

def node_swap(self,key1,key2):
if(key1 == key2):
return
else:
temp = self.start
prev1 =None
prev2 = None

while(temp.next!= None):
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

if(temp.next.data == key1):
prev1 = temp
elif(temp.next.data == key2):
prev2 = temp
temp = temp.next

if(prev1!=None and prev2!=None):


store = prev1.next
prev1.next = prev2.next
prev2.next = store

link = prev1.next.next
prev1.next.next = prev2.next.next
prev2.next.next = link

linked_list = LinkedList()
linked_list.insert_at_last(8)
linked_list.insert_at_last(10)
linked_list.insert_at_last(12)
linked_list.insert_at_last(13)

linked_list.viewList()
linked_list.delete_at_first()
print("\n")
linked_list.viewList()
print("\n")
linked_list.insert_at_beg(15)
linked_list.insert_at_beg(20)
linked_list.viewList()
print("\n")
print("\n")
prev_node = linked_list.start.next
linked_list.insert_after_node(prev_node,7)
linked_list.viewList()
print("\n")
print(linked_list.len_list_iterative())
print(linked_list.len_recursive(linked_list.start))
linked_list.node_swap(15,12)
linked_list.viewList()
linked_list.delete_at_last()
print("\n")
linked_list.viewList()
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

3. A teacher has given a project assignment to a class of 10 students. She


wants to store the marks (out of 100 ) scored by each student.
The marks scored are as mentioned below: 89,78,99,76,77,67,99,98,90
Write a python program to store the marks in a list and perform the
following:
1. The teacher forgot to include the marks of one student. Insert 78 at
index position, 8 and display the marks of all 10 students.
2. The teacher also wants to know the marks scored by students
represented by index positions, 5 and 7.
Identify and display the two marks.

CODE:
marks=[89,78,99,76,77,67,99,98,90]
marks.insert(8,78)
print(marks)
print(marks[5])
print(marks[7])
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

4.Given two lists, both having String elements, write a python program
using python lists to create a new string as per the rule given below: The
first element in list1 should be merged with last element in list2, second
element in list1 should be merged with second last element in list2 and
so on. If an element in list1/list2 is None, then the corresponding
element in the other list should be kept as it is in the merged list.
Sample Inputlist1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']
Expected Output : “An apple a day keeps the doctor away”

CODE:
list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']
for i in range(len(list1)):
if(list1[i]==None):
list1[i]=''
for i in range(len(list2)):
if(list2[i]==None):
list2[i]=''
st=''
for i in range(len(list1)):
st+=list1[i]+list2[::-1][i]+' '

print(st)

5.
Given two lists, both having integer elements, write a python program
using python lists to create and return a new list as per the rule given
below: If the double of an element in list1 is present in list2, then add it
to the new list. Sample Input list1 - [11, 8,23,7,25, 15] list2 – [6, 33,
50,31, 46, 78, 16,34] Expected Output : new_list – [8,23,25]

CODE:
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

list1 = [11, 8,23,7,25, 15]


list2 = [6, 33, 50,31, 46, 78, 16,34]
new_list=[]
for i in list1:
if(i*2 in list2):
new_list.append(i)
print(new_list)

7. Given a linked list containing whole numbers, write a


python function which finds and returns the sum of all the
elements at the odd position in the given linked list.

Source Code:
import math
class Node:
def __init__(self, data):
self.data = data
self.next = None

def sum_node(head):
count = 0
sum = 0
while (head != None):
if (count % 2 == 0):
sum = sum + head.data
count = count + 1
head = head.next
return sum

def push(head_ref, new_data):


NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

new_node = Node(new_data)
new_node.data = new_data
new_node.next = head_ref
head_ref = new_node
return head_ref

if __name__=='__main__':
head = None
head = push(head, 11)
head = push(head, 21)
head = push(head, 31)
head = push(head, 41)
head = push(head, 51)
print(sum_node(head))
output:-

8. Write a python program to find the maximum value in a


linked list and replace it with a given value. Assume that the
linked list is populated with whole numbers and there is only
one maximum value in the linked list.
Source Code:
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LL:
def __init__(self):
self.head = None
def insert(self, data):
if self.head == None:
self.head = Node(data)
else:
p = Node(data)
p.next = self.head
self.head = p

def replace_max(self, k):


cnt = 0
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

p = self.head
q = None
max = -1
while p!=None:
if p.data>max:
max = p.data
q=p
p = p.next
q.data = k
def display(self):
p = self.head
while p!=None:
print(p.data)
p = p.next

l = LL()
l.insert(10)
l.insert(20)
l.insert(30)
l.insert(100)
l.insert(50)
l.insert(60)
print("Old List")
l.display()
l.replace_max(23)
print("\nNew List")
l.display()
output:-
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

Q.10 Write a python program to remove all duplicate elements from a sorted linked
list containing integer data. Use the LinkedList class and methods in it to implement
the above program. Example: Input LinkedList: 10 10 20 20 30 30 30 40 50 Output
LinkedList: 10 20 30 40 50

CODE:-

class Node:
def _init_(self, data):
self.data = data
self.next = None

class LinkedList:
def _init_(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def get_prev_node(self, ref_node):


current = self.head
while (current and current.next != ref_node):
current = current.next
return current

def remove(self, node):


prev_node = self.get_prev_node(node)
if prev_node is None:
self.head = self.head.next
else:
prev_node.next = node.next

def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next

def remove_duplicates(llist):
current1 = llist.head
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

while current1:
data = current1.data
current2 = current1.next
while current2:
if current2.data == data:
llist.remove(current2)
current2 = current2.next
current1 = current1.next

a_llist = LinkedList()

data_list = input().split()
for data in data_list:
a_llist.append(int(data))

remove_duplicates(a_llist)
a_llist.display()

OUTPUT:-

STACK AND QUEUE

Q1. Implement stack using list


NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

SOURCE CODE:-
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
print('\nElements poped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())

print('\nStack after elements are poped:')


OUTPUT:-
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

Q2. Implement stack using class having basic


attributes and methods of stack like. top
variable, push method, pop method, display
method.
SOURCE CODE:-
class Stack:
def __init__(self):
self.items = []
defis_empty(self):
returnself.items == []
def push(self, data):
self.items.append(data)
def pop(self):
returnself.items.pop()
def display(self):
print(*self.items[::-1])
def top(self):
print(self.items[len(self.items)-1])
s = Stack()
print('push <value>')
print('pop')
print('quit')
print('disp')
print('top')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'push':
s.push(int(do[1]))
elif operation == 'pop':
ifs.is_empty():
print('Stack is empty.')
else:
print('Popped value: ', s.pop())
elif operation == 'disp':
s.display();
elif operation == 'top':
s.top();
elif operation == 'quit':
break
OUTPUT:
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

Q3. Given a stack of integers, write a program


which calculates the average of all the
elements in the stack and push it to the stack.
The given input stack should be left
unchanged except for the average pushed to it
as the top most element.
SOURCE CODE:-
class Stack:
def __init__(self):
self.items = []
defis_empty(self):
returnself.items == []
def push(self, data):
data=(data+sum(self.items))/(len(self.items)+1)
data=round(data, 2)
self.items.append(data)
def pop(self):
returnself.items.pop()
def display(self):
print(*self.items[::-1])
s = Stack()
print('push <value>')
print('disp')
print('quit')
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'push':
s.push(int(do[1]))
elif operation == 'pop':
ifs.is_empty():
print('Stack is empty.')
else:
print('Popped value: ', s.pop())
elif operation == 'disp':
s.display();
elif operation == 'quit':
break
OUTPUT:-
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

Q4. Write a python function which accepts


a stack of integers, sorts it in ascending
order and returns the sorted stack.
Sample Input Stack:top->bottom (9,3,56,6,2,7,4)
Expected Output: Stack(2,3,4,6,7,9,56)
SOURCE CODE:-
def sortStack ( stack ):
tmpStack = createStack()
while(isEmpty(stack) == False):
tmp = top(stack)
pop(stack)
while(isEmpty(tmpStack) == False and
int(top(tmpStack)) < int(tmp)):
push(stack,top(tmpStack))
pop(tmpStack)
push(tmpStack,tmp)
return tmpStack
def createStack():
stack = []
return stack
def isEmpty( stack ):
return len(stack) == 0
def push( stack, item ):
stack.append( item )
def top( stack ):
p = len(stack)
return stack[p-1]
def pop( stack ):
if(isEmpty( stack )):
print("Stack Underflow ")
exit(1)
return stack.pop()
def prints(stack):
for i in range(len(stack)-1, -1, -1):
print(stack[i], end = ' ')
print()
stack = createStack()
push( stack, str(9) )
push( stack, str(3) )
push( stack, str(56) )
push( stack, str(6) )
push( stack, str(2) )
push( stack, str(7) )
push( stack, str(4) )
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

print("Sorted numbers are: ")


sortedst = sortStack ( stack )
prints(sortedst)
OUTPUT:-
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

5. Implement queue using list


SOURCE CODE:-
class Node:

def __init__(self, data):


self.data = data
self.next = None
class Queue:

def __init__(self):
self.front = self.rear = None

def isEmpty(self):
return self.front == None
def EnQueue(self, item):
temp = Node(item)

if self.rear == None:
self.front = self.rear = temp
return
self.rear.next = temp
self.rear = temp

def DeQueue(self):

if self.isEmpty():
return
temp = self.front
self.front = temp.next

if(self.front == None):
self.rear = None
if __name__== '__main__':
q = Queue()
q.EnQueue(10)
q.EnQueue(20)
q.DeQueue()
q.DeQueue()
q.EnQueue(30)
q.EnQueue(40)
q.EnQueue(50)
q.DeQueue()
print("Queue Front " + str(q.front.data))
print("Queue Rear " + str(q.rear.data))
OUTPUT:-
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

Q6. Implement queue using 2 stacks


SOURCE CODE:-
class Queue:
def __init__(self):
self.s1 = []
self.s2 = []

def enQueue(self, x):


while len(self.s1) != 0:
self.s2.append(self.s1[-1])
self.s1.pop()
self.s1.append(x)
while len(self.s2) != 0:
self.s1.append(self.s2[-1])
self.s2.pop()
def deQueue(self):
if len(self.s1) == 0:
print("Q is Empty")
x = self.s1[-1]
self.s1.pop()
return x
if __name__ == '__main__':
q = Queue()
q.enQueue(1)
q.enQueue(2)
q.enQueue(3)

print(q.deQueue())
print(q.deQueue())
print(q.deQueue())

OUTPUT:-
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

7. Implement stack using 2 queues


SOURCE CODE:-
from queue import Queue
class Stack:
def __init__(self):
self.q1 = Queue()
self.q2 = Queue()
self.curr_size = 0

def push(self, x):


self.curr_size += 1
self.q2.put(x)
while (not self.q1.empty()):
self.q2.put(self.q1.queue[0])
self.q1.get()
self.q = self.q1
self.q1 = self.q2
self.q2 = self.q

def pop(self):
if (self.q1.empty()):
return
self.q1.get()
self.curr_size -= 1

def top(self):
if (self.q1.empty()):
return -1
return self.q1.queue[0]

def size(self):
return self.curr_size
if __name__ == '__main__':
s = Stack()
s.push(1)
s.push(2)
s.push(3)
s.push(4)

print("current size: ", s.size())


print(s.top())
s.pop()
print(s.top())
s.pop()
print(s.top())

print("current size: ", s.size())


NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

OUTPUT:-
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

Q8. In a sequence of characters, a letter means en-


queue and an asterisk means de-queue. Write a
python function which accepts the given sequence
and returns the string obtained by de-queuing.
Sample Input 1 I*TS** A
**BE***AUT**IF**UL** D**AY***
Expected Output ITS A BEAUTIFUL DAY
Sample Input 2 : E*NE**M*Y S***HI**P*S*
O**N T***H*E W***AY**
Expected Output : ENEMY SHIPS ON THE WAY
Source code:-
def input_s(str_statement):
new_str_statement = []
for i in str_statement:
if i != "*":
new_str_statement.append(i)
new_str_state = ""
for i in new_str_statement:
new_str_state += i
print(new_str_state)
# return ''.join(new_str_statement)

input_s("I*TS** A **BE***AUT**IF**UL** D**AY***")


input_s("E*NE**M*Y S***HI**P*S* O**N T***H*E W***AY**")
output:-
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

Q9. Given n processes with their burst times, the


task is to find average waiting time and average
turn around time using FCFS scheduling algorithm.
Assuming arrival time of each process is 0.
Input : n = 3
Process no : 1 2 3
Burst Time: 10 5 8
Output : Av. Waiting time : 8.33
Av Turn around time : 16
SOURCE CODE:-
def findWaitingTime(processes, n, bt, wt, at):
service_time = [0] * n
service_time[0] = 0
wt[0] = 0
for i in range(1, n):
service_time[i] = (service_time[i - 1] +bt[i - 1])
wt[i] = service_time[i] - at[i]
if (wt[i] < 0):
wt[i] = 0
def findTurnAroundTime(processes, n, bt, wt, tat):
for i in range(n):
tat[i] = bt[i] + wt[i]
def findavgTime(processes, n, bt, at):
wt = [0] * n
tat = [0] * n
findWaitingTime(processes, n, bt, wt, at)
findTurnAroundTime(processes, n, bt, wt, tat)
print("Processes Burst Time Arrival Time Waiting", "Time Turn-Around Time
Completion Time \n")
total_wt = 0
total_tat = 0
for i in range(n):

total_wt = total_wt + wt[i]


total_tat = total_tat + tat[i]
compl_time = tat[i] + at[i]
print(" ", i + 1, "\t\t", bt[i], "\t\t", at[i], "\t\t", wt[i], "\t\t ", tat[i], "\t\t ",
compl_time)

print("Average waiting time = %.5f "%(total_wt /n))


print("\nAverage turn around time = ", total_tat / n)
if __name__ =="__main__":
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

processes = [1, 2, 3]
n=3
burst_time = [10, 5,8]
arrival_time = [0, 0,0
]
findavgTime(processes, n, burst_time,arrival_time)
OUTPUT:-

Q10.Write a Python program to create a LIFO


queue.
SOURCE CODE:-
import queue
q = queue.LifoQueue()
for x in range(4):
q.put(str(x))
while not q.empty():
print(q.get(), end=" ")
print()
OUTPUT:-
NAME = AMMAR AHSAN ADMISSION NO = 18SCSE1180067
ENROLLMENT NO = 18021180065

You might also like