# Function that returns 1 for all numbers equal to or above 1 [closed]

What's a function (intended to use in a Python program) that returns 1 for all numbers that are >= 1 and 0 for all numbers that are < 1?

It should be expressed without using if, ternary/conditional operators, booleans or list comprehension.

Example:

>>> f(0)
0
>>> f(1)
1
>>> f(-0.3)
0
>>> f(999)
1
>>> f(0.9)
0

• Actually, how did you even come up with the super verbose version in the first place... (protip: math notation is rarely the conventional way to do it in programming since programming allows a lot more freedom) – somebody May 24 '18 at 7:44
• At some SE forums it's considered a bit unfair to add restrictions to a question after some answers were given, as this may render those answers incorrect or, even worse, off-topic. – CiaPan May 24 '18 at 8:51
• I agree, and flagged this question for moving it to codegolf.stackexchange.com. – Alexander May 24 '18 at 9:42
• (@Alexander - this question would not be welcome on PPCG as-is, for exactly the same reason it's a problem here, except that PPCG by default assumes the "best answer" criteria is "shortest code". I'm not sure that's at all what you want. In any event, you'd have to improve it for it to be migratable: just asking for a "better" function is entirely too broad.) – Rubio May 24 '18 at 9:48
• If you want to ask this over PPCG, I would suggest using the sandbox first. You may also be able to get feedback at its chat room. – EKons May 24 '18 at 10:45

def f(a): return abs(math.floor(a-1)+0.5)/(math.floor(a-1)+0.5)/2 + 0.5

Try it online!

if you don't need your function to be defined for the input 1, you can have it shorter

def f(a): return abs(a-1)/(a-1)/2 + 0.5

By the way, you should put your question on CodeGolf SE, you would have much better results

• This solution works great here. Good job on creating a relatively small expression from simple components! – Alexander May 24 '18 at 8:15

Since you asked for Python code...

def f(x):
return int(x >= 1)


UPDATE: OP added a restriction on not using if, booleans, list comprehension or ternary/conditional expressions. It is however, still possible to abstract these conditions away with functions such as...

import numpy as np

def f(x):
return np.heaviside(x-1, 1)


The absolute function in OP's suggested answer relies just as much on abstracting the if statement away.

• The solution after the update works great here, I didn't know about that numpy function. Thanks! – Alexander May 24 '18 at 8:13

In Python there is

a conditional expression a if condition else b
(see Does Python have a ternary conditional operator? at StackOverflow)

so you can simply

    def f(x):
return 1 if x >= 1 else 0