Categories:Viewed: 5 - Published at: a few seconds ago

Write a python program to implement Dequeue

class Dequeue:
    def __init__(self):
        self.items = []

    def is_empty(self):
        return self.items == []

    def append(self, data):
        self.items.append(data)

    def append_left(self, data):
        self.items.insert(0, data)

    def pop(self):
        return self.items.pop()

    def pop_left(self):
        return self.items.pop(0)


q = Dequeue()
print('Menu')
print('append <value>')
print('appendleft <value>')
print('pop')
print('popleft')
print('quit')

while True:
    do = input('What would you like to do? ').split()

    operation = do[0].strip().lower()
    if operation == 'append':
        q.append(int(do[1]))
    elif operation == 'appendleft':
        q.append_left(int(do[1]))
    elif operation == 'pop':
        if q.is_empty():
            print('Dequeue is empty.')
        else:
            print('Popped value from right: ', q.pop())
    elif operation == 'popleft':
        if q.is_empty():
            print('Dequeue is empty.')
        else:
            print('Popped value from left: ', q.pop_left())
    elif operation == 'quit':
        break

Write a python program to Check and print if string is palindrome using Stack

class Stack:
    def __init__(self):
        self.items = []

    def is_empty(self):
        return self.items == []

    def push(self, data):
        self.items.append(data)

    def pop(self):
        return self.items.pop()


s = Stack()
text = "ABA"

for character in text:
    s.push(character)

reversed_text = ''
while not s.is_empty():
    reversed_text = reversed_text + s.pop()

if text == reversed_text:
    print('The string is a palindrome.')
else:
    print('The string is not a palindrome.')

Write a python program to Check and print if Expression is Correctly Parenthesized using Stack

class Stack:
    def __init__(self):
        self.items = []

    def is_empty(self):
        return self.items == []

    def push(self, data):
        self.items.append(data)

    def pop(self):
        return self.items.pop()


s = Stack()
exp = "(x+y"

for c in exp:
    if c == '(':
        s.push(1)
    elif c == ')':
        if s.is_empty():
            is_balanced = False
            break
        s.pop()
else:
    if s.is_empty():
        is_balanced = True
    else:
        is_balanced = False

if is_balanced:
    print('Expression is correctly parenthesized.')
else:
    print('Expression is not correctly parenthesized.')

Write a python program to Implement Linear Search and print the key element if found

def linear_search(alist, key):
    """Return index of key in alist. Return -1 if key not present."""
    for i in range(len(alist)):
        if alist[i] == key:
            return i
    return -1


alist = [2, 3, 5, 6, 4, 5]

key = 6

index = linear_search(alist, key)
if index < 0:
    print(f'{key} was not found.')
else:
    print(f'{key} was found at index {index}.')