0

I created this line of code today which determines whether a number divides evenly

if (numerator / denominator * denominator) == numerator:
    print "Divides evenly!"
else:
    print "Doesn't divide evenly."

Yet I ran into an issue when dividing by 0 as I still wanted it to tell me whether it would divide even if the denominator was 0 by looking at the numerator and seeing if it was even or odd. I came up with this:

if denominator != 0 and (numerator / denominator * denominator) == 
numerator:
    print "Divides evenly!"
elif denominator == 0 and numerator % 2 == 0:
    print "Divides evenly!"
else:
    print "Doesn't divide evenly."

Is there any way to shorten this? Also, is there any way to not have to add the new 'elif' statement?

  • 1
    won't denominater cancel out here? – Joe Aug 24 '17 at 16:31
  • 3
    I think this would be better suited on https://codereview.stackexchange.com/ – bummi Aug 24 '17 at 16:32
  • 1
    I'm assuming you are relying on integer division `//`, which is required in Py3. `numerator / denominator * denominator) == numerator` is equivalent to `numerator % denominator == 0`. Divide by `0` is undefined and it is meaningless to say this divides evenly. – AChampion Aug 24 '17 at 16:32
  • 4
    I'm voting to close this question as off-topic because it belongs on https://codereview.stackexchange.com/ – ekhumoro Aug 24 '17 at 16:43

2 Answers2

3

In short, if the denominator is 0, you want it to be 2:

if denominator == 0:
    denominator = 2

if numerator % denominator == 0:
    print "Divides evenly!"
else:
    print "Doesn't divide evenly."

or even shorter:

if numerator % (denominator or 2) == 0:
    print "Divides evenly!"
else:
    print "Doesn't divide evenly."
Daniel
  • 42,087
  • 4
  • 55
  • 81
0
def fun(n,d):
    return (d==0 and n%2==0) or (d!=0 and n%d==0)
akp
  • 619
  • 5
  • 12
  • 1
    Use `True` and `False` instead of `1` and `0`. Use meaningful names. You can return the result of conditions directly. – Daniel Aug 24 '17 at 17:02
  • While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. **Flaggers / reviewers:** [For code-only answers such as this one, downvote, don't delete!](//meta.stackoverflow.com/a/260413/2747593) – Patrick Aug 25 '17 at 00:05
  • code reuse using function and thus shorten code. – akp Aug 25 '17 at 04:31