Kaydet (Commit) a0bcc27e authored tarafından Georg Brandl's avatar Georg Brandl

Modernize factorisation demo (mostly augassign.)

üst 3d072c95
...@@ -9,39 +9,41 @@ import sys ...@@ -9,39 +9,41 @@ import sys
from math import sqrt from math import sqrt
def fact(n): def fact(n):
if n < 1: raise ValueError # fact() argument should be >= 1 if n < 1:
if n == 1: return [] # special case raise ValueError('fact() argument should be >= 1')
if n == 1:
return [] # special case
res = [] res = []
# Treat even factors special, so we can use i = i+2 later # Treat even factors special, so we can use i += 2 later
while n%2 == 0: while n % 2 == 0:
res.append(2) res.append(2)
n = n//2 n //= 2
# Try odd numbers up to sqrt(n) # Try odd numbers up to sqrt(n)
limit = sqrt(float(n+1)) limit = sqrt(n+1)
i = 3 i = 3
while i <= limit: while i <= limit:
if n%i == 0: if n % i == 0:
res.append(i) res.append(i)
n = n//i n //= i
limit = sqrt(n+1) limit = sqrt(n+1)
else: else:
i = i+2 i += 2
if n != 1: if n != 1:
res.append(n) res.append(n)
return res return res
def main(): def main():
if len(sys.argv) > 1: if len(sys.argv) > 1:
for arg in sys.argv[1:]: source = sys.argv[1:]
n = eval(arg)
print n, fact(n)
else: else:
source = iter(raw_input, '')
for arg in source:
try: try:
while 1: n = int(arg)
n = input() except ValueError:
print n, fact(n) print arg, 'is not an integer'
except EOFError: else:
pass print n, fact(n)
if __name__ == "__main__": if __name__ == "__main__":
main() main()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment