From the HackerRank question definition:

The word google can be spelled in many different ways.

E.g. google, g00gle, g0oGle, g<>0gl3, googl3, GooGIe etc...


g = G

o = O = 0 = () = [] = <>

l = L = I

e = E = 3

That's the problem here to solve.

And the match has to be only this single word, nothing more, nothing less.


"g00gle" = True, "g00gle " = False, "g google" = False, "GGOOGLE" = False, "hey google" = False

What I'm looking in review: How can I make my code more pythonic?

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import re

g = ["g", "G"]
o = ["o", "O", "0", "()", "[]", "<>"]
l = ["l", "L", "I"]
e = ["e", "E", "3"]

regex = (g, o, o, g, l, e)
regex = ((re.escape(y) for y in x) for x in regex)
regex = ("(?:{})".format("|".join(x)) for x in regex)
regex = "^{}$".format("".join(regex))

print(bool(re.match(regex, input())))

Honestly there's not much code to comment on, it's also a programming challenge, so there's not much incentive to make it any better than it is. I too would have done it your way.

The only objective criticism I have is I'd just add a function regex_options to build the non-capturing group.

Other than that I'd apply this to the creation of g, o, l and e. As I think it's a little cleaner. But you may want to perform it before "".join, and after regex = (g, o, o, g, l, e).

import re

def regex_options(options):
    options = (re.escape(o) for o in options)
    return "(?:{})".format("|".join(options))

g = regex_options(["g", "G"])
o = regex_options(["o", "O", "0", "()", "[]", "<>"])
l = regex_options(["l", "L", "I"])
e = regex_options(["e", "E", "3"])

regex = "^{}$".format("".join((g, o, o, g, l, e)))

print(bool(re.match(regex, input())))

If this were professional code, I'd suggest using an if __name__ == '__main__': block, and possibly a main function.

  • 2
    \$\begingroup\$ I like this solution better, because it doesn't repeatedly redefine regex and change its type. \$\endgroup\$ Feb 18 '19 at 19:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.