如何为堆栈实现一些函数?

2024-06-16 10:13:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为堆栈实现这些函数:push(S)、isEmpty(S)、top(S)、nextToTop(S)。它说语法错误。如何测试

S= [1, 5, 13, 21]
def push(S):
    return S

def isEmpty(S):
    if S = []:
        print ("Empty String")
    else:
        print ("String is not empty")
def Top(S):
     if S = []:
         print ("Empty String")
    else:
        return S[0]

def nextToTop(S):
    if S = []:
        print ("String is not empty")
    else:
        return S[1]

print(push(S))
print(isEmpty(S))
print(Top(S))
print(nextToTop(S))

Tags: stringreturnifis堆栈topdefnot
1条回答
网友
1楼 · 发布于 2024-06-16 10:13:05

S = []是赋值运算符,其中as==conditional equal to运算符。因此,检查空列表的if条件应该类似于if S == []

同样的行为也可以通过简单的操作来实现:

if S:   # check if S is not empty
    print "list is not empty"  # S is list, not string
else:
    print "list is empty"

相关问题 更多 >