LoginSignup
7
6

More than 3 years have passed since last update.

Pythonで代入しながら結果をreturnしたい

Posted at

競技プログラミングで、メモ化再帰のコードを書く際によく出てくる書き方。
C++だと、returnで代入しながらreturnできる
こんな感じのやつ↓

bool func(int i, int x) {
    ...

    return dp[i][x] = 0;
}

が、Pythonだと以下のように書くと怒られる

def func(i, x):
    ...
    return dp[i][x] = 0

returnのあとには文を指定できない(式じゃないとだめ)なのかと思い、いろいろ調べて見たところ…

代入式

結論から言うとPython 3.8から導入される「代入式」を使えば書けそう。

def func(i, x):
    ...
    return dp[i][x] := 0

参考

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6