スキップしてメイン コンテンツに移動

投稿

注目

その数式、プログラムできますか? list2-1

c++ のソースをpythonに移植 int multiply0(int n, int a) { if (n == 1) rturn a; return multiply0(n - 1, a) + a; } c++ のソースをpythonに移植したい 以下がC++の再帰的な乗算関数 multiply0 をPythonに移植したものです。 元のC++コード(修正前のもの) C++ int multiply0(int n, int a) { if (n == 1) rturn a; // ← ここはtypo(returnのはず) return multiply0(n - 1, a) + a; } Pythonへの移植(自然な書き方) Python def multiply0(n: int, a: int) -> int: if n == 1: return a return multiply0(n - 1, a) + a もっとPythonらしい書き方(おすすめ) Python def multiply(n: int, a: int) -> int: """n × a を再帰で計算する(ただし非効率)""" if n == 1: return a if n == 0: return 0 return multiply(n - 1, a) + a # 使い方例 print(multiply(5, 3)) # 15 print(multiply(10, 7)) # 70 print(multiply(4, 100)) # 400 さらに短く書くことも可能(Pythonらしい書き方) Python def mul(n: int, a: int) -> int: return a if n == 1 else mul(n-1, a) + a 注意点 元のC++コードは nが0以下 の場合を考慮していないので、無限再帰やスタックオーバー...

最新の投稿

Hellscape Mexico; US Military Mission Underway to Rescue Trapped US Citizens

White House Source: Major SOTU Announcement Incoming

Trump Calls for JAG Probe into Supreme Court “Betrayal” Over Global Tariffs

Red Hats Splinter Group Busted in Daring White House Plot to Expose “Imposter” Trump

White Hats Denied Permission to Apprehend “Seditious Six”

Suicide at GITMO

White Hats Sour on Bondi: “Cover-up Artist”

JAG Hangs Former Defense Secretary Chuck Hagel

Exclusive: Delta Force Stopped Trump Assassination in Davos

White Hats Want the Epstein Files in Full