我正在嘗試將 python 函式轉換為 C ,但沒有成功。有人能幫我嗎?
python 函式接收一個字串 S 和 2 個整數(fragment_size 和 jump)作為輸入。此函式的目的是將字串 S 切成長度等于輸入給定的第一個整數 (fragment_size) 的多個片段,并以等于輸入給定的第二個整數的步長遍歷整個字串 S(跳轉)。
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):
for i in range(0, len(S), jump):
word = S[i:i 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 GTA TAG AGA GAC ACC CCT
示例 2: 輸入 ACGGTAGACCT 3 3
輸出 ACG GTA GAC
謝謝!
uj5u.com熱心網友回復:
使用string資料型別,您可以輕松實作它。[:]您可以使用以下substr方法代替 python運算子:
#include <iostream>
#include <string.h>
using namespace std;
string S = "";
int fragment_size = 0;
int jump = 0;
string window(string s) {
if (s.length() < fragment_size)
return "";
else
return s.substr(0, fragment_size) " " window(s.substr(jump));
}
int main(int argc, char *argv[]) {
cin >> S;
cin >> fragment_size;
cin >> jump;
if (S.length() && fragment_size > 0 && jump > 0) {
cout << endl
<< window(S);
}
return 0;
}
此外,在您的window函式中,您有一個不需要的額外 for 回圈,因為您在第一次迭代后回傳一個值。
uj5u.com熱心網友回復:
它可以完成這項作業,但由于我不是很喜歡 C Alexandros Palacios 方法可能會更好。這只是對 Python 代碼的粗略翻譯。
#include <strings.h>
#include <iostream>
#include <vector>
std::string window(std::string S, int fragment_size, int jump) {
for (int i = 0; i <= S.length(); jump) {
std::string word = S.substr(i, i fragment_size);
if (word.length() < fragment_size) {
return "";
}
else {
return word " " window(S.substr(jump, S.length()-1), fragment_size, jump);
}
}
}
int main(int argc, char const *argv[])
{
std::string S;
std::cout << "Enter DNA sequence: ";
std::cin >> S;
int fragment_size;
std::cout << "Enter fragment size: ";
std::cin >> fragment_size;
int jump;
std::cout << "Enter jump size: ";
std::cin >> jump;
std::vector<std::string> data;
std::string result;
if (S.length() > 0 && fragment_size > 0 && jump > 0) {
result = window(S, fragment_size, jump);
} else {
return 1;
}
size_t pos;
std::string delimiter = " ";
while ((pos = result.find(delimiter)) != std::string::npos) {
data.push_back(result.substr(0, pos));
result.erase(0, pos delimiter.length());
}
for (const auto &str : data) {
std::cout << str << " ";
}
std::cout << std::endl;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/339717.html
上一篇:具有可變數量引數的建構式
下一篇:std::vector和移動語意
