《数据结构与算法分析python版》第三周编程作业

@[TOC]慕课《数据结构与算法分析python版》第三周编程作业

有效的括号

题目要求

《数据结构与算法分析python版》第三周编程作业_第1张图片

脚本

def isValid(s):
    dic = {
     '(': ')', '[': ']', '{': '}'} 
    stack = []  
    for i in s:
        if i in dic.keys():
            stack.append(i)  
        elif i in dic.values():
            if len(stack) == 0 or dic.get(stack[-1]) != i:  
                return False
            else:
                stack.pop()  
    if len(stack) == 0:
        return True
    else:
        return False



print(isValid(input()))

一维开心消消乐

题目要求:

《数据结构与算法分析python版》第三周编程作业_第2张图片

脚本


def xxl(s):
    stack = []
    for item in s:
        if not len(stack)== 0:  #栈非空执行
            if item == stack[-1]:              
                stack.pop()
            else:
                stack.append(item)
        else:
            stack.append(item)
    str_ = ""
    for i in stack:
         str_ = str_+ i
    return str_
print(xxl(input()))

强迫症老板和他的洗碗工

题目要求:

《数据结构与算法分析python版》第三周编程作业_第3张图片

脚本1

#模拟取盘子的过程
def laow(s):
    stack = []
    s = list(s)
    for i in range(10):
        stack.append(i)
        susp = False
        while not susp and len(stack) != 0:
            if stack[-1] ==int(s[0]):
                stack.pop()
                s.pop(0)
            else:
                susp = True

    if len(stack)==0:
        return "Yes"
    else:
        return "No"       
    
print(laow(input()))

脚本2

# 根据数字排列判断,下一个取得盘子要么比前一个大,要么只能比前一个小1
def laow(lst):
    lst = [int(i) for i in lst]
    for i in range(len(lst)):
        if i == 0:
            next
        elif lst[i] > lst[i-1]:
            next
        elif lst[i] < lst[i-1]:
            if lst[i-1] - lst[i] == 1:
                next
            else:
                return "No"
    return "Yes"

print(laow(input()))

你可能感兴趣的:(python,算法)