python学习之变位词和用数组实现栈、队列

python练习之变位词

from timeit import Timer


def anagram_solution(s1, s2):
    c1 = [0] * 26
    c2 = [0] * 26
    for i in range(len(s1)):
        pos = ord(s1[i]) - ord('a')
        c1[pos] += 1
    for j in range(len(s2)):
        pos = ord(s2[j]) - ord('a')
        c2[pos] += 1
    for i in range(26):
        if c1[i] == c2[i]:
            continue
        else:
            return False
    return True


t1 = Timer("anagram_solution('heldfglo', 'ellsdfgboh')", "from __main__ import anagram_solution")
print(t1.timeit(10000))

python练习之用数组实现栈

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

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

    def push(self, value):
        self.list.append(value)

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

    def size(self):
        return len(self.list)

    def isEmpty(self):
        return self.list == []

s = Stack()
s.push(8)
s.push(4)
s.push('a')
s.push(9)
print(s.size())
print(s.peek())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.size())

python练习之用数组实现队列

class Queue:
    def __init__(self):
        self.list = []

    def enqueue(self, item):
        self.list.insert(0, item)

    def dequeue(self):
        return self.list.pop()

    def isEmpty(self):
        return self.list == []

    def size(self):
        return len(self.list)

q = Queue()
q.enqueue('k')
q.enqueue('a')
q.enqueue('l')
q.enqueue('e')

print(q.isEmpty())
print(q.size())
print(q.dequeue())
print(q.dequeue())
print(q.size())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值