Merge pull request #13 from nd-cse-20289-sp25/reading06

Reading06
This commit is contained in:
AlyssaRiter23 2025-02-28 20:41:58 -05:00 committed by GitHub
commit 518a3d94bb
2 changed files with 89 additions and 0 deletions

15
reading06/Makefile Normal file
View file

@ -0,0 +1,15 @@
test:
@$(MAKE) -sk test-all
test-all: test-odds
test-scripts:
@curl -sLO https://www3.nd.edu/~pbui/teaching/cse.20289.sp25/static/txt/reading06/odds.test
@chmod +x ./*.test
test-odds: test-scripts odds.py
@echo Testing Odds ...
@./odds.test -v
@echo
clean:
@rm -f *.test

74
reading06/odds.py Normal file
View file

@ -0,0 +1,74 @@
#!/usr/bin/env python3
from typing import Iterator
import io
import sys
# Functions
def odds(stream=sys.stdin) -> list[int]:
''' Return a list of all the odd numbers in stream.
>>> odds(io.StringIO('\\n'.join('1 2 3 4 5'.split())))
[1, 3, 5]
'''
results = []
for line in stream:
number = int(line)
if number % 2:
results.append(number)
return results
def odds_fp(stream=sys.stdin) -> Iterator[int]:
''' Return a sequence of odd numbers from stream using map and filter.
>>> odds_fp(io.StringIO('\\n'.join('1 2 3 4 5'.split()))) # doctest: +ELLIPSIS
<filter object at ...>
'''
numbers = map(int, stream)
return filter(lambda x: x % 2, numbers)
def odds_lc(stream=sys.stdin) -> list[int]:
''' Return a list of all the odd numbers in stream using a list
comprehension.
>>> odds_lc(io.StringIO('\\n'.join('1 2 3 4 5'.split())))
[1, 3, 5]
'''
numbers = []
for line in stream:
number = int(line)
if number % 2:
numbers.append(number)
return numbers
def odds_gr(stream=sys.stdin) -> Iterator[int]:
''' Return a sequence of odd numbers from stream using yield.
>>> odds_gr(io.StringIO('\\n'.join('1 2 3 4 5'.split()))) # doctest: +ELLIPSIS
<generator object odds_gr at ...>
'''
for line in stream:
number = int(line)
if number % 2:
yield number
# Main Execution
def main(arguments=sys.argv[1:], stream=sys.stdin) -> None:
odds_functions = {
'-f': odds_fp,
'-l': odds_lc,
'-g': odds_gr,
}
if not arguments:
print('Usage: odds.py [-f -l -g]', file=sys.stderr)
sys.exit(1)
odds_function = odds_functions.get(arguments[0], odds)
for odd in odds_function(stream):
print(odd)
if __name__ == '__main__':
main()