Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Knowing my solution ...

Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not.

xyz_there('abcxyz') → True  
xyz_there('abc.xyz') → False 
xyz_there('xyz.abc') → True

def xyz_there(str):
    return str.count("xyz") > str.count(".xyz")

...evolved from this code:

def xyz_there(str):
    if str.count("xyz") > str.count(".xyz"):
        return True
    return False

I wonder if there's some rule that describes when you can flatten the IF and write is as a return value like I did?

share|improve this question
    
Is this a question about Python semantics or are you asking for a review of your code? – jacwah Jul 26 '15 at 10:27
    
@jacwah I can only get the answer from the review of that code hence the question :) – noob81 Jul 26 '15 at 10:32
up vote 4 down vote accepted

You can use boolean expressions directly. When you return a boolean expression directly, the code is naturally readable, and shorter too. No need to write out a full if-else condition.

I don't think it's a "rule" though. It's a general recommendation.

Your code has a bigger problem though: it's inefficient. count will search through the entire string. A better way is to use regular expressions:

import re

xyz_not_preceded_by_dot = re.compile(r'(?<!\.)xyz')


def xyz_there(str):
    """
    >>> xyz_there("abcxyz")
    True
    >>> xyz_there("abc.xyz")
    False
    >>> xyz_there("xyz.abc")
    True
    >>> xyz_there("abc")
    False
    """
    return xyz_not_preceded_by_dot.search(str) is not None
share|improve this answer
    
what's the best way to go about learning regular expressions, I see those are an advanced topic – noob81 Jul 27 '15 at 6:17
    
Yes, regular expressions are extremely important in programming. I learned them a long time ago, mainly from the docs, for example the re package. That might not be easy reading, and probably more friendly tutorials exist today, but I don't know them. – janos Jul 27 '15 at 7:47
1  
I'm very grateful to you for pointing me to regex and everything else, if you ever decide to become a mentor, I volunteer as a disciple lol – noob81 Jul 27 '15 at 9:51
    
is there any way to write that regex without using a negative lookbehind? :) – noob81 Sep 6 '15 at 15:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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