problem-solving-with-algorithms-and-data-structure-usingpython(使用python解决算法和数据结构) -- 基本数据结构(一)

1. 什么是线性数据结构?

栈,队列,deques, 列表是一类数据的容器,它们数据项之间的顺序由添加或删除的顺序决定。

一旦一个数据项被添加,它相对于前后元素一直保持该位置不变。

诸如此类的数据结构被称为线性数据结构。

2. 什么是栈?

栈(有时称为“后进先出栈”)是一个项的有序集合,其中添加移除新项总发生在同一端。

这一端通常称为“顶部”。与顶部对应的端称为“底部”。
实际应用:
每个 web 浏览器都有一个返回按钮。当你浏览网页时,这些网页被放置在一个栈中(实际是网页的网址)。

你现在查看的网页在顶部,你第一个查看的网页在底部。如果按‘返回’按钮,将按相反的顺序浏览刚才的页面。

Stack() 创建一个空的新栈。 它不需要参数,并返回一个空栈。

push(item)将一个新项添加到栈的顶部。它需要 item 做参数并不返回任何内容。

pop() 从栈中删除顶部项。它不需要参数并返回 item 。栈被修改。

peek() 从栈返回顶部项,但不会删除它。不需要参数。 不修改栈。

isEmpty() 测试栈是否为空。不需要参数,并返回布尔值。

size() 返回栈中的 item 数量。不需要参数,并返回一个整数。

栈的一些相关操作

3. python实现栈

class Stack:
    def __init__(self):
        self.items = []
    def isEmpty(self):
        return self.items == []
    def push(self, item):
        self.items.append(item)
    def pop(self):
        return self.items.pop()
    def peek(self):
        return self.items[-1]
    def size(self):
        return len(self.items)

s = Stack()
print(s.isEmpty())          # True
s.push(4)
s.push(‘dog‘)
print(s.peek())             # dog
s.push(True)
print(s.size())             # 3
print(s.isEmpty())          # False
s.push(8.4)
print(s.pop())              # 8.4
s.pop()
print(s.size())             # 2

4. 简单括号匹配

class Stack:
    def __init__(self):
        self.items = []
    def isEmpty(self):
        return self.items == []
    def push(self, item):
        self.items.append(item)
    def pop(self):
        return self.items.pop()
    def peek(self):
        return self.items[-1]
    def size(self):
        return len(self.items)

def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol == ‘(‘:
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced = False
            else:
                s.pop()
        index += 1
    return balanced and s.isEmpty()

print(parChecker(‘((())()())‘))
print(parChecker(‘()(((()(()())))‘))

5. 符号匹配  ()、[]、{}

class Stack:
    def __init__(self):
        self.items = []
    def isEmpty(self):
        return self.items == []
    def push(self, item):
        self.items.append(item)
    def pop(self):
        return self.items.pop()
    def peek(self):
        return self.items[-1]
    def size(self):
        return len(self.items)

def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol in ‘([{‘:
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced = False
            else:
                top = s.pop()
                if not ‘([{‘.index(top) == ‘)]}‘.index(symbol):
                    balanced = False
        index += 1
    return balanced and s.isEmpty()

print(parChecker(‘{({}){}([][])}‘))
print(parChecker(‘[{()]‘))

6. 十进制转换成二进制

class Stack:
    def __init__(self):
        self.items = []
    def isEmpty(self):
        return self.items == []
    def push(self, item):
        self.items.append(item)
    def pop(self):
        return self.items.pop()
    def peek(self):
        return self.items[-1]
    def size(self):
        return len(self.items)

def divideBy2(decNumber):
    remstack = Stack()
    while decNumber > 0:
        rem = decNumber % 2
        remstack.push(rem)
        decNumber = decNumber // 2
    binString = ‘‘
    while not remstack.isEmpty():
        binString = binString + str(remstack.pop())
    return binString
print(divideBy2(11))
print(divideBy2(42))

7. 十进制转换成任意进制

class Stack:
    def __init__(self):
        self.items = []
    def isEmpty(self):
        return self.items == []
    def push(self, item):
        self.items.append(item)
    def pop(self):
        return self.items.pop()
    def peek(self):
        return self.items[-1]
    def size(self):
        return len(self.items)

def divideBy2(decNumber,base):
    ‘‘‘
    十进制数转换成任意进制(16以下)
    :param decNumber: 十进制数
    :param base: 要转换成多少进制
    :return: 结果
    ‘‘‘
    digits = ‘0123456789ABCDEF‘         # 假如余数为13,则通过13索引找到D
    remstack = Stack()
    while decNumber > 0:
        rem = decNumber % base
        remstack.push(rem)
        decNumber = decNumber // base
    newString = ‘‘
    while not remstack.isEmpty():
        newString = newString + digits[remstack.pop()]
    return newString
print(divideBy2(11,8))
print(divideBy2(42,16))

原文地址:https://www.cnblogs.com/YD2018/p/9427890.html

时间: 2024-10-09 03:45:17

problem-solving-with-algorithms-and-data-structure-usingpython(使用python解决算法和数据结构) -- 基本数据结构(一)的相关文章

[Algorithms] Tree Data Structure in JavaScript

In a tree, nodes have a single parent node and may have many children nodes. They never have more than one parent nor point to any siblings. The most common tree structure you see is a web page. The underlying structure is often called the "DOM tree&

CDOJ 483 Data Structure Problem DFS

32‘20 Data Structure Problem Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/problem/show/483 Description Data structure is a fundamental course of Computer Science, so that each contestant is highly likely to solve this data s

Use the Right Algorithm and Data Structure

Use the Right Algorithm and Data Structure Jan Christiaan "JC" van Winkel A big bank with many branch offices complained that the new computers it had bought for the tellers were too slow. This was in the time before everyone used electronic ban

uva 11995 - I Can Guess the Data Structure!

题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=3146&mosmsg=Submission+received+with+ID+14262472 I Can Guess the Data Structure! There is a bag-like data structure, supporti

hdu-5929 Basic Data Structure(双端队列+模拟)

题目链接: Basic Data Structure Time Limit: 7000/3500 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 207    Accepted Submission(s): 41 Problem Description Mr. Frog learned a basic data structure recently, which is called

Leetcode: Add and Search Word - Data structure design

Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter

Add and Search Word - Data structure design

https://leetcode.com/problems/add-and-search-word-data-structure-design/ Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string co

HDU 4217 Data Structure?(线段树 or 树状数组啊)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4217 Problem Description Data structure is one of the basic skills for Computer Science students, which is a particular way of storing and organizing data in a computer so that it can be used efficiently

HDU 5929 Basic Data Structure 模拟

Basic Data Structure Time Limit: 7000/3500 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Problem Description Mr. Frog learned a basic data structure recently, which is called stack.There are some basic operations of stack: ? PUSH x: p

[LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计

Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter