I'm embarrassed I spent so much time on this seemingly simple but tricky coding exercise.
The task is this: input is various strings - digits, characters, non-English characters, e.g. some could be Cyrillic. The input must be split into words and then each word must be interpreted numerically if possible. It should handle actual digits from 1 to 6 as valid numbers. All others should be printed as is.
Valid input includes positive, int or float type numbers 1 to 6, such as the following:
- 1,2,3,4,5,6
- +1, +2, ... , +6
- 1.0, 2.0,... 6.0
- any scientific notation that represent numbers 1 to 6.
if number is 1 - print "rule1" , 2- "rule2" etc.
Special case is if input number can be interpreted as 0, or any other variation of 0: .0 , 0.0000 or 0.e00. It prints all 6 - "rule1, rule2,.... rule6".
Invalid input includes negative numbers, they should be printed as-is: -1 prints '-1', -2 prints -2.
- any digits in scientific notation that are not in [1 .. 6] should be printed as is.
- any single char or string, English and non-English (like dot) is printed as-is; 'nine' is printed 'nine' and "ывъхзъх" is printed "ывъхзъх".
Sample input:
1.0 03
+5
2.0e0
+.4e1
6.E+00
20e-1 2e1 2ва . 1e-307
expected output:
rule1
rule3
rule5
rule2
rule4
rule6
rule2
2e1
2ва
.
1e-307
Here is my code. I'm looking to make it more elegant.
from math import modf
import fileinput
rule1 = 'rule1'
rule2 = 'rule2'
rule3 = 'rule3'
rule4 = 'rule4'
rule5 = 'rule5'
rule6 = 'rule6'
def print_rule(n):
if n == 1:
print(rule1)
elif n == 2:
print(rule2)
elif n == 3:
print(rule3)
elif n == 4:
print(rule4)
elif n == 5:
print(rule5)
elif n == 6:
print(rule6)
def print_all():
print(rule1)
print(rule2)
print(rule3)
print(rule4)
print(rule5)
print(rule6)
def get_num(s):
try:
s = int(s)
if s == 0:
print_all()
elif s in [1, 2, 3, 4, 5, 6]:
print_rule(s)
elif s < 1 or s > 6:
print(s)
except ValueError:
try:
saved = s
s = float(s)
if s == 0:
print_all()
elif s < 1 or s > 6:
print(saved)
else:
s = float(s)
s = check_float(s)
if s == 0:
print_all()
elif s in [1, 2, 3, 4, 5, 6]:
print_rule(s)
else:
print(s)
except ValueError:
print(s)
def check_float(n):
frac, _ = modf(n)
if frac != 0:
return n
else:
return n
def test2():
for line in fileinput.input():
line = line.strip().split()
for item in line:
get_num(item)
if __name__ == "__main__":
test2()