Calculating Odd/Even number of divisors in Python

The challenge

Given an integer `n` return `"odd"` if the number of its divisors is odd. Otherwise, return `"even"`.

Note: big inputs will be tested.

Examples:

All prime numbers have exactly two divisors (hence `"even"`).

For `n = 12` the divisors are `[1, 2, 3, 4, 6, 12]` – `"even"`.

For `n = 4` the divisors are `[1, 2, 4]` – `"odd"`.

The solution in Python code

Option 1:

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```def oddity(n):
return 'odd' if n**0.5 == int(n**0.5) else 'even'
```Code language: Python (python)```

Option 2:

``````import math
def oddity(n):
return math.sqrt(n) % 1 == 0 and 'odd' or 'even'
```Code language: Python (python)```

Option 3:

``````oddity=lambda n: ["odd","even"][n**.5%1!=0]
```Code language: Python (python)```

Test cases to validate our solution

``````import test
from solution import oddity

@test.describe("Sample tests")
def tests():
@test.it("Some examples")
def tests():
test.assert_equals(oddity(1), 'odd')
test.assert_equals(oddity(5), 'even')
test.assert_equals(oddity(16), 'odd')
```Code language: Python (python)```
Tags:
Subscribe
Notify of