Skip to content

Commit b50778d

Browse files
committed
factor: Support reading from stdin
1 parent d67b5c6 commit b50778d

File tree

1 file changed

+18
-17
lines changed

1 file changed

+18
-17
lines changed

userland/utilities/factor.py

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#!/usr/bin/python3
22

33
import math
4+
import sys
45
from typing import Generator, Iterable
56

67
from .. import lib
@@ -107,34 +108,34 @@ def format_exponents(factors: Iterable[int]) -> str:
107108

108109
parser.add_option("-h", "--exponents", action="store_true")
109110

111+
110112
@lib.command(parser)
111113
def python_userland_factor(opts, args):
112-
numbers: list[int] = []
113-
114-
for arg in args:
115-
try:
116-
num = int(arg)
117-
if num < 0:
118-
raise ValueError
119-
except ValueError:
120-
parser.error(f"'{arg}' is not a valid positive integer")
121-
122-
numbers.append(num)
114+
failed = False
123115

124116
try:
125-
for n in numbers:
126-
if n < 2:
127-
print(f"{n}:")
117+
for arg in args or lib.readwords_stdin():
118+
try:
119+
num = int(arg)
120+
if num < 0:
121+
raise ValueError
122+
except ValueError:
123+
failed = True
124+
print(f"'{arg}' is not a valid positive integer", file=sys.stderr)
125+
continue
126+
127+
if num < 2:
128+
print(f"{num}:")
128129
continue
129130

130-
factors = sorted(factorize(n))
131+
factors = sorted(factorize(num))
131132

132133
print(
133-
f"{n}: {format_exponents(factors) if opts.exponents
134+
f"{num}: {format_exponents(factors) if opts.exponents
134135
else " ".join(map(str, factors))}"
135136
)
136137
except KeyboardInterrupt:
137138
print()
138139
return 130
139140

140-
return 0
141+
return int(failed)

0 commit comments

Comments
 (0)