• + 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.