mongona

mongona
-- --
正在获取天气

python使用list实现栈

# -*- coding: utf-8 -*-
"""
@author: sato
@file: stack.py
@time: 2019-08-22 00:06

"""


class Stack(object):

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

    def is_empty(self):
        return len(self.items) == 0

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

    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        raise IndexError('Stack is empty!')

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

    def peek(self):
        return self.items[len(self.items) - 1]


# s = Stack()
# print(s.is_empty())
# print(s.pop())


def reverse_str(mystr):
    # 反转字符串
    output = ''
    s = Stack()
    for m in mystr:
        s.push(m)
    while not s.is_empty():
        output += s.pop()
    # print(output)


def is_balanced(symbolstring):
    # 利用栈, 判断括号的平衡性
    s = Stack()
    balanced = True
    for i in symbolstring:
        # print(i)
        if i not in ')]}([{':
            continue
        if balanced:
            if i in '([{':
                s.push(i)
            else:
                if s.is_empty():
                    return False
                else:
                    # print(s.pop(), i)
                    if ')]}'.index(i) != '([{'.index(s.pop()):
                        return False
        else:
            return balanced
    return s.is_empty() and balanced


def Dec2Bin(decNumber):
    # 利用栈十进制转换为二进制
    s = Stack()

    while decNumber > 0:
        temp = decNumber % 2
        s.push(temp)
        decNumber = decNumber // 2
    binString = ''
    while not s.is_empty():
        binString += str(s.pop())
    print(binString)

# Dec2Bin(9)


# 利用栈实现多进制转换 十进制转换为多进制
def any_converter(decNumber, base):
    digits = '0123456789ABCDEF'

    s = Stack()

    while decNumber > 0:
        temp = decNumber % base
        s.push(temp)
        decNumber = decNumber // base

    new_string = ''
    while not s.is_empty():
        new_string += digits[s.pop()]
    print(new_string)

any_converter(15, 16)

 

2
0
Tags
富强,民主,文明,和谐,自由,平等,公正,法治,爱国,敬业,诚信,友善。
打赏二维码