Jes*_*irk 5 python python-itertools rust
在Python中,我可以执行以下操作:
from itertools import product
k = 3
for kmer in product("AGTC", repeat=k):
print(kmer)
Run Code Online (Sandbox Code Playgroud)
在Rust中,我可以k=3通过以下方式强制行为:
#[macro_use] extern crate itertools;
for kmer in iproduct!("AGTC".chars(), "AGTC".chars(), "AGTC".chars()){
println!("{:?}", kmer);
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我想要k=4或k=5怎么办?
小智 5
为任何 k 的任何类型编写适当的泛化将很困难,因为返回类型可能是任何大小的元组。由于您只想在 上工作String,所以更容易:playground
fn kproduct(seq: String, k: u32) -> Vec<String> {
match k {
0 => vec![],
1 => seq.chars().map(|c| c.to_string()).collect(),
2 => iproduct!(seq.chars(), seq.chars()).map(|(a, b)| format!("{}{}", a, b)).collect(),
_ => iproduct!(kproduct(seq.clone(), k - 1), seq.chars()).map(|(a, b)| format!("{}{}", a, b)).collect(),
}
}
Run Code Online (Sandbox Code Playgroud)
我在 4 年后回答这个问题,既因为接受的答案太复杂,又因为 Pythonitertools.product是一个通用函数(而接受的答案仅适用于Strings)。此外,请注意,kproduct接受的答案中定义的函数是递归的,并且Rust 不保证尾部调用优化。
使用第三方itertools crate,我们可以product_repeat通过两种方式定义函数:定义一个标准的顶级函数,或者ProductRepeat为所有 s 添加一个特征Iterator。
这是顶层函数:
use itertools::{Itertools, MultiProduct};
/// Rust version of Python's itertools.product().
/// It returns the cartesian product of the input iterables, and it is
/// semantically equivalent to `repeat` nested for loops.
///
/// # Arguments
///
/// * `it` - An iterator over a cloneable data structure
/// * `repeat` - Number of repetitions of the given iterator
pub fn product_repeat<I>(it: I, repeat: usize) -> MultiProduct<I>
where
I: Iterator + Clone,
I::Item: Clone {
std::iter::repeat(it)
.take(repeat)
.multi_cartesian_product()
}
Run Code Online (Sandbox Code Playgroud)
如果您更喜欢增强 Iterator 特性,则可以按如下方式进行:
pub trait ProductRepeat: Iterator + Clone
where Self::Item: Clone {
fn product_repeat(self, repeat: usize) -> MultiProduct<Self> {
std::iter::repeat(self)
.take(repeat)
.multi_cartesian_product()
}
}
impl<T: Iterator + Clone> ProductRepeat for T
where T::Item: Clone {}
Run Code Online (Sandbox Code Playgroud)
这是Rust 游乐场中的演示。
| 归档时间: |
|
| 查看次数: |
167 次 |
| 最近记录: |