Python到C / C ++的转换 [英] Python to C/C++ conversion

查看:108
本文介绍了Python到C / C ++的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def readinput():
  n = int(input())     # Length
  for j in range(n):   
    nextnum = int(input())  # Read each value
    insequence.append(nextnum)
    best.append(0)     # Initialize best[k] for each position
  return

def solve():
  for j in range(len(insequence)):
    # Collect best[k] for values to left of j that divide insequence[j]
    prev = [ best[k] for k in range(j) if insequence[j]%insequence[k] == 0 ]
    if prev:
       best[j] = 1 + max(prev)
    else:
       best[j] = 1

insequence = []
best = []
readinput()
solve()
print(max(best))





什么我试过了:



我不知道从哪里开始。请帮助



What I have tried:

I don't know where to start. please help

推荐答案

C ++非常富有表现力:

C++ is quite expressive:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> readinput()
{
  size_t n;
  cin >> n; 
  vector<int> v(n);
  for (auto & x : v)
    cin >> x;
  return v;
}
vector <int> solve(const vector<int> & inseq)
{
  auto size = inseq.size();
  vector<int> best(size);
  for (size_t j=0; j<size; ++j)
  {
    vector<int> prev;
    for (size_t k=0; k<j; ++k)
      if ( inseq[j] % inseq[k] == 0)
        prev.push_back(best[k]);
    best[j] = prev.size() > 0 ? 1 + *max_element(prev.begin(), prev.end()) : 1;
  }
  return best;
}

int main()
{
  auto inseq = readinput();
  auto best = solve(inseq);
  cout << *max_element(best.begin(), best.end()) << endl;
}


算了吧。 Python与C的区别太大,无法简化任何转换。 Python的许多功能在C中没有直接的等价物,因此您需要设计自己的替代品。只需使用程序的设计细节就可以用C语言编写。
Forget it. Python is too different from C to make any conversion simple. Many of the features of Python have no direct equivalent in C so you would need to design your own alternatives. Just use the design details of the program to write it in C.


这篇关于Python到C / C ++的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆