使用堆栈类检查括号("(",")","<",">")平衡 - 蟒蛇

时间:2017-01-25 01:50:12

标签: python python-3.x stack

我有这段代码来检查括号是否在字符串的一段文本中是平衡的。

def balanced_brackets(text):

    s = Stack()

    for character in text:
        if character == "(":
            s.push(character)
        elif character == ")":
            if s.is_empty():
                return False
            else:  
                s.pop()
        if character == "<":
            s.push(character)
        elif character == ">":
            if s.is_empty():
                return False
            else:
                s.pop()

    if s.is_empty():
        return True
    else:
        return False

对于以下测试:

print(balanced_brackets('(<x)>(())()'))
print(balanced_brackets('x<y)(>z'))
print(balanced_brackets('<(x)<y>)z'))

以下输出应全部打印

False 

但是他们打印

True 

出于某种原因。我需要帮助来确定这是为什么。谢谢。

1 个答案:

答案 0 :(得分:1)

我可能会这样做,使用字典来映射哪个右括号属于哪个左括号。这样,您可以将代码简化为仅一个<?php // start the session session_start(); require_once ('connect.php'); // if form is submitted if(isset($_POST['username']) and isset($_POST['password'])) { $username = $_POST['username']; $password = $_POST['password']; $query = "SELECT * FROM `users` WHERE username='$username' and password='$password'"; $result = mysqli_query($con, $query) or die(mysqli_error($con)); $count = mysqli_num_rows($result); // create session if values are equal if($count == 1) { $row = mysqli_fetch_assoc($result); // This gets the first (and only) result of your query. // save id as cookie $_COOKIE['ID'] = $row['id']; // Or whatever ID you have in your users table } else { header("Location: http://localhost/FolderName/index.php"); exit; } } // if user is logged in redirect if(isset($_COOKIE['ID'])) { header("Location: http://localhost/FolderName/home.php"); exit; } 块,而不是每个括号类型一个。您也可以轻松地在字典中添加更多括号。

if/elif