diff --git a/reading06/Makefile b/reading06/Makefile new file mode 100644 index 0000000..3dae83f --- /dev/null +++ b/reading06/Makefile @@ -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 diff --git a/reading06/odds.py b/reading06/odds.py new file mode 100644 index 0000000..2d8a84d --- /dev/null +++ b/reading06/odds.py @@ -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 + + ''' + 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 + + ''' + 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()