【解決方法】C++ コードを Python に変換する方法

プログラミングQA


C++
// Example program
#include <iostream>
#include <string>
using namespace std;

  void findMultiples( int i ,int n){
      int count=0;
  for( i ; i <= n; i++)
    if(i % 3 == 0 ){
    count++;
      cout << i<<"  ";
      if(count==5)
      cout<<endl;
 }
}

int="" main()="" {
="" int="" x;
="" y;
="" cin="">>x>>y;
  findMultiples(x,y);

  return 0;
}

<pre>// Example program
#include <iostream>
#include <string>
using namespace std;

  void findMultiples( int i ,int n){
      int count=0;
  for( i ; i <= n; i++)
    if(i % 3 == 0 ){
    count++;
      cout << i<<"  ";
      if(count==5)
      cout<<endl;
    }
}

int main() {
    int x;
    int y;
    cin>>x>>y;
  findMultiples(x,y);

  return 0;
}

私が試したこと:

C++
// Example program
#include <iostream>
#include <string>
using namespace std;

  void findMultiples( int i ,int n){
      int count=0;
  for( i ; i <= n; i++)
    if(i % 3 == 0 ){
    count++;
      cout << i<<"  ";
      if(count==5)
      cout<<endl;
    }
}

int main() {
    int x;
    int y;
    cin>>x>>y;
  findMultiples(x,y);

  return 0;
}

解決策 1

その C コードには複雑なことは何もないので、変換にそれほど時間はかかりません。 見る Python チュートリアル — Python 3.7.10 ドキュメント[^] 助けを求めて。

解決策 2

良い…

CコードをPythonに変換したい理由がわかりません…

CP QA フォーラムの主なルールは、質問する前に Google を使用することです。 だから、それを使用してください!

これを読むことをお勧めします:
ctopy(1): クイック/ダーティ C から Python へのトランスレータ) – Linux man ページ[^]
Python からの C 関数の呼び出し – JournalDev[^]

Richard MacCutchan が述べたように、上記のコードが何をするかを理解していれば、コンバーターなしで Python で書くことができます。

解決策 3

洞察を得るために、要件と元のソース コード ロジックを明確に理解しておく方がよい場合もあります。

場合によっては、要件と元のソース コードのロジックを理解して、ターゲット言語への適切な変換を実行する方がよい場合があります。

場合によっては、要件と元のソース コード ロジックを理解したほうがよい場合があります。これにより、ジャンクを捨てて、ターゲット言語を使用してプログラムを最初からやり直すことができます。

Python
def find_multiples_of_3_in_range( first, last ):
  if last < first:
    return 0
  frem = first % 3
  lrem = last % 3

  if frem != 0:
   first += (3 - frem)

  last -= lrem

  return (last -first)//3 + 1



def main():
  first = int(input("insert the starting number of the range "))
  last = int(input("insert the last number of the range "))
  multiples = find_multiples_of_3_in_range(first, last)
  print("thre are {} multiples of 3 in the given range".format(multiples))

main()

解決策 12

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int,int> ii;
typedef unsigned long long ull;

#define X first
#define Y second
#define pb push_back
#define mp make_pair
#define ep emplace_back
#define EL printf("\n")
#define sz(A) (int) A.size()
#define FOR(i,l,r) for (int i=l;i<=r;i++)
#define FOD(i,r,l) for (int i=r;i>=l;i--)
#define fillchar(a,x) memset(a, x, sizeof (a))
#define faster ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);

int     a,b,c,res;

int main() {
//  freopen("INP.TXT", "r", stdin);
//  freopen("OUT.TXT", "w", stdout);

	while (scanf("%d",&a) == 1) {
		scanf("%d%d",&b,&c);
		printf("%d\n",max(b-a-1,c-b-1));
	}

	return 0;
}

コメント

タイトルとURLをコピーしました