0

Is there a faster or shorter way of writing the following code to aviod calculating f(x) twice without defining another variable?

# could be any function or condition
if f(x) == 0:
    print(f(x))

# with additional variable
y = f(x)
if y == 0:
    print(y)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Christian
  • 124
  • 6

3 Answers3

4

The walrus operator would save you an extra line (but not the assignment of y).

if (y := f(x)) == 0:
    print(y)
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • This is not actually shorter if you put it all on one line, because the `():` are longer than the newline that's saved. – Barmar Sep 10 '21 at 16:29
  • @Barmar But if you put it all in one line someone's gonna PEP8 you. – timgeb Sep 10 '21 at 16:30
  • 1
    True, but the OP seems to be looking for a one-liner, and he also asked how to do it "without defining another variable". I'm not sure why he accepted this, since it doesn't seem to address either of his wishes. – Barmar Sep 10 '21 at 16:33
  • @Barmar sometimes OPs don't know what they should actually want before they see it, eh. – timgeb Sep 10 '21 at 16:34
0

Define a print_if_0() function, and use that where you need it.

def print_if_0(n):
    if n == 0:
        print(n)

print_if_0(f(x))

You can generalize it to any test:

def print_if(f, val):
    if f(val):
        print(val)

print_if(lambda x: x == 0, f(x))
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Use lru_cache to cache the results of f(x).

from functools import lru_cache

@lru_cache
def f(x):
    ...
gold_cy
  • 13,648
  • 3
  • 23
  • 45