John Lance John Lance - 1 year ago 278
Python Question

Failing hidden CodeFights test - can't find flaw in code

Here's the challenge I'm failing a hidden test on:

Given integers n, l and r, find the number of ways to represent n as a sum of two integers A and B such that l ≤ A ≤ B ≤ r.

Here's my code:

def countSumOfTwoRepresentations2(n, l, r):
#initializing return variable
totalcount = 0
#returns 0 in impossible cases
if (l + r > n):
return 0
if (r + r < n):
return 0
if (r < (n/2)) or (l > (n/2)):
return 0
# finding the total number of possibilities
p = n / 2
# finding which if l or r is further from 0 or n, respectively
c = max((n-r),l)
# removing impossible cases
totalcount = (p - c) + 1
return totalcount

It passes all the tests I can see the inputs for (and every custom one I could think of), but fails on one of the hidden ones. Any obvious flaws I'm missing? Thanks

Answer Source

As user2357112 noted, you have rejected some valid cases, such as 11, 5, 9: that still permits 6+5 as a solution.

You have also failed to reject an invalid case due to integer division, such as 11, 2, 5, where n == 2*r + 1; however, in these cases, your calculations naturally return 0. I'm wrong here: r + r < n will catch this case, but this means that your r < (n/2) case is redundant

If you still have trouble with your testing, please include your test classes and test vectors (input sets).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download