Home > other >  How can i return a string based on an integer without "if" or Lists or Dictionary in pytho
How can i return a string based on an integer without "if" or Lists or Dictionary in pytho

Time:10-31

This is an assignment for college. I cant use if statements nor if nor Dictionary... (Lists, etc)

I have to return the verbose form of remainder of any number by 5. I mean something like this

14%5 = 4 and I have to return string "Four"
15%5 = 0 --> "Zero"

I cant use any modules either.

this might be a silly, but I have been thinking on this for about 4 days and so far no solution

CodePudding user response:

This seems like a crappy assignment that is asking to solve the problem in the wrong way. It is also not 100% clear what is and is not "allowed".

In any case, here are six crappy ways to solve this problem. Feel free to reject any that are too "list dependent" as it is was not 100% clear if using them is allowed.

test_value = 14%5

##----------------
## Use the value as an index into a list
##----------------
print(["zero","one","two","three","four"][test_value])
##----------------

##----------------
## Use the value as an index into a string
##----------------
print("zero one  two  threefour "[test_value*5: test_value*5 5].strip())
##----------------

##----------------
## Use the value to select the correct variable
##----------------
v0 = "zero"
v1 = "one"
v2 = "two"
v3 = "three"
v4 = "four"
print(eval(f"v{test_value}"))
##----------------

##----------------
## Use the value to do replacements
##----------------
print(
    str(test_value)
        .replace("0", "zero")
        .replace("1", "one")
        .replace("2", "two")
        .replace("3", "three")
        .replace("4", "four"))
##----------------

##----------------
## Use the value and some logic and string manipulation
##----------------
print(
    str((test_value == 0 and "zero") or "")  
    str((test_value == 1 and "one") or "")  
    str((test_value == 2 and "two") or "")  
    str((test_value == 3 and "three") or "")  
    str((test_value == 4 and "four") or "")
)
##----------------

##----------------
## simpler version of above
##----------------
print(
    (test_value == 0 and "zero") or
    (test_value == 1 and "one") or
    (test_value == 2 and "two") or
    (test_value == 3 and "three") or
    (test_value == 4 and "four")
)
##----------------

Each will give you:

four
  • Related