0% found this document useful (0 votes)
90 views12 pages

CSE203 - Assignment-2 - Colaboratory

The document contains 5 problems related to stacks and their solutions in Python. Problem 1 involves reversing a string using a stack and printing the unicode of each character. Problem 2 checks if a string of brackets is balanced. Problem 3 modifies a stack so the largest value is always on top. Problem 4 balances the sum of values in two stacks by adding to one. Problem 5 involves maintaining ascending order when adding new values to a stack.

Uploaded by

Ja Khushi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views12 pages

CSE203 - Assignment-2 - Colaboratory

The document contains 5 problems related to stacks and their solutions in Python. Problem 1 involves reversing a string using a stack and printing the unicode of each character. Problem 2 checks if a string of brackets is balanced. Problem 3 modifies a stack so the largest value is always on top. Problem 4 balances the sum of values in two stacks by adding to one. Problem 5 involves maintaining ascending order when adding new values to a stack.

Uploaded by

Ja Khushi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

3/2/23, 8:40 PM 2230851_assignment-2 - Colaboratory

Problem 1
Take a string from the user and print it in the reverse order using stack data structure. Also prints the unicode of each character.

1 class Stack:
2     def __init__(self):
3         self.items = []
4
5     def push(self, item):
6         self.items.append(item)
7
8     def pop(self):
9         return self.items.pop()
10
11     def is_empty(self):
12         return len(self.items) == 0
13
14
15 input_string = input("Enter a string: ")
16 stack = Stack()
17
18
19 if not input_string:
20     print("Input string is empty.")
21 else:
22     for char in input_string:
23         stack.push(char)
24     print("Reversed with Unicode:")
25     while not stack.is_empty():
26         char = stack.pop()
27         print(char, ord(char))
28

Enter a string: WATERMELON


Reversed with Unicode:
N 78
O 79
L 76
E 69
M 77
R 82
E 69
T 84
A 65
W 87

Problem 2
Given a string of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, print True on a new line; otherwise,
print False on

1 class Stack:
2     def __init__(self):
3         self.data = []
4     
5     def size(self):
6         return len(self.data)
7     
8     def is_empty(self):
9         return self.size() == 0
10     
11     def push(self, item):
12         self.data.append(item)
13     
14     def pop(self):
15         if self.is_empty():
16             print("Stack is empty")

https://colab.research.google.com/drive/17W3NmtTCZe_qbOueI4ourcF4NkRTQy5E?authuser=1#scrollTo=cEMvYotjsWeS&printMode=true 1/12
3/2/23, 8:40 PM 2230851_assignment-2 - Colaboratory
17         else:
18             return self.data.pop()
19     
20     def peek(self):
21         if self.is_empty():
22             print("Stack is empty")
23         else:
24             return self.data[-1]
25
26
27 def is_balanced(string):
28     stack = Stack()
29     for char in string:
30         if char in '([{':
31             stack.push(char)
32         elif char in ')]}':
33             if stack.is_empty():
34                 return False
35             else:
36                 top_char = stack.peek()
37                 if (char == ')' and top_char == '(') or \
38                    (char == ']' and top_char == '[') or \
39                    (char == '}' and top_char == '{'):
40                     stack.pop()
41                 else:
42                     return False
43     return stack.is_empty()
44
45
46 string = "()"
47 print(is_balanced(string))  
48
49 string = "{}"
50 print(is_balanced(string))  
51
52 string = "[]"
53 print(is_balanced(string))  
54
55 string = "{[]}"
56 print(is_balanced(string))  
57
58 string = "{([)]}"
59 print(is_balanced(string))  
60
61 string = "(()"
62 print(is_balanced(string))  
63
64 string = "{[(]}"
65 print(is balanced(string))  
True
True
True
True
False
False
False

Problem 3
Write a program keepLargestOnTop(stack) in a way that the largest value in that stack would be in the TOP position always. Return the stack.

1 class Stack():
2     def __init__(self):
3         self.data = []
4
5     def size(self):
6         return len(self.data)
7     

https://colab.research.google.com/drive/17W3NmtTCZe_qbOueI4ourcF4NkRTQy5E?authuser=1#scrollTo=cEMvYotjsWeS&printMode=true 2/12
3/2/23, 8:40 PM 2230851_assignment-2 - Colaboratory
8     def isempty(self):
9         if self.size() == 0:
10             return True
11         else:
12             return False
13         
14     def push(self, item):
15         self.data.append(item)
16
17     def pop(self):
18         if self.isempty():
19             print("Stack is empty")
20         else:
21             self.data.pop()
22         
23     def peek(self):
24         if self.isempty():
25             print("Stack is empty")
26         else:
27             return self.data[-1]
28         
29     def display(self):
30         if self.isempty():
31             print("Stack is empty")
32         else:
33             print(self.data[::-1])
34
35 def largest_on_top_stack(s):
36     helpingstack = Stack()
37     if s.isempty():
38         print("Stack is empty!!!")
39         return
40     max = s.peek()
41     while not s.isempty():
42         val = s.peek()
43         if val > max:
44             max = val
45         helpingstack.push(val)
46         s.pop()
47     while not helpingstack.isempty():
48         val = helpingstack.peek()
49         helpingstack.pop()
50         if max != val:
51             s.push(val)
52     s.push(max)
53     return s
54
55 arr = [23, 53, 56, 19, 44, 22, 99, 44]
56
57 stack = Stack()
58
59 for item in arr:
60     stack.push(item)
61 print("Current Stack: ")
62 stack.display()
63 print()
64 print("After your Program keepLargestOnTop(stack): Stack looks like below: ")
65 s = largest_on_top_stack(stack)
66 s.display()
67
Current Stack:
[44, 99, 22, 44, 19, 56, 53, 23]

After your Program keepLargestOnTop(stack): Stack looks like below:


[99, 44, 22, 44, 19, 56, 53, 23]

Problem 4
https://colab.research.google.com/drive/17W3NmtTCZe_qbOueI4ourcF4NkRTQy5E?authuser=1#scrollTo=cEMvYotjsWeS&printMode=true 3/12
3/2/23, 8:40 PM 2230851_assignment-2 - Colaboratory

Given two stacks with integer values, balance the sum of integer values present in each of the stack by adding a new element in any of the
stack.

1 class stack:
2   def __init__(self):
3     self.__element=list()
4
5   def size(self):
6     return len(self.__element) 
7
8   def isempty(self):
9     return len(self.__element) == 0
10
11   def pop(self):
12
13     if (len(self.__element) == 0) == True:
14       return  int("-inf")
15
16     else:
17       return self.__element.pop()
18
19
20
21   def push(self,val):
22     self.__element.append(val)
23
24   def peek(self):
25     return self.__element[-1]
26   
27
28 s1=stack()
29 s1.push(4)
30 s1.push(11)
31 s1.push(5)
32 s1.push(1)
33
34 s2=stack()
35 s2.push(-1)
36 s2.push(1)
37 s2.push(32)
38 s2.push(4)
39
40 ts1=stack()
41 ts2=stack() 
42
43 temp1=0
44 while  not s1.isempty():
45   x=s1.pop()
46   temp1=temp1+x
47   ts1.push(x)
48
49 temp2=0
50 while  not s2.isempty():
51   x=s2.pop()
52   temp2=temp2+x
53   ts2.push(x)
54
55 sum=abs(temp2-temp1)
56 if temp2>temp1:
57   ts1.push(sum)
58 else:
59   ts2.push(sum)
60
61 while not ts1.isempty():
62   s1.push(ts1.pop())
63
64

https://colab.research.google.com/drive/17W3NmtTCZe_qbOueI4ourcF4NkRTQy5E?authuser=1#scrollTo=cEMvYotjsWeS&printMode=true 4/12
3/2/23, 8:40 PM 2230851_assignment-2 - Colaboratory
65 while not ts2.isempty():
66   s2.push(ts2.pop())
67
68 print("stack A")
69 print()
70 while  not s1.isempty():
71   print(s1.pop())
72 print("  ")  
73
74
75 print("stack B")
76 print()
77 while  not s2.isempty():
78   print(s2.pop())
stack A

1
5
11
4
15

stack B

4
32
1
-1

Problem 5a
Now, you would need to insert a new value into this stack using a pushStack(value) function. Write the pushStack(value) utility function for the
stack class so that the function always maintains the ascending order in the stack.

1 class stack:
2   def __init__(self):
3     self.element=list()
4
5   def size(self):
6     return len(self.element) 
7
8   def isempty(self):
9     return len(self.element) == 0
10
11   def pop(self):
12
13     if (len(self.element) == 0) :
14       return   False
15
16     else:
17       return self.element.pop()
18
19
20
21   def push(self,val):
22     self.element.append(val)
23
24   def peek(self):
25     return self.element[-1]
26   def pushstack(self,val):
27     self.element.append(val)
28     
29
30     x=sorted(self.element)  
31     self.element=x
32     print(self.element)
33
34
35 s1=stack()
36 s1.push(44)
https://colab.research.google.com/drive/17W3NmtTCZe_qbOueI4ourcF4NkRTQy5E?authuser=1#scrollTo=cEMvYotjsWeS&printMode=true 5/12
3/2/23, 8:40 PM 2230851_assignment-2 - Colaboratory

37 s1.push(99)
38 s1.push(22)
39 s1.push(44)
40 s1.push(19)
41 s1.push(56)
42 s1.push(53)
43 s1.push(23)
44
45 s1.pushstack(12)
46 s1.pushstack(33)

[12, 19, 22, 23, 44, 44, 53, 56, 99]


[12, 19, 22, 23, 33, 44, 44, 53, 56, 99]

Problem 5B
Program a simple text editor using Stack . The user will input a complete sentence. You have to put this string into a character stack. When the
user selects the option to undo, a word from the stack will be deleted. By selecting undo again, another word from the stack will be removed
and so on. Hints: Create a stack for words.

1 class stack:
2     def __init__(self):
3         self.element = []
4
5     def size(self):
6         return len(self.element)
7
8     def isempty(self):
9         return len(self.element) == 0
10
11     def pop(self):
12         if self.isempty():
13             return False
14         else:
15             return self.element.pop()
16
17     def push(self, val):
18         self.element.append(val)
19
20     def peek(self):
21         return self.element[-1]
22
23 class TextEditor:
24     def __init__(self):
25         self.words = stack()
26     
27     def add_sentence(self, sentence):
28         for word in sentence.split():
29             self.words.push(word)
30     
31     def undo(self):
32         if self.words.isempty():
33             print("No words left!")
34             return
35
36         self.words.pop()
37     
38     def display(self):
39         if self.words.isempty():
40             print("No words left!")
41             return
42
43         hs = stack()
44
45         while not self.words.isempty():
46             hs.push(self.words.peek())
47             self.words.pop()    
https://colab.research.google.com/drive/17W3NmtTCZe_qbOueI4ourcF4NkRTQy5E?authuser=1#scrollTo=cEMvYotjsWeS&printMode=true 6/12
3/2/23, 8:40 PM 2230851_assignment-2 - Colaboratory
48         
49         while not hs.isempty():
50             val = hs.peek()
51             print(val, end=" ")
52             self.words.push(val)
53             hs.pop()
54         print()
55
56 te = TextEditor()
57 te.add_sentence("This is a sample sentence.")
58 te.add_sentence("I am testing the text editor program.")
59 te.display() 
60 te.undo()
61
62 te.display()
63 te.add_sentence("and it is working.")
64 te.display()
65
This is a sample sentence. I am testing the text editor program.
This is a sample sentence. I am testing the text editor
This is a sample sentence. I am testing the text editor and it is working.

Problem 6
Reverse the first ‘k’ elements of a queue, push it back into the queue. For example, if the queue has members 10, 20, 30, 40 , 50 , 60 , 70, 80, 90
and first 5 numbers are asked to be reversed then the result will be 60, 70, 80, 90, 50, 40, 30, 20, 10.

1 from collections import deque
2
3  
4
5 def aareverse_first_k(aaq, k):
6
7     aasolve(aaq, k)
8
9     s = len(aaq) - k
10
11     for _ in range(s):
12
13         x = aaq.popleft()
14
15         aaq.append(x)
16
17     for _ in range(s+1):
18
19         x = aaq.popleft()
20
21         aaq.append(x)
22
23     return aaq
24
25  
26
27 def aasolve(q, k):
28
29     if k == 0:
30
31         return
32
33     e = q.popleft()
34
35     aasolve(q, k - 1)
36
37     q.append(e)
38
39  

https://colab.research.google.com/drive/17W3NmtTCZe_qbOueI4ourcF4NkRTQy5E?authuser=1#scrollTo=cEMvYotjsWeS&printMode=true 7/12
3/2/23, 8:40 PM 2230851_assignment-2 - Colaboratory
40 aaqueue = deque([10, 20, 30, 40, 50, 60, 70, 80, 90])
41
42 k = 5
43
44 aaqueue = aareverse_first_k(aaqueue, k)
45
46 print(aaqueue)
deque([60, 70, 80, 90, 50, 40, 30, 20, 10])

Problem 7
You have two volunteers who are collecting donations from the members of a community. Suppose each of the members has a member id and
they are lined up in ascending order. To keep the number of people balanced, volunteer A is collecting donations from members whose ids are
divisible by 2 and volunteer B is collecting donations from members whose ids are not divisible by 2. Write a program which uses two queues,
such that if the even number member id is given, it will assign that member to volunteer A, otherwise, the member will go to volunteer B.

1 class queue:
2   def __init__(self):
3     self.__element=list()
4
5   def size(self):
6     return len(self.__element)
7
8   def isempty(self):
9     return len(self.__element) == 0
10
11   def dequeue(self):
12
13     if (len(self.__element) == 0) == True:
14
15       return  int("-inf")
16     else:
17       return self.__element.pop(0)
18
19   def enqueue(self,val):
20     self.__element.append(val)
21
22   def peek(self):
23     return self.__element[-1]
24
25
26
27 p1=queue()
28 p6=queue()
29
30 def enter(n):
31   if n%2==0:
32     p1.enqueue(n)
33   else:
34     p6.enqueue(n)  
35
36 enter (2)  
37 enter (4) 
38 enter (7) 
39 enter (10) 
40 enter (1) 
41 enter (9) 
42 enter (11) 
43
44 while p1.isempty() == False:
45   print(p1.dequeue(),end=" ")
46
47 print()  
48 while p6.isempty() == False:
49   print(p6.dequeue(),end= " ")  

https://colab.research.google.com/drive/17W3NmtTCZe_qbOueI4ourcF4NkRTQy5E?authuser=1#scrollTo=cEMvYotjsWeS&printMode=true 8/12
3/2/23, 8:40 PM 2230851_assignment-2 - Colaboratory

2 4 10
7 1 9 11

Problem 8
Given a number n, write a function that generates and prints all binary numbers with decimal values from 1 to n. You need to use a queue for
that

1 class Queue:
2     def __init__(self):
3         self.__elements = []
4
5     def size(self):
6         return len(self.__elements)
7
8     def is_empty(self):
9         return len(self.__elements) == 0
10
11     def dequeue(self):
12         if self.is_empty():
13             raise IndexError("dequeue from empty queue")
14         else:
15             return self.__elements.pop(0)
16
17     def enqueue(self, val):
18         self.__elements.append(val)
19
20     def peek(self):
21         return self.__elements[-1]
22
23 n=int(input("Enter a positive integer: ")   )  
24 if  n>=0:
25   q1=queue()
26   q1.enqueue("1")
27   i=0
28   while i<n:
29     
30     x=q1.dequeue()
31     q1.enqueue( x + "0")
32     q1.enqueue( x + "1")
33     print(x)
34     i=i+1
35 else:
36     print("Invalid input: please enter a positive integer.") 

Enter a positive integer: 5


1
10
11
100
101

Problem 9
Create a myQueue class and all of it’s functions (enqueue, dequeue, isEmpty, peek, size). You can use only two stacks (two objects from your
stack class) inside the myQueue class to hold the data. That means, you cannot use any list or double ended queue to hold data.

1 class myQueue:
2     def __init__(self):
3         self.stack1 = []
4         self.stack2 = []
5
6     def enqueue(self, item):
7         self.stack1.append(item)
8
9     def dequeue(self):
10         if not self.stack2:
https://colab.research.google.com/drive/17W3NmtTCZe_qbOueI4ourcF4NkRTQy5E?authuser=1#scrollTo=cEMvYotjsWeS&printMode=true 9/12
3/2/23, 8:40 PM 2230851_assignment-2 - Colaboratory
11             while self.stack1:
12                 self.stack2.append(self.stack1.pop())
13         if not self.stack2:
14             raise Exception("Queue is empty")
15         return self.stack2.pop()
16
17     def isEmpty(self):
18         return not (self.stack1 or self.stack2)
19
20     def peek(self):
21         if not self.stack2:
22             while self.stack1:
23                 self.stack2.append(self.stack1.pop())
24         if not self.stack2:
25             raise Exception("Queue is empty")
26         return self.stack2[-1]
27
28     def size(self):
29         return len(self.stack1) + len(self.stack2)
30
31
32
33 q = myQueue()
34 print(q.isEmpty()) 
35 q.enqueue(1)
36 q.enqueue(2)
37 q.enqueue(3)
38 print(q.size()) 
39 print(q.peek())  
40 print(q.dequeue())  
41 print(q.dequeue())  
42 print(q.peek())  
43 q.enqueue(4)
44 print(q.size()) 
45 print(q.isEmpty()) 
46 print(q.dequeue()) 
47 print(q.dequeue())  
48 try:
49     q.dequeue()
50 except Exception as e:
51     print(e) 
True
3
1
1
2
3
2
False
3
4
Queue is empty

Problem 10
Create a myStack class and all of it’s functions (push, pop, isEmpty, peek, size). You can use only two queues (two objects from your queue
class) inside the myStack class to hold the data. That means, you cannot use any list to hold data.

1 class Queue:
2     def __init__(self):
3         self.__elements = []
4
5     def enqueue(self, val):
6         self.__elements.append(val)
7
8     def dequeue(self):
9         if self.is_empty():
10             raise IndexError("dequeue from empty queue")

https://colab.research.google.com/drive/17W3NmtTCZe_qbOueI4ourcF4NkRTQy5E?authuser=1#scrollTo=cEMvYotjsWeS&printMode=true 10/12
3/2/23, 8:40 PM 2230851_assignment-2 - Colaboratory
11         else:
12             return self.__elements.pop(0)
13
14     def is_empty(self):
15         return len(self.__elements) == 0
16
17     def peek(self):
18         if self.is_empty():
19             raise IndexError("peek from empty queue")
20         else:
21             return self.__elements[0]
22
23     def size(self):
24         return len(self.__elements)
25
26
27 class myStack:
28     def __init__(self):
29         self.q1 = Queue()
30         self.q2 = Queue()
31
32     def push(self, val):
33         self.q1.enqueue(val)
34
35     def pop(self):
36         if self.q1.is_empty() and self.q2.is_empty():
37             raise IndexError("pop from empty stack")
38         while self.q1.size() > 1:
39             self.q2.enqueue(self.q1.dequeue())
40         result = self.q1.peek()
41         self.q1, self.q2 = self.q2, self.q1
42         return result
43
44     def is_empty(self):
45         return self.q1.is_empty() and self.q2.is_empty()
46
47     def peek(self):
48         if self.q1.is_empty() and self.q2.is_empty():
49             raise IndexError("peek from empty stack")
50         while self.q1.size() > 1:
51             self.q2.enqueue(self.q1.dequeue())
52         result = self.q1.peek()
53         self.q2.enqueue(self.q1.peek())
54         self.q1, self.q2 = self.q2, self.q1
55         return result
56
57     def size(self):
58         return self.q1.size() + self.q2.size()
59
60
61 q = myStack()
62 print(q.is_empty()) 
63 q.push(1)
64 q.push(2)
65 q.push(3)
66 print(q.size()) 
67 print(q.peek())  
68 print(q.pop())  
69 print(q.pop())  
70 print(q.peek())  
71 q.push(4)
72 print(q.size()) 
73 print(q.is_empty()) 
74 print(q.pop()) 
75 print(q.pop())  
76
77

https://colab.research.google.com/drive/17W3NmtTCZe_qbOueI4ourcF4NkRTQy5E?authuser=1#scrollTo=cEMvYotjsWeS&printMode=true 11/12
3/2/23, 8:40 PM 2230851_assignment-2 - Colaboratory

True
3
3
3
2
1
6
False
4
1

1 def dailyTemperatures(temperatures):
2     stack = []
3     ans = [0] * len(temperatures)
4     for i in range(len(temperatures)-1, -1, -1):
5         while stack and temperatures[stack[-1]] <= temperatures[i]:
6             stack.pop()
7         if stack:
8             ans[i] = stack[-1] - i
9         stack.append(i)
10     return ans
11
12 temperatures = [73,74,75,71,69,72,76,73]
13 print(dailyTemperatures(temperatures)) 
14
15
16 temperatures = [30,40,50,60]
17 print(dailyTemperatures(temperatures)) 
18

[1, 1, 4, 2, 1, 1, 0, 0]
[1, 1, 1, 0]

check 0s completed at 8:39 PM

https://colab.research.google.com/drive/17W3NmtTCZe_qbOueI4ourcF4NkRTQy5E?authuser=1#scrollTo=cEMvYotjsWeS&printMode=true 12/12

You might also like