Home > Net >  A more pythonic way to check for duplicate characters and check that they are next to each other?
A more pythonic way to check for duplicate characters and check that they are next to each other?

Time:11-19

Is there a more pythonic way to check if there are two '((' AND '))' in the string? I've made an attempt but it does not look very pythonic

def check (string):

    text = list(string) 

    prev = text[0]
    curr = text[1]
    first=False
    second=False

    for nxt in text[2:]:    
        if (prev == "(" and curr == "("):
            first = True

        elif (curr == "(" and nxt == "("):
            first = True

        elif (prev == ")" and curr == ")"):
            second = True
        
        elif (curr == ")" and nxt == ")"):
            second = True
        
        prev = curr
        curr = nxt
       
    if (first == True and second == True):
         return "true"
    else:
        return "false"

examples:

check("((a))   b") # true
check("((a)   b") # false
check("(a b))") # false
check("((a b))") # true
check("((a)(b))") # true
check("(((a)))") # true
check("a))   ((b") # true

CodePudding user response:

If all you want is "has adjacent parens of each type", the solution is just:

def check(string):
    return '((' in string and '))' in string

A regex could be used to confirm they appear in the correct order and reduce the work to a single pass over string, not two, but if you don't need correct "logical" order, the incremental work of scanning twice is pretty meaningless 99% of the time. A regex solution would just be:

import re

def check(string):
    return re.search(r'\(\(.*\)\)', string, re.DOTALL) is not None
  • Related