【发布时间】:2021-12-12 15:05:47
【问题描述】:
我正在尝试将 python 函数转换为 c++,但没有成功。有人可以帮我吗?
python 函数接收一个字符串 S 和 2 个整数(fragment_size 和 jump)作为输入。 该函数的目的是将字符串 S 切成长度等于输入给定的第一个整数 (fragment_size) 的多个片段,并以等于输入给定的第二个整数的步长遍历整个字符串 S (jump )。
import sys
# First we read the input and asign it to 3 different variables
S = sys.stdin.readline().strip()
fragment_size = sys.stdin.readline().strip()
jump = sys.stdin.readline().strip()
def window(S, fragment_size, jump):
word = S[:fragment_size]
if len(word)< fragment_size:
return []
else:
return [word] + window(S[jump:], fragment_size, jump)
# We check that S is not an empty string and that fragment_size and jump are bigger than 0.
if len(S) > 0 and int(fragment_size) > 0 and int(jump) > 0:
# We print the results
for i in window(S, int(fragment_size), int(jump)):
print(i)
例如: 输入 ACGGTAGACCT 3 1
输出 ACG CGG GGT 侠盗猎车手 标签 AGA 广汽 ACC 色温
示例 2: 输入 ACGGTAGACCT 3 3
输出 ACG 侠盗猎车手 广汽
我知道如何在 c++ 中在窗口函数中返回一个字符串来解决这个问题。但我确实需要返回一个列表,就像我在 python 程序中返回的那样。
现在,我有这个 C++ 代码:
# include <iostream>
# include <vector>
# include <string>
using namespace std;
vector<string> window_list(string word, vector<vector<string>>& outp_list){
outp_list.push_back(word);
}
vector<string> window(string s, int len_suf, int jump){
string word;
vector<vector<string>> outp_list;
word = s.substr(0, len_suf);
if(word.length() < len_suf){
return vector<string> window_list();
}
else {
window_list(word, outp_list);
return window(s.substr(jump), len_suf, jump);
}
}
int main(){
// We define the variables
string s;
int len_suf, jump;
// We read the input and store it to 3 different variables
cin >> s;
cin >> len_suf;
cin >> jump;
// We print the result
vector<string> ans = window(s, len_suf, jump);
for(auto& x: ans){
cout << x << endl;
}
return 0;
}
谢谢!
【问题讨论】:
-
你能告诉我们你到目前为止做了什么吗?分享您的代码。
标签: python c++ c++11 recursion