python – how to refactor this simple but tricky input task?

I’m embarassed i spent so much time on this seemingly simple but tricky coding exercise.

The task is this: input is various numbers.

The only valid numbers are :

  • 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.

If input number is 0 or .0 or 0.e00 it prints all 6 – “rule1, rule2,…. rule6”

  • Negative numbers should simply be printed as-is: -1 prints ‘-1’
  • any digits in scientific notation that are not in (1 .. 6) should be printed as is.
  • any char like dot is printed as-is – ‘nine’ is printed ‘nine’

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 – how to refactor it , more elegant way?:

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()