0

I want to write this code in more pythonic way. Have you any idea how I can do this?

def counter():
    for x in self.get_xs():
        total_x = 0
        result = (re.sub('[^0-9]', '', x))
        for number in result:
            total_x += int(number)
        yield(total_x)
3
  • Where is the result from ? Commented Jan 21, 2015 at 8:51
  • 2
    Where did result came from? Perhaps you meant: re.sub('[^0-9]', '', x). Commented Jan 21, 2015 at 8:51
  • Yes, sorry for mistake. Commented Jan 21, 2015 at 8:52

1 Answer 1

2

You can calculate the sum using sum() and a generator expression. If the iterable passed to sum() is empty(i.e re.sub() returned '') then it will simply return the default start value 0.

def counter():
    r = re.compile('[^0-9]')
    for x in self.get_xs():
        yield sum(int(number) for number in r.sub('', x))

In Python 3.3+ you can use yield from:

def counter():
    r = re.compile('[^0-9]')
    yield from (sum(map(int, r.sub('', x))) for x in self.get_xs()) 
Sign up to request clarification or add additional context in comments.

6 Comments

I think, in this case, where there's just one yield from, you could also do return (<generator>) in Python 2.
It would be a good idea to move the compiled regular expression out of the function so it’s reused instead of recompiled every time. Also, the function likely needs a self argument.
@poke IIRC Python caches regular expressions.
The docs say: "The compiled versions of the most recent patterns passed to re.match(), re.search() or re.compile() are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions." re.sub is not mentioned.
@AshwiniChaudhary Interesting, I didn’t know that!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.