From 9f83fe38e24a005d07ee31c0c53582f3eefbc9e5 Mon Sep 17 00:00:00 2001 From: Paulo Custodio Date: Thu, 23 Dec 2021 14:31:24 +0000 Subject: Add Perl and Python solutions to challenge 032 --- challenge-032/paulo-custodio/python/ch-1.py | 51 +++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 challenge-032/paulo-custodio/python/ch-1.py (limited to 'challenge-032/paulo-custodio/python/ch-1.py') diff --git a/challenge-032/paulo-custodio/python/ch-1.py b/challenge-032/paulo-custodio/python/ch-1.py new file mode 100644 index 0000000000..2a600a8112 --- /dev/null +++ b/challenge-032/paulo-custodio/python/ch-1.py @@ -0,0 +1,51 @@ +#!/usr/bin/python3 + +# Challenge 032 +# +# Task #1 +# Contributed by Neil Bowers +# Count instances +# Create a script that either reads standard input or one or more files +# specified on the command-line. Count the number of times and then print a +# summary, sorted by the count of each entry. +# +# So with the following input in file example.txt +# +# apple +# banana +# apple +# cherry +# cherry +# apple +# the script would display something like: +# +# apple 3 +# cherry 2 +# banana 1 +# For extra credit, add a -csv option to your script, which would generate: +# +# apple,3 +# banana,1 +# cherry,2 + +import fileinput +import sys + +# command line options +sep = "\t" +if len(sys.argv)>1 and sys.argv[1]=="-csv": + sys.argv.pop(1) + sep = "," + +# count instances +count = {} +for line in fileinput.input(): + word = line.strip() + if word in count: + count[word] += 1 + else: + count[word] = 1 + +# output +for key in sorted(count): + print(f"{key}{sep}{count[key]}") -- cgit From ce5bd2dd1a3159107febe4b9eb488a071bc601f5 Mon Sep 17 00:00:00 2001 From: Paulo Custodio Date: Thu, 23 Dec 2021 14:33:04 +0000 Subject: Whitespace --- challenge-032/paulo-custodio/python/ch-1.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'challenge-032/paulo-custodio/python/ch-1.py') diff --git a/challenge-032/paulo-custodio/python/ch-1.py b/challenge-032/paulo-custodio/python/ch-1.py index 2a600a8112..717d0f8ded 100644 --- a/challenge-032/paulo-custodio/python/ch-1.py +++ b/challenge-032/paulo-custodio/python/ch-1.py @@ -8,9 +8,9 @@ # Create a script that either reads standard input or one or more files # specified on the command-line. Count the number of times and then print a # summary, sorted by the count of each entry. -# +# # So with the following input in file example.txt -# +# # apple # banana # apple @@ -18,12 +18,12 @@ # cherry # apple # the script would display something like: -# +# # apple 3 # cherry 2 # banana 1 # For extra credit, add a -csv option to your script, which would generate: -# +# # apple,3 # banana,1 # cherry,2 -- cgit