質問

Given the following Python function (ignoring its shortcomings):

def adjust_year(year):
  return year > 2000 and year - 2000 or year - 1900

If I change it to instead be:

def adjust_year(year):
  return year - 2000 if year > 2000 else year - 1900

Will the behavior be equivalent or have I changed it in some subtle way?

役に立ちましたか?

解決

They are indeed equivalent, but the conditional expression variation is preferred.

Your expression narrowly avoids the typical and ... or pitfall where the middle expression evaluates to a falsy value (year >= 2000 and year - 2000 or year - 1900 and year = 2000 will result in 100).

他のヒント

There are several ways to tackle this. One is to logically analyse both versions; the other is to use brute force and compare the results for every valid input:

def adjust_year_1(year):
  return year > 2000 and year - 2000 or year - 1900

def adjust_year_2(year):
  return year - 2000 if year > 2000 else year - 1900

for y in range(-4000, 4000):
  if adjust_year_1(y) != adjust_year_2(y):
    print y, adjust_year_1(y), adjust_year_2(y)

This doesn't print anything, demonstrating that the functions are indeed equivalent for years between -4000 and 4000 (it's easy to see that they are also equivalent for inputs outside this range).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top