Sort by

recency

|

308 Discussions

|

  • + 0 comments

    TIL about lookahead and lookbehind.

    The compact "code golf" version…

    import re, sys
    
    # everything in one "line"
    print(''.join(re.sub(r'(?<=( ))(&&|||)(?=( ))', 
        lambda m: ['and', 'or'][m[2] == '||'], l)
      for l in sys.stdin.readlines()[1:]))
    

    The somewhat easier to read version…

    import re, sys
    
    print(
      ''.join(
        re.sub(
          r'(?<=( ))(&&|||)(?=( ))', 
          lambda match: ['and', 'or'][match[2] == '||'],
          line
        )
        for line in sys.stdin.readlines()[1:]
      )
    )
    

    The somewhat easier to read version…

    I've yet to see a HackerRank challenge requiring the "N" parameter on the first line of the input. I always read all lines in and skip the first one.

  • + 1 comment

    n = int(input()) pattern = r'(?<= )(&&|||)(?= )' for _ in range(n): a = input() s = re.sub(pattern, lambda m: 'and' if m.group(0) == '&&' else 'or',a) print(s)

  • + 0 comments

    Here is HackerRank Regex Substitution in Python solution - https://programmingoneonone.com/hackerrank-regex-substitution-solution-in-python.html

  • + 0 comments

    and_pattern = "(?<= )\&\&(?= )" or_pattern = "(?<= )||(?= )"

    Explanation: (?<= ) is a look behind positive. This ensures the characters are preceeded by a space. (?= ) is a look ahead positive. This ensures the characters are followed by a space. Finally, the string in question contains characters which themselves are used in regex statement, so they must be escaped with a backslash to be recognized!

  • + 0 comments

    import re

    def replace_operators(text): text = re.sub(r'(?<=\s)||(?=\s)', 'or', text) text = re.sub(r'(?<=\s)&&(?=\s)', 'and', text) return text

    N = int(input()) text = "\n".join(input() for _ in range(N)) result = replace_operators(text) print(result)