蟒蛇
由于我不太确定评分标准,因此出于娱乐考虑,我提出了许多解决方案。它们中的大多数abs(n)
用来支持负数。绝大部分(如果不是全部)都绝不能用于实际计算。
这很无聊:
from __future__ import division
def parity(n):
"""An even number is divisible by 2 without remainder."""
return "Even" if n/2 == int(n/2) else "Odd"
def parity(n):
"""In base-10, an odd number's last digit is one of 1, 3, 5, 7, 9."""
return "Odd" if str(n)[-1] in ('1', '3', '5', '7', '9') else "Even"
def parity(n):
"""An even number can be expressed as the sum of an integer with itself.
Grossly, even absurdly inefficient.
"""
n = abs(n)
for i in range(n):
if i + i == n:
return "Even"
return "Odd"
def parity(n):
"""An even number can be split into two equal groups."
g1 = []
g2 = []
for i in range(abs(n)):
g1.append(None) if len(g1) == len(g2) else g2.append(None)
return "Even" if len(g1) == len(g2) else "Odd"
import ent # Download from: http://wstein.org/ent/ent_py
def parity(n):
"""An even number has 2 as a factor."""
# This also uses modulo indirectly
return "Even" if ent.factor(n)[0][0] == 2 else "Odd"
这是我最喜欢的,尽管不幸的是它不起作用(正如下面的March Ho指出的:仅仅因为所有偶数都是两个质数之和,并不意味着所有奇数都不是)。
import itertools
import ent # Download from: http://wstein.org/ent/ent_py
def parity(n)
"""Assume Goldbach's Conjecture: all even numbers greater than 2 can
be expressed as the sum of two primes.
Not guaranteed to be efficient, or even succeed, for large n.
"""
# A few quick checks
if n in (-2, 0, 2): return "Even"
elif n in (-1, 1): return "Odd"
if n < 0: n = -n # a bit faster than abs(n)
# The primes generator uses the Sieve of Eratosthenes
# and thus modulo, so this is a little bit cheating
primes_to_n = ent.primes(n)
# Still one more easy way out
if primes_to_n[-1] == n: return "Odd"
# Brutish!
elif n in (p1+p2 for (p1, p2) in itertools.product(primes_to_n, primes_to_n)):
return "Even"
else:
return "Odd"