From 09790e9ed218ceb50b9e471c2c714f760ac473d1 Mon Sep 17 00:00:00 2001 From: Tomi Oredein Date: Wed, 9 Nov 2022 17:52:56 +0000 Subject: [PATCH 1/8] tiny project chapter 1 --- 01_hello/hello.py | 22 ++++++++++++++ 01_hello/hello2.py | 72 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100755 01_hello/hello.py create mode 100755 01_hello/hello2.py diff --git a/01_hello/hello.py b/01_hello/hello.py new file mode 100755 index 000000000..9c7eedb6f --- /dev/null +++ b/01_hello/hello.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +""" +Author: Tomi Oredein +Purpose: Say hello +""" + + +import argparse + +def get_args(): + """Get the command-line arguments""" + parser = argparse.ArgumentParser(description='Say hello') + parser.add_argument('-n', '--name', metavar='name', default='World', help='Name to greet') + return parser.parse_args() + +def main(): + """Make a jazz noise here""" + args = get_args() + print('Hello, ' + args.name + '!') + +if __name__ == '__main__': + main() diff --git a/01_hello/hello2.py b/01_hello/hello2.py new file mode 100755 index 000000000..bdd33b529 --- /dev/null +++ b/01_hello/hello2.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +""" +Author : tomioredein +Date : 2022-11-09 +Purpose: Rock the Casbah +""" + +import argparse + + +# -------------------------------------------------- +def get_args(): + """Get command-line arguments""" + + parser = argparse.ArgumentParser( + description='Rock the Casbah', + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + + parser.add_argument('positional', + metavar='str', + help='A positional argument') + + parser.add_argument('-a', + '--arg', + help='A named string argument', + metavar='str', + type=str, + default='') + + parser.add_argument('-i', + '--int', + help='A named integer argument', + metavar='int', + type=int, + default=0) + + parser.add_argument('-f', + '--file', + help='A readable file', + metavar='FILE', + type=argparse.FileType('rt'), + default=None) + + parser.add_argument('-o', + '--on', + help='A boolean flag', + action='store_true') + + return parser.parse_args() + + +# -------------------------------------------------- +def main(): + """Make a jazz noise here""" + + args = get_args() + str_arg = args.arg + int_arg = args.int + file_arg = args.file + flag_arg = args.on + pos_arg = args.positional + + print(f'str_arg = "{str_arg}"') + print(f'int_arg = "{int_arg}"') + print('file_arg = "{}"'.format(file_arg.name if file_arg else '')) + print(f'flag_arg = "{flag_arg}"') + print(f'positional = "{pos_arg}"') + + +# -------------------------------------------------- +if __name__ == '__main__': + main() From eb7366bb59c0cb00f6cde0a790f453680f8979cb Mon Sep 17 00:00:00 2001 From: opanther Date: Tue, 15 Nov 2022 10:53:37 +0000 Subject: [PATCH 2/8] working with strings --- 01_hello/hello.py | 14 +++++--- 02_crowsnest/crowsnest.py | 37 ++++++++++++++++++++ template/template.py | 72 ++++++++++++++++++++------------------- 3 files changed, 83 insertions(+), 40 deletions(-) create mode 100755 02_crowsnest/crowsnest.py diff --git a/01_hello/hello.py b/01_hello/hello.py index 9c7eedb6f..8b7f84991 100755 --- a/01_hello/hello.py +++ b/01_hello/hello.py @@ -4,19 +4,23 @@ Purpose: Say hello """ - import argparse + def get_args(): """Get the command-line arguments""" - parser = argparse.ArgumentParser(description='Say hello') - parser.add_argument('-n', '--name', metavar='name', default='World', help='Name to greet') + parser = argparse.ArgumentParser(description="Say hello") + parser.add_argument( + "-n", "--name", metavar="name", default="World", help="Name to greet" + ) return parser.parse_args() + def main(): """Make a jazz noise here""" args = get_args() - print('Hello, ' + args.name + '!') + print("Hello, " + args.name + "!") + -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/02_crowsnest/crowsnest.py b/02_crowsnest/crowsnest.py new file mode 100755 index 000000000..0dfb0390a --- /dev/null +++ b/02_crowsnest/crowsnest.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +""" +Author : tomioredein +Date : 2022-11-11 +Purpose: Crow's Nest +""" + +import argparse + + +# -------------------------------------------------- +def get_args(): + """Get command-line arguments""" + + parser = argparse.ArgumentParser( + description="Working with strings", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + + parser.add_argument("word", metavar="word", help="A word") + return parser.parse_args() + + +# -------------------------------------------------- +def main() -> object: + """Make a jazz noise here""" + + args = get_args() + word = args.word + article = "an" if word[0].lower() in "aeiou" else "a" + + print(f"Ahoy, Captain, {article} {word} off the larboard bow!") + + +# -------------------------------------------------- +if __name__ == "__main__": + main() diff --git a/template/template.py b/template/template.py index 225dea9c4..0df2e4ea0 100755 --- a/template/template.py +++ b/template/template.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """ -Author : Me +Author : Tomi Oredein Date : today Purpose: Rock the Casbah """ @@ -13,38 +13,40 @@ def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( - description='Rock the Casbah', - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - - parser.add_argument('positional', - metavar='str', - help='A positional argument') - - parser.add_argument('-a', - '--arg', - help='A named string argument', - metavar='str', - type=str, - default='') - - parser.add_argument('-i', - '--int', - help='A named integer argument', - metavar='int', - type=int, - default=0) - - parser.add_argument('-f', - '--file', - help='A readable file', - metavar='FILE', - type=argparse.FileType('r'), - default=None) - - parser.add_argument('-o', - '--on', - help='A boolean flag', - action='store_true') + description="Rock the Casbah", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + + parser.add_argument("positional", metavar="str", help="A positional argument") + + parser.add_argument( + "-a", + "--arg", + help="A named string argument", + metavar="str", + type=str, + default="", + ) + + parser.add_argument( + "-i", + "--int", + help="A named integer argument", + metavar="int", + type=int, + default=0, + ) + + parser.add_argument( + "-f", + "--file", + help="A readable file", + metavar="FILE", + type=argparse.FileType("r"), + default=None, + ) + + parser.add_argument("-o", "--on", help="A boolean flag", action="store_true") return parser.parse_args() @@ -62,11 +64,11 @@ def main(): print(f'str_arg = "{str_arg}"') print(f'int_arg = "{int_arg}"') - print('file_arg = "{}"'.format(file_arg.name if file_arg else '')) + print('file_arg = "{}"'.format(file_arg.name if file_arg else "")) print(f'flag_arg = "{flag_arg}"') print(f'positional = "{pos_arg}"') # -------------------------------------------------- -if __name__ == '__main__': +if __name__ == "__main__": main() From d1ee385b10c01ce6006c3d5bfeeb4c10edf8b84f Mon Sep 17 00:00:00 2001 From: opanther Date: Fri, 18 Nov 2022 13:18:23 +0000 Subject: [PATCH 3/8] working with list --- 03_picnic/picnic.py | 71 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100755 03_picnic/picnic.py diff --git a/03_picnic/picnic.py b/03_picnic/picnic.py new file mode 100755 index 000000000..1e08de7a2 --- /dev/null +++ b/03_picnic/picnic.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +""" +Author : tomioredein +Date : 2022-11-17 +Purpose: Working with list +""" + +import argparse + + +# -------------------------------------------------- + +# The get_args() function is placed first so i can easily see what the program accepts when we read it. +def get_args(): + """Get command-line arguments""" + + parser = argparse.ArgumentParser( + description="Picnic game", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + # The item argument uses nargs='+' so that it will accept one or more positional arguments, which will be strings. + parser.add_argument("items", metavar="str", help="Item(s) to bring", nargs="+") + # The dashes in the short (-s) and long (--sorted) names make this an option. There is no value associated with this argument. It’s either present (in which case it will be True) or absent (False). + parser.add_argument( + "-s", + "--sorted", + action="store_true", + help="Sort the items", + ) + # Process the command-line arguments and return them to the caller. + return parser.parse_args() + + +# -------------------------------------------------- + + +# The main() function is where the program will start. + + +def main(): + """Make a jazz noise here""" + # Call the get_args() function and put the returned value into the variable args. If there is a problem parsing the arguments, the program will fail before the values are returned. + args = get_args() + # Copy the item list from args into the new variable items. + items = args.items + # Use the length function len() to get the number of items in the list. There can never be zero items because we defined the argument using nargs='+', which always requires at least one value. + num = len(items) + # The args.sorted value will be either True or False. + # If we are supposed to sort the items, call the items.sort() method to sort them in place. + if args.sorted: + items.sort() + # Use an empty string to initialize a variable to hold the items we are bringing. + bringing = "" + # If the number of items is 1, we will assign the one item to bringing. + if num == 1: + bringing = items[0] + # If the number of items is 2, put the string ' and ' in between the items + elif num == 2: + bringing = " and ".join(items) + # Otherwise, alter the last element in items to append the string 'and ' before whatever is already there. + else: + items[-1] = "and " + items[-1] + # Join the items on a string of comma and space. + bringing = ", ".join(items) + + print(f"You are bringing {bringing}.") + + +# -------------------------------------------------- +if __name__ == "__main__": + main() From 018639e275727ef34b011ac12d27b88e919737d8 Mon Sep 17 00:00:00 2001 From: opanther Date: Tue, 29 Nov 2022 16:07:31 +0000 Subject: [PATCH 4/8] Jump the five, working with dictionary --- .gitignore | 21 +------------- 02_crowsnest/crowsnest.py | 4 +-- 04_jump_the_five/jump.py | 58 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 22 deletions(-) create mode 100755 04_jump_the_five/jump.py diff --git a/.gitignore b/.gitignore index 68ca39690..7dd14fd83 100644 --- a/.gitignore +++ b/.gitignore @@ -11,23 +11,4 @@ tex2pdf* .coverage .idea .vscode -02_crowsnest/crowsnest.py -03_picnic/picnic.py -04_jump_the_five/jump.py -05_howler/howler.py -06_wc/wc.py -07_gashlycrumb/gashlycrumb.py -08_apples_and_bananas/apples.py -09_abuse/abuse.py -10_telephone/telephone.py -11_bottles_of_beer/bottles.py -12_ransom/ransom.py -13_twelve_days/twelve_days.py -14_rhymer/rhymer.py -15_kentucky_friar/friar.py -16_scrambler/scrambler.py -17_mad_libs/mad.py -18_gematria/gematria.py -19_wod/wod.py -20_password/password.py -21_tictactoe/tictactoe.py + diff --git a/02_crowsnest/crowsnest.py b/02_crowsnest/crowsnest.py index 0dfb0390a..c834b6b0e 100755 --- a/02_crowsnest/crowsnest.py +++ b/02_crowsnest/crowsnest.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """ -Author : tomioredein +Author : tomi oredein Date : 2022-11-11 Purpose: Crow's Nest """ @@ -22,7 +22,7 @@ def get_args(): # -------------------------------------------------- -def main() -> object: +def main(): """Make a jazz noise here""" args = get_args() diff --git a/04_jump_the_five/jump.py b/04_jump_the_five/jump.py new file mode 100755 index 000000000..872ec9811 --- /dev/null +++ b/04_jump_the_five/jump.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +""" +Author : tomioredein +Date : 2022-11-29 +Purpose: Jump the five +""" + +import argparse + + +# -------------------------------------------------- +def get_args(): + """Get command-line arguments""" + + parser = argparse.ArgumentParser( + description="Jump the five", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + + parser.add_argument("text", metavar="str", help="Input text") + + return parser.parse_args() + + +# -------------------------------------------------- +def main(): + """Make a jazz noise here""" + + args = get_args() + jump = { + "1": "9", + "2": "8", + "3": "7", + "4": "6", + "5": "0", + "6": "4", + "7": "3", + "8": "2", + "9": "1", + "0": "5", + } + # Solution 1 + # for char in args.text: + # print(jump.get(char, char), end="") + # + # print() + + # List comprehension solution + + # print("".join([jump.get(char, char) for char in args.text])) + + # Using the str.translate function + print(args.text.translate(str.maketrans(jump))) + + +# -------------------------------------------------- +if __name__ == "__main__": + main() From ddbe5c08c729de9046ce95f730df524b19c66755 Mon Sep 17 00:00:00 2001 From: opanther Date: Tue, 3 Jan 2023 16:34:08 +0000 Subject: [PATCH 5/8] chapter 5, 6 and 7 --- 05_howler/howler.py | 74 +++++++++++++++++++++++++++++++++++ 06_wc/tomi.txt | 2 + 06_wc/wc.py | 74 +++++++++++++++++++++++++++++++++++ 07_gashlycrumb/gashlycrumb.py | 54 +++++++++++++++++++++++++ hagrid.txt | 1 + out.txt | 0 6 files changed, 205 insertions(+) create mode 100755 05_howler/howler.py create mode 100644 06_wc/tomi.txt create mode 100755 06_wc/wc.py create mode 100755 07_gashlycrumb/gashlycrumb.py create mode 100644 hagrid.txt create mode 100644 out.txt diff --git a/05_howler/howler.py b/05_howler/howler.py new file mode 100755 index 000000000..c255d4ed8 --- /dev/null +++ b/05_howler/howler.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +""" +Author : tomioredein +Date : 2022-12-01 +Purpose: Rock the Casbah +""" + +import argparse + + +# -------------------------------------------------- +def get_args(): + """Get command-line arguments""" + + parser = argparse.ArgumentParser( + description="Rock the Casbah", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + + parser.add_argument("positional", metavar="str", help="A positional argument") + + parser.add_argument( + "-a", + "--arg", + help="A named string argument", + metavar="str", + type=str, + default="", + ) + + parser.add_argument( + "-i", + "--int", + help="A named integer argument", + metavar="int", + type=int, + default=0, + ) + + parser.add_argument( + "-f", + "--file", + help="A readable file", + metavar="FILE", + type=argparse.FileType("rt"), + default=None, + ) + + parser.add_argument("-o", "--on", help="A boolean flag", action="store_true") + + return parser.parse_args() + + +# -------------------------------------------------- +def main(): + """Make a jazz noise here""" + + args = get_args() + str_arg = args.arg + int_arg = args.int + file_arg = args.file + flag_arg = args.on + pos_arg = args.positional + + print(f'str_arg = "{str_arg}"') + print(f'int_arg = "{int_arg}"') + print('file_arg = "{}"'.format(file_arg.name if file_arg else "")) + print(f'flag_arg = "{flag_arg}"') + print(f'positional = "{pos_arg}"') + + +# -------------------------------------------------- +if __name__ == "__main__": + main() diff --git a/06_wc/tomi.txt b/06_wc/tomi.txt new file mode 100644 index 000000000..91a090eec --- /dev/null +++ b/06_wc/tomi.txt @@ -0,0 +1,2 @@ +this is a test file for my program +i need to stop cheating myself with the process diff --git a/06_wc/wc.py b/06_wc/wc.py new file mode 100755 index 000000000..cf78cffac --- /dev/null +++ b/06_wc/wc.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +""" +Author : tomioredein +Date : 2022-12-29 +Purpose: Rock the Casbah +""" + +import argparse + + +# -------------------------------------------------- +def get_args(): + """Get command-line arguments""" + + parser = argparse.ArgumentParser( + description="Rock the Casbah", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + + parser.add_argument("positional", metavar="str", help="A positional argument") + + parser.add_argument( + "-a", + "--arg", + help="A named string argument", + metavar="str", + type=str, + default="", + ) + + parser.add_argument( + "-i", + "--int", + help="A named integer argument", + metavar="int", + type=int, + default=0, + ) + + parser.add_argument( + "-f", + "--file", + help="A readable file", + metavar="FILE", + type=argparse.FileType("rt"), + default=None, + ) + + parser.add_argument("-o", "--on", help="A boolean flag", action="store_true") + + return parser.parse_args() + + +# -------------------------------------------------- +def main(): + """Make a jazz noise here""" + + args = get_args() + str_arg = args.arg + int_arg = args.int + file_arg = args.file + flag_arg = args.on + pos_arg = args.positional + + print(f'str_arg = "{str_arg}"') + print(f'int_arg = "{int_arg}"') + print('file_arg = "{}"'.format(file_arg.name if file_arg else "")) + print(f'flag_arg = "{flag_arg}"') + print(f'positional = "{pos_arg}"') + + +# -------------------------------------------------- +if __name__ == "__main__": + main() diff --git a/07_gashlycrumb/gashlycrumb.py b/07_gashlycrumb/gashlycrumb.py new file mode 100755 index 000000000..77eb7bdb5 --- /dev/null +++ b/07_gashlycrumb/gashlycrumb.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +""" +Author : tomioredein +Date : 2023-01-03 +Purpose: Rock the Casbah +""" + +import argparse +import sys + + +# -------------------------------------------------- +def get_args(): + """Get command-line arguments""" + + parser = argparse.ArgumentParser( + description="Gashlycrumb", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + + parser.add_argument( + "letter", metavar="letter", nargs="*", help="Letters(s)", type=str + ) + parser.add_argument( + "-f", + "--file", + metavar="FILE", + default="gashlycrumb.txt", + type=argparse.FileType("rt"), + help="Input file", + ) + return parser.parse_args() + + +# -------------------------------------------------- +def main(): + """Make a jazz noise here""" + + args = get_args() + + lookup = {} + for line in args.file: + lookup[line[0].upper()] = line.rstrip() + + for letter in args.letter: + if letter.upper() in lookup: + print(lookup[letter.upper()]) + else: + print(f'I do not know "{letter}".') + + +# -------------------------------------------------- +if __name__ == "__main__": + main() diff --git a/hagrid.txt b/hagrid.txt new file mode 100644 index 000000000..1c56337be --- /dev/null +++ b/hagrid.txt @@ -0,0 +1 @@ +I am what I am an' I'm not ashamed. diff --git a/out.txt b/out.txt new file mode 100644 index 000000000..e69de29bb From 84c1cfec1b47cc8f529c8be62c7d403e5d3afc4f Mon Sep 17 00:00:00 2001 From: opanther Date: Tue, 3 Jan 2023 16:37:47 +0000 Subject: [PATCH 6/8] Jump the five, working with dictionary --- 05_howler/howler.py | 64 ++++++++++++++++----------------------------- 06_wc/wc.py | 60 +++++++++++++++--------------------------- out.txt | 2 ++ 3 files changed, 46 insertions(+), 80 deletions(-) diff --git a/05_howler/howler.py b/05_howler/howler.py index c255d4ed8..da52d2531 100755 --- a/05_howler/howler.py +++ b/05_howler/howler.py @@ -2,71 +2,53 @@ """ Author : tomioredein Date : 2022-12-01 -Purpose: Rock the Casbah +Purpose: Working with files and STDOUT """ import argparse - +import os +import sys # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( - description="Rock the Casbah", + description="Howler (upper-cases input)", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) - parser.add_argument("positional", metavar="str", help="A positional argument") + parser.add_argument("text", metavar="text", type=str, help="Input string or file") parser.add_argument( - "-a", - "--arg", - help="A named string argument", + "-o", + "--outfile", + help="Output filename", metavar="str", type=str, default="", ) - - parser.add_argument( - "-i", - "--int", - help="A named integer argument", - metavar="int", - type=int, - default=0, - ) - - parser.add_argument( - "-f", - "--file", - help="A readable file", - metavar="FILE", - type=argparse.FileType("rt"), - default=None, - ) - - parser.add_argument("-o", "--on", help="A boolean flag", action="store_true") - - return parser.parse_args() + # Parse the command-line arguments into the variable args so that we can manually check the text argument. + args = parser.parse_args() + # Check if args.text is the name of an existing file. + if os.path.isfile(args.text): + # if so, overwrite the value of args.text with the results of reading the file Potential memory problem + args.text = open(args.text).read().rstrip() + # Return the arguments to the caller + return args # -------------------------------------------------- def main(): """Make a jazz noise here""" - + # Call get_args() to get the arguments to the program. args = get_args() - str_arg = args.arg - int_arg = args.int - file_arg = args.file - flag_arg = args.on - pos_arg = args.positional - - print(f'str_arg = "{str_arg}"') - print(f'int_arg = "{int_arg}"') - print('file_arg = "{}"'.format(file_arg.name if file_arg else "")) - print(f'flag_arg = "{flag_arg}"') - print(f'positional = "{pos_arg}"') + # use an if expression to choose either sys.stdout or a newly opened file handle to write the output. + out_fh = open(args.outfile, "wt") if args.outfile else sys.stdout + # Use the opened file handle to write the output converted to uppercase. + out_fh.write(args.text.upper() + "\n") + # Close the file handle + out_fh.close() # -------------------------------------------------- diff --git a/06_wc/wc.py b/06_wc/wc.py index cf78cffac..808abf3f4 100755 --- a/06_wc/wc.py +++ b/06_wc/wc.py @@ -2,10 +2,11 @@ """ Author : tomioredein Date : 2022-12-29 -Purpose: Rock the Casbah +Purpose: Emulate wc (word count) """ import argparse +import sys # -------------------------------------------------- @@ -13,41 +14,19 @@ def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( - description="Rock the Casbah", + description="Emulate wc (word count)", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) - parser.add_argument("positional", metavar="str", help="A positional argument") - parser.add_argument( - "-a", - "--arg", - help="A named string argument", - metavar="str", - type=str, - default="", - ) - - parser.add_argument( - "-i", - "--int", - help="A named integer argument", - metavar="int", - type=int, - default=0, - ) - - parser.add_argument( - "-f", - "--file", - help="A readable file", + "file", metavar="FILE", + nargs="*", + default=[sys.stdin], type=argparse.FileType("rt"), - default=None, + help="Input file(s)", ) - parser.add_argument("-o", "--on", help="A boolean flag", action="store_true") - return parser.parse_args() @@ -56,17 +35,20 @@ def main(): """Make a jazz noise here""" args = get_args() - str_arg = args.arg - int_arg = args.int - file_arg = args.file - flag_arg = args.on - pos_arg = args.positional - - print(f'str_arg = "{str_arg}"') - print(f'int_arg = "{int_arg}"') - print('file_arg = "{}"'.format(file_arg.name if file_arg else "")) - print(f'flag_arg = "{flag_arg}"') - print(f'positional = "{pos_arg}"') + total_lines, total_bytes, total_words = 0, 0, 0 + for fh in args.file: + num_lines, num_words, num_bytes = 0, 0, 0 + for line in fh: + num_lines += 1 + num_bytes += len(line) + num_words += len(line.split()) + + total_lines += num_lines + total_bytes += num_bytes + total_words += num_words + print(f"{num_lines:8}{num_words:8}{num_bytes:8} {fh.name}") + if len(args.file) > 1: + print(f"{total_lines:8}{total_words:8}{total_bytes:8} total") # -------------------------------------------------- diff --git a/out.txt b/out.txt index e69de29bb..1746bd0e2 100644 --- a/out.txt +++ b/out.txt @@ -0,0 +1,2 @@ +this is some text +this is some more text From 3cf43e4c97e2505d68692d7713abf7417672c584 Mon Sep 17 00:00:00 2001 From: opanther Date: Mon, 9 Jan 2023 18:49:43 +0000 Subject: [PATCH 7/8] chapter 8,9 --- 08_apples_and_bananas/apples.py | 74 ++++++++++++++++++++++++++++++++ 09_abuse/abuse.py | 76 +++++++++++++++++++++++++++++++++ 09_abuse/test.py | 28 ++++++------ 3 files changed, 164 insertions(+), 14 deletions(-) create mode 100755 08_apples_and_bananas/apples.py create mode 100755 09_abuse/abuse.py diff --git a/08_apples_and_bananas/apples.py b/08_apples_and_bananas/apples.py new file mode 100755 index 000000000..a26baa41b --- /dev/null +++ b/08_apples_and_bananas/apples.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +""" +Author : tomioredein +Date : 2023-01-04 +Purpose: Rock the Casbah +""" + +import argparse + + +# -------------------------------------------------- +def get_args(): + """Get command-line arguments""" + + parser = argparse.ArgumentParser( + description="Rock the Casbah", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + + parser.add_argument("positional", metavar="str", help="A positional argument") + + parser.add_argument( + "-a", + "--arg", + help="A named string argument", + metavar="str", + type=str, + default="", + ) + + parser.add_argument( + "-i", + "--int", + help="A named integer argument", + metavar="int", + type=int, + default=0, + ) + + parser.add_argument( + "-f", + "--file", + help="A readable file", + metavar="FILE", + type=argparse.FileType("rt"), + default=None, + ) + + parser.add_argument("-o", "--on", help="A boolean flag", action="store_true") + + return parser.parse_args() + + +# -------------------------------------------------- +def main(): + """Make a jazz noise here""" + + args = get_args() + str_arg = args.arg + int_arg = args.int + file_arg = args.file + flag_arg = args.on + pos_arg = args.positional + + print(f'str_arg = "{str_arg}"') + print(f'int_arg = "{int_arg}"') + print('file_arg = "{}"'.format(file_arg.name if file_arg else "")) + print(f'flag_arg = "{flag_arg}"') + print(f'positional = "{pos_arg}"') + + +# -------------------------------------------------- +if __name__ == "__main__": + main() diff --git a/09_abuse/abuse.py b/09_abuse/abuse.py new file mode 100755 index 000000000..928372bff --- /dev/null +++ b/09_abuse/abuse.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +""" +Author : tomioredein +Date : 2023-01-06 +Purpose: Heap Abuse +""" + +import argparse +import random + + +# -------------------------------------------------- +def get_args(): + """Get command-line arguments""" + + parser = argparse.ArgumentParser( + description="Heap abuse", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + + parser.add_argument( + "-a", + "--adjectives", + help="Number of adjectives", + metavar="adjectives", + default=2, + type=int, + ) + + parser.add_argument( + "-n", + "--number", + help="Number of insults", + metavar="insults", + default=3, + type=int, + ) + + parser.add_argument( + "-s", + "--seed", + help="Random seed", + metavar="seed", + default=None, + type=int, + ) + + args = parser.parse_args() + if args.adjectives < 1: + parser.error(f"--adjectives'{args.adjectives}' must be > 0") + if args.number < 1: + parser.error(f"--number'{args.number}' must be > 0") + return args + + +# -------------------------------------------------- +def main(): + """Make a jazz noise here""" + + args = get_args() + random.seed(args.seed) + + adjectives = """bankrupt base caterwauling corrupt cullionly detestable dishonest false filthsome filthy foolish foul gross + heedless indistinguishable infected insatiate irksome lascivious lecherous loathsome lubbery old peevish rascaly rotten + ruinous scurilous scurvy slanderous sodden-witted thin-faced toad-spotted unmannered vile wall-eyed""".strip().split() + nouns = """Judas Satan ape ass barbermonger beggar block boy braggart butt carbuncle coward coxcomb cur dandy degenerate fiend + fishmonger fool gull harpy jack jolthead knave liar lunatic maw milksop minion ratcatcher recreant rogue scold slave swine + traitor varlet villain worm""".strip().split() + for n in range(args.number): + adjs = ",".join(random.sample(adjectives, k=args.adjectives)) + print(f"you {adjs}, {random.choice(nouns)} !") + + +# -------------------------------------------------- +if __name__ == "__main__": + main() diff --git a/09_abuse/test.py b/09_abuse/test.py index ff31fc90a..5ab496901 100755 --- a/09_abuse/test.py +++ b/09_abuse/test.py @@ -7,7 +7,7 @@ import string from subprocess import getstatusoutput, getoutput -prg = './abuse.py' +prg = "./abuse.py" # -------------------------------------------------- @@ -21,8 +21,8 @@ def test_exists(): def test_usage(): """usage""" - for flag in ['-h', '--help']: - rv, out = getstatusoutput(f'{prg} {flag}') + for flag in ["-h", "--help"]: + rv, out = getstatusoutput(f"{prg} {flag}") assert rv == 0 assert re.match("usage", out, re.IGNORECASE) @@ -32,7 +32,7 @@ def test_bad_adjective_str(): """bad_adjectives""" bad = random_string() - rv, out = getstatusoutput(f'{prg} -a {bad}') + rv, out = getstatusoutput(f"{prg} -a {bad}") assert rv != 0 assert re.search(f"invalid int value: '{bad}'", out) @@ -42,7 +42,7 @@ def test_bad_adjective_num(): """bad_adjectives""" n = random.choice(range(-10, 0)) - rv, out = getstatusoutput(f'{prg} -a {n}') + rv, out = getstatusoutput(f"{prg} -a {n}") print(out) assert rv != 0 assert re.search(f'--adjectives "{n}" must be > 0', out) @@ -53,7 +53,7 @@ def test_bad_number_str(): """bad_number""" bad = random_string() - rv, out = getstatusoutput(f'{prg} -n {bad}') + rv, out = getstatusoutput(f"{prg} -n {bad}") assert rv != 0 assert re.search(f"invalid int value: '{bad}'", out) @@ -63,7 +63,7 @@ def test_bad_number_int(): """bad_number""" n = random.choice(range(-10, 0)) - rv, out = getstatusoutput(f'{prg} -n {n}') + rv, out = getstatusoutput(f"{prg} -n {n}") assert rv != 0 assert re.search(f'--number "{n}" must be > 0', out) @@ -73,7 +73,7 @@ def test_bad_seed(): """bad seed""" bad = random_string() - rv, out = getstatusoutput(f'{prg} -s {bad}') + rv, out = getstatusoutput(f"{prg} -s {bad}") assert rv != 0 assert re.search(f"invalid int value: '{bad}'", out) @@ -82,15 +82,15 @@ def test_bad_seed(): def test_01(): """test""" - out = getoutput(f'{prg} -s 1 -n 1') - assert out.strip() == 'You filthsome, cullionly fiend!' + out = getoutput(f"{prg} -s 1 -n 1") + assert out.strip() == "You filthsome, cullionly fiend!" # -------------------------------------------------- def test_02(): """test""" - out = getoutput(f'{prg} --seed 2') + out = getoutput(f"{prg} --seed 2") expected = """ You corrupt, detestable beggar! You peevish, foolish gull! @@ -103,7 +103,7 @@ def test_02(): def test_03(): """test""" - out = getoutput(f'{prg} -s 3 -n 5 -a 1') + out = getoutput(f"{prg} -s 3 -n 5 -a 1") expected = """ You infected villain! You vile braggart! @@ -118,7 +118,7 @@ def test_03(): def test_04(): """test""" - out = getoutput(f'{prg} --seed 4 --number 2 --adjectives 4') + out = getoutput(f"{prg} --seed 4 --number 2 --adjectives 4") expected = """ You infected, lecherous, dishonest, rotten recreant! You filthy, detestable, cullionly, base lunatic! @@ -130,4 +130,4 @@ def test_04(): def random_string(): """generate a random filename""" - return ''.join(random.choices(string.ascii_lowercase + string.digits, k=5)) + return "".join(random.choices(string.ascii_lowercase + string.digits, k=5)) From 9fea42647ce7aa0718b7f2ab7b365dc989cea164 Mon Sep 17 00:00:00 2001 From: opanther Date: Thu, 19 Jan 2023 15:32:04 +0000 Subject: [PATCH 8/8] chapter 10,11,12 --- 10_telephone/telephone.py | 74 +++++++++++++++++++++++ 11_bottles_of_beer/bottles.py | 74 +++++++++++++++++++++++ 12_ransom/ransom.py | 72 ++++++++++++++++++++++ 13_twelve_days/twelve_days.py | 110 ++++++++++++++++++++++++++++++++++ 4 files changed, 330 insertions(+) create mode 100755 10_telephone/telephone.py create mode 100755 11_bottles_of_beer/bottles.py create mode 100755 12_ransom/ransom.py create mode 100755 13_twelve_days/twelve_days.py diff --git a/10_telephone/telephone.py b/10_telephone/telephone.py new file mode 100755 index 000000000..c414d058e --- /dev/null +++ b/10_telephone/telephone.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +""" +Author : tomioredein +Date : 2023-01-11 +Purpose: Rock the Casbah +""" + +import argparse + + +# -------------------------------------------------- +def get_args(): + """Get command-line arguments""" + + parser = argparse.ArgumentParser( + description="Rock the Casbah", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + + parser.add_argument("positional", metavar="str", help="A positional argument") + + parser.add_argument( + "-a", + "--arg", + help="A named string argument", + metavar="str", + type=str, + default="", + ) + + parser.add_argument( + "-i", + "--int", + help="A named integer argument", + metavar="int", + type=int, + default=0, + ) + + parser.add_argument( + "-f", + "--file", + help="A readable file", + metavar="FILE", + type=argparse.FileType("rt"), + default=None, + ) + + parser.add_argument("-o", "--on", help="A boolean flag", action="store_true") + + return parser.parse_args() + + +# -------------------------------------------------- +def main(): + """Make a jazz noise here""" + + args = get_args() + str_arg = args.arg + int_arg = args.int + file_arg = args.file + flag_arg = args.on + pos_arg = args.positional + + print(f'str_arg = "{str_arg}"') + print(f'int_arg = "{int_arg}"') + print('file_arg = "{}"'.format(file_arg.name if file_arg else "")) + print(f'flag_arg = "{flag_arg}"') + print(f'positional = "{pos_arg}"') + + +# -------------------------------------------------- +if __name__ == "__main__": + main() diff --git a/11_bottles_of_beer/bottles.py b/11_bottles_of_beer/bottles.py new file mode 100755 index 000000000..8684aa739 --- /dev/null +++ b/11_bottles_of_beer/bottles.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +""" +Author : tomioredein +Date : 2023-01-12 +Purpose: Rock the Casbah +""" + +import argparse + + +# -------------------------------------------------- +def get_args(): + """Get command-line arguments""" + + parser = argparse.ArgumentParser( + description="Rock the Casbah", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + + parser.add_argument("positional", metavar="str", help="A positional argument") + + parser.add_argument( + "-a", + "--arg", + help="A named string argument", + metavar="str", + type=str, + default="", + ) + + parser.add_argument( + "-i", + "--int", + help="A named integer argument", + metavar="int", + type=int, + default=0, + ) + + parser.add_argument( + "-f", + "--file", + help="A readable file", + metavar="FILE", + type=argparse.FileType("rt"), + default=None, + ) + + parser.add_argument("-o", "--on", help="A boolean flag", action="store_true") + + return parser.parse_args() + + +# -------------------------------------------------- +def main(): + """Make a jazz noise here""" + + args = get_args() + str_arg = args.arg + int_arg = args.int + file_arg = args.file + flag_arg = args.on + pos_arg = args.positional + + print(f'str_arg = "{str_arg}"') + print(f'int_arg = "{int_arg}"') + print('file_arg = "{}"'.format(file_arg.name if file_arg else "")) + print(f'flag_arg = "{flag_arg}"') + print(f'positional = "{pos_arg}"') + + +# -------------------------------------------------- +if __name__ == "__main__": + main() diff --git a/12_ransom/ransom.py b/12_ransom/ransom.py new file mode 100755 index 000000000..ae7e2865d --- /dev/null +++ b/12_ransom/ransom.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +""" +Author : tomioredein +Date : 2023-01-16 +Purpose: Rock the Casbah +""" + +import argparse + + +# -------------------------------------------------- +def get_args(): + """Get command-line arguments""" + + parser = argparse.ArgumentParser( + description='Rock the Casbah', + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + + parser.add_argument('positional', + metavar='str', + help='A positional argument') + + parser.add_argument('-a', + '--arg', + help='A named string argument', + metavar='str', + type=str, + default='') + + parser.add_argument('-i', + '--int', + help='A named integer argument', + metavar='int', + type=int, + default=0) + + parser.add_argument('-f', + '--file', + help='A readable file', + metavar='FILE', + type=argparse.FileType('rt'), + default=None) + + parser.add_argument('-o', + '--on', + help='A boolean flag', + action='store_true') + + return parser.parse_args() + + +# -------------------------------------------------- +def main(): + """Make a jazz noise here""" + + args = get_args() + str_arg = args.arg + int_arg = args.int + file_arg = args.file + flag_arg = args.on + pos_arg = args.positional + + print(f'str_arg = "{str_arg}"') + print(f'int_arg = "{int_arg}"') + print('file_arg = "{}"'.format(file_arg.name if file_arg else '')) + print(f'flag_arg = "{flag_arg}"') + print(f'positional = "{pos_arg}"') + + +# -------------------------------------------------- +if __name__ == '__main__': + main() diff --git a/13_twelve_days/twelve_days.py b/13_twelve_days/twelve_days.py new file mode 100755 index 000000000..1c5d22346 --- /dev/null +++ b/13_twelve_days/twelve_days.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +""" +Author : tomioredein +Date : 2023-01-18 +Purpose: Twelve days of Christmas +""" + +import argparse +import sys + + +# -------------------------------------------------- +def get_args(): + """Get command-line arguments""" + + parser = argparse.ArgumentParser( + description="Twelve days of Christmas", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + + parser.add_argument( + "-o", + "--outfile", + help="Output filename", + metavar="file", + type=argparse.FileType('wt'), + default=sys.stdout, + ) + + parser.add_argument( + "-n", + "--num", + help="Number of days to sing", + metavar="days", + type=int, + default=12, + ) + + args = parser.parse_args() + + if not 1 <= args.num <= 12: + parser.error(f'--num "{args.num}" must be between 1 and 12 ') + + return args + + +# -------------------------------------------------- +def main(): + """Make a jazz noise here""" + + args = get_args() + verses = map(verse, range(1, args.num + 1)) + print('\n\n'.join(verses), file=args.outfile) + + +# -------------------------------------------------- +def verse(day): + """Create a verse""" + + ordinal = [ + 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', + 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth' + ] + + gifts = [ + 'A partridge in a pear tree.', + 'Two turtle doves,', + 'Three French hens,', + 'Four calling birds,', + 'Five gold rings,', + 'Six geese a laying,', + 'Seven swans a swimming,', + 'Eight maids a milking,', + 'Nine ladies dancing,', + 'Ten lords a leaping,', + 'Eleven pipers piping,', + 'Twelve drummers drumming,', + ] + + lines = [ + f'On the {ordinal[day - 1]} day of Christmas,', + 'My true love gave to me,' + ] + + lines.extend(reversed(gifts[:day])) + + if day > 1: + lines[-1] = 'And ' + lines[-1].lower() + + return '\n'.join(lines) + + +# -------------------------------------------------- +def test_verse(): + """Test verse""" + + assert verse(1) == '\n'.join([ + 'On the first day of Christmas,', 'My true love gave to me,', + 'A partridge in a pear tree.' + ]) + + assert verse(2) == '\n'.join([ + 'On the second day of Christmas,', 'My true love gave to me,', + 'Two turtle doves,', 'And a partridge in a pear tree.' + ]) + + +# -------------------------------------------------- +if __name__ == '__main__': + main()