aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <mohammad.anwar@yahoo.com>2021-10-23 09:36:05 +0100
committerMohammad S Anwar <mohammad.anwar@yahoo.com>2021-10-23 09:38:02 +0100
commit2a950d0800474d0745b527227ccbc9a33b0840a1 (patch)
tree7bdf9aee60e886ba7130f57126b9069589d94880
parentfa1806724d058c378f969160aac6267bfb454a31 (diff)
downloadperlweeklychallenge-club-2a950d0800474d0745b527227ccbc9a33b0840a1.tar.gz
perlweeklychallenge-club-2a950d0800474d0745b527227ccbc9a33b0840a1.tar.bz2
perlweeklychallenge-club-2a950d0800474d0745b527227ccbc9a33b0840a1.zip
- Added Python solution to "Middle 3-digits" task of week 135.
-rw-r--r--challenge-135/mohammad-anwar/python/ch-1.py58
1 files changed, 58 insertions, 0 deletions
diff --git a/challenge-135/mohammad-anwar/python/ch-1.py b/challenge-135/mohammad-anwar/python/ch-1.py
new file mode 100644
index 0000000000..7cbe66a9c3
--- /dev/null
+++ b/challenge-135/mohammad-anwar/python/ch-1.py
@@ -0,0 +1,58 @@
+#!/usr/bin/python3
+
+'''
+
+Week 135:
+
+ https://theweeklychallenge.org/blog/perl-weekly-challenge-135
+
+Task #1: Middle 3-digits
+
+ You are given an integer.
+
+ Write a script find out the middle 3-digits of the given integer, if possible otherwise throw sensible error.
+
+'''
+
+import sys, math, re, getopt
+
+def main(argv):
+ try:
+ opts, arg = getopt.getopt(argv, "hn:", ["number="])
+ except getopt.GetoptError:
+ print('ch-1.py -n <number>')
+ sys.exit(2)
+
+ for opt, arg in opts:
+ if opt == '-h':
+ print('ch-1.py -n <number>')
+ sys.exit()
+ elif opt in ("-n", "--number"):
+ number = arg
+
+ valid = re.compile('^\-?\d+$')
+ if valid.match(number):
+ num = abs(int(number))
+ size = int_size(num)
+
+ if size == 1:
+ print('ERROR: Too short')
+ sys.exit()
+
+ if size % 2 == 0:
+ print('ERROR: Even number of digits.')
+ sys.exit()
+
+ i = int(size / 2) - 1
+ s = str(num)
+
+ print(s[i:i+3])
+
+ else:
+ print('Invalid number')
+
+def int_size(n):
+ return 1 + math.floor(math.log10(n))
+
+if __name__ == "__main__":
+ main(sys.argv[1:])