In: Computer Science
STACK IMPLEMENTATION USING LIST:
# class to represent the stack using list
class Stack:
# constructor to initialize the
object
def __init__(self):
self.item_lst =
[]
# method to push an element into the
stack
def push(self, item):
self.item_lst.append(item)
# method to remove the top element from
the stack
def pop(self):
return
self.item_lst.pop()
# method to retrieve the top element of
the stack
def peek(self):
return
self.item_lst[len(self.item_lst)-1]
# method to find the size of the
stack
def size(self):
return
len(self.item_lst)
# method to find the emptiness of the
stack
def isEmpty(self):
return
self.item_lst == []
# testing
if __name__=='__main__':
# creating stack object
s=Stack()
# checking for empty
print(s.isEmpty())
# adding elements into the stack
s.push(44)
s.push(55)
s.push(60)
# displaying the size of the stack
print(s.size())
s.push(4.55)
# calling various functions of the
stack
print(s.pop())
print(s.size())
print(s.peek())
SCREENSHOT FOR CODING:
SCREENSHOT FOR OUTPUT:
-----------------
QUEUE IMPLEMENTATION USING LIST:
# class to represent the QUEUE using list
class Queue:
# constructor to initialize the object
def __init__(self):
self.item_lst = []
# method to add a element in the queue
def enqueue(self, i):
self.item_lst.insert(0,i)
# method to remove a element from the
queue
def dequeue(self):
return
self.item_lst.pop()
# method to find the size of the queue
def size(self):
return
len(self.item_lst)
# method to find the emptiness of the
queue
def isEmpty(self):
return self.item_lst ==
[]
# testing
if __name__=='__main__':
# creating queue object
q=Queue()
# adding elements to the queue
q.enqueue(47)
q.enqueue(52)
q.enqueue(62)
# displaying the size of the queue
print(q.size())
# removing the first element from the
queue
print(q.dequeue())
q.enqueue(50)
SCREENSHOT FOR CODING:
SCREENSHOT FOR OUTPUT:
-----------------------------
CODE FOR LETTER COUNT FUNCTION:
# function to count letters in a string
def count_letter(s):
# dictionary to store the letter count
d={}
# looping through every character in the
string
for c in s:
# changing to
lowercase
c=c.lower()
# adding the
character to the dictionary
if c not in d:
d[c]=1
else:
d[c]+=1
# returning the dictionary
return d
# testing
if __name__=='__main__':
print(count_letter('python'))
print(count_letter('Python ProgramMing'))
SCREENSHOT FOR CODING:
SCREENSHOT FOR OUTPUT: