[Python-checkins] r75325 - python/trunk/Demo/scripts/fact.py

georg.brandl python-checkins at python.org
Sat Oct 10 23:55:11 CEST 2009


Author: georg.brandl
Date: Sat Oct 10 23:55:11 2009
New Revision: 75325

Log:
Modernize factorisation demo (mostly augassign.)

Modified:
   python/trunk/Demo/scripts/fact.py

Modified: python/trunk/Demo/scripts/fact.py
==============================================================================
--- python/trunk/Demo/scripts/fact.py	(original)
+++ python/trunk/Demo/scripts/fact.py	Sat Oct 10 23:55:11 2009
@@ -9,39 +9,41 @@
 from math import sqrt
 
 def fact(n):
-    if n < 1: raise ValueError # fact() argument should be >= 1
-    if n == 1: return []    # special case
+    if n < 1:
+        raise ValueError('fact() argument should be >= 1')
+    if n == 1:
+        return []  # special case
     res = []
-    # Treat even factors special, so we can use i = i+2 later
-    while n%2 == 0:
+    # Treat even factors special, so we can use i += 2 later
+    while n % 2 == 0:
         res.append(2)
-        n = n//2
+        n //= 2
     # Try odd numbers up to sqrt(n)
-    limit = sqrt(float(n+1))
+    limit = sqrt(n+1)
     i = 3
     while i <= limit:
-        if n%i == 0:
+        if n % i == 0:
             res.append(i)
-            n = n//i
+            n //= i
             limit = sqrt(n+1)
         else:
-            i = i+2
+            i += 2
     if n != 1:
         res.append(n)
     return res
 
 def main():
     if len(sys.argv) > 1:
-        for arg in sys.argv[1:]:
-            n = eval(arg)
-            print n, fact(n)
+        source = sys.argv[1:]
     else:
+        source = iter(raw_input, '')
+    for arg in source:
         try:
-            while 1:
-                n = input()
-                print n, fact(n)
-        except EOFError:
-            pass
+            n = int(arg)
+        except ValueError:
+            print arg, 'is not an integer'
+        else:
+            print n, fact(n)
 
 if __name__ == "__main__":
     main()


More information about the Python-checkins mailing list