Learning Python Record: matching brackets detect problems

Python learning record: matching brackets detect problems

 

A problem description

In practice Python when the program question, I met paired brackets detection problem.

Problem Description: prompt the user to enter his string, which may include the parentheses () , check whether parentheses are correctly paired, the pairing is successful or not are output:

 

The pairing is successful!

Pairing failed!

 

Wherein paired parentheses to consider matching sequence, i.e., () indicates pairing ) ( not paired, pairing only consider parentheses.

 

Mention parentheses matching, we might think of C symbol priority issues language regular expressions calculated in the C language we usually use the stack to solve, but in Python , we can also use the ideas and methods of the stack, in a list form to achieve it. The list as a stack to use, but the establishment or list object that provides a list type function method.

 

 

Two , Python list of functions & methods

Sequences are Python in the basic data structure. Each element in the sequence is assigned a number - its position, or index, the first index is 0 , the second index is 1 , and so on.

Python has 6 built-in types of sequences, but the most common are lists and tuples.

The sequence of operations can be carried out, including indexing, slicing, add, multiply, check members.

In addition, the Python has been built to determine the sequence length and determining the maximum and minimum element method.

The list is the most common Python data types, which can appear as a comma-separated values in square brackets.

Data items list need not have the same type .

 

Create a list, as long as the comma-separated data items using different brackets can be. As follows:

list1 = ['physics', 'chemistry', 1997, 2000]

list2 = [1, 2, 3, 4, 5 ]

list3 = ["a", "b", "c", "d"]

 

Like string indices, list index from 0 begun. The list can be intercepted, combinations and the like.

 

 

1.Python contains the following functions :

1 ) cmp (List1, list2) : compare elements of two lists

2 ) len (List) : the list of the number of elements

. 3 ) max (List) : Returns the list of elements the maximum

. 4 ) min (List) : returns a list of the minimum element

. 5 ) List (SEQ) : converts a list of tuples

 

Here only related to functions and methods to solve this problem, the details may refer to: https://www.runoob.com/python/python-lists.html

 

① using len () method returns the number of list elements.

 

len () method syntax:

len (list)

 

Return the number of list elements.

 

The following examples illustrate len () to use the function:

list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']

print("First list length : ",len(list1))

print("Second list length : ",len(list2))

 

Output:

 

 

 

②list()方法用于将元组转换为列表。

 

list()方法语法:

list(tup)

 

返回列表。

 

注:元组与列表是非常类似的,区别在于元组的元素值不能修改,元组是放在括号中,列表是放于方括号中。

 

以下实例展示了list()函数的使用方法:

aTuple = (123, 'xyz', 'zara', 'abc')

aList = list(aTuple)

print("列表元素:", aList)

 

输出结果如下:

 

 

 

2.Python包含以下方法:

1list.append(obj):在列表末尾添加新的对象

2list.count(obj):统计某个元素在列表中出现的次数

3list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)

4list.index(obj):从列表中找出某个值第一个匹配项的索引位置

5list.insert(index, obj):将对象插入列表

6list.pop([index=-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值

7list.remove(obj):移除列表中某个值的第一个匹配项

8list.reverse():反向列表中元素

9list.sort(cmp=None, key=None, reverse=False):对原列表进行排序

 

①append()方法用于在列表末尾添加新的对象。

 

append()方法语法:

list.append(obj)

 

该方法无返回值,但是会修改原来的列表。

 

以下实例展示了append()函数的使用方法:

aList = [123, 'xyz', 'zara', 'abc']

aList.append(2009)

print("Updated List : ", aList)

 

输出结果如下:

 

 

 

②pop()函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

 

pop()方法语法:

list.pop([index=-1])

 

obj -- 可选参数,要移除列表元素的索引值,不能超过列表总长度,默认为 index=-1,删除最后一个列表值。

 

该方法返回从列表中移除的元素对象。

 

以下实例展示了 pop()函数的使用方法:

list1 = ['Google', 'Runoob', 'Taobao']

list_pop = list1.pop(1)

print("删除的项为 :", list_pop)

print("列表现在为 :", list1)

 

输出结果如下:

 

 

 

 

、代码实现

 

代码实现如下:

#使用列表来存放栈元素

def parentheses(m):

  list1=[]

  for i in range(len(m)):    

    if m[i]=='(' or m[i]==')':

      list1.append(m[i])  #将小括号元素放在list1

  list2=[]  #存放(,相当于栈

  if len(list1)==0:   #无小括号元素

    return True

  elif list1[0]==')':    #第一个元素为),即)在(前面

    return False

  elif len(list1)%2!=0:   #小括号元素总数为奇数,无论怎么配对也不会成功

    return False

  else:

    for i in range(len(list1)):

      if list1[i]=='(':   #将左括号元素放在list2

        list2.append(list1[i])

      elif list1[i]==')' and len(list2)!=0:   #排除右括号比左括号多的情况

        list2.pop()   #只要list1中有一个右括号且list2中左括号个数不为0,就移除list2里的一个左括号,以此进行左右括号配对

      else:

        return False

    return True

 

m=input('请输入字符串:')

if parentheses(m):

  print('括号配对成功!')

else:

  print('括号配对失败!')

 

运行结果:

 

 

 

 

 

 

 

 

 

上面的程序可以正常运行,但我发现了新的问题:以上代码并不适用于所有可能的输入,比如我输入(((()),即左括号比右括号多的情况,程序运行结果却未报错。

经查阅,我发现网上关于Python括号配对的问题基本上都是利用列表方法实现,但关于不合理输入的异常处理情况考虑的比较少。这里列出了一些有代表性的可能的输入情况,并且对每一种输入情况进行处理,符合括号配对原则的配对成功,否则失败。

 

可能存在情况:((())).(((()).(()))).()()等等。

 

可以看到,当左括号比右括号多时,上面的代码无法处理异常。这里我用自己的思路对上面的代码进行修改,修改后的代码如下:

#使用列表来存放栈元素

def bracketsmatch(m):

    list1=[]

    left=[]#存放(,相当于栈

    right=[]#存放),相当于栈

    

    for i in range(len(m)):    

        if m[i]=='(' or m[i]==')':

            list1.append(m[i])#将小括号元素放在list1

      

    if len(list1)==0:#无小括号元素

        return True

    elif list1[0]==')':#第一个元素为),即)在(前面

        return False

    elif len(list1)%2!=0:#小括号元素总数为奇数,无论怎么配对也不会成功

        return False

    else:

        for i in range(len(list1)):

            if list1[i]=='(':

                left.append(list1[i])#将左括号元素放在left              

            elif list1[i]==')' and len(left)!=0:#排除右括号比左括号多的情况
                right.append(list1[i])#将右括号元素放在right

                left.pop()#只要有一个右括号进入right,就将其移除,同时移除left里的一个左括号,以此进行左右括号配对

                right.pop()


                if len(left)==0 and len(right)==0:#如果左右括号配对完毕

                    return True  

                else:#左右括号未配对完毕,继续执行循环      

                    continue

            else:      

                return False

 

m=input('请输入字符串:')

if bracketsmatch(m):

  print('括号配对成功!')

else:

  print('括号配对失败!')

 

运行结果:

 

 

 

 

 

 

 

 

 

修改后的代码虽然处理了左括号比右括号多时的异常情况,但又无法处理右括号比左括号多的情况。这也是让我有点头疼的一点,即使我知道是程序算法设计的问题,但由于时间问题,我没来得及再进一步深入解决这个问题,后续时间里我会继续思考,争取将这个缺口补上。

 

 

参考资料:

https://www.runoob.com/python/python-lists.html

https://www.cnblogs.com/WoLykos/p/8709937.html

 

Guess you like

Origin www.cnblogs.com/BIXIABUMO/p/11627342.html