In Rust, what is the correct way to repeat the Python repeat option in itertools.product?

In Python, I can do:

from itertools import product

k = 3
for kmer in product("AGTC", repeat=k):
    print(kmer)

In Rust, I can force the behavior k=3:

#[macro_use] extern crate itertools;

for kmer in iproduct!("AGTC".chars(), "AGTC".chars(), "AGTC".chars()){
    println!("{:?}", kmer);
}

But what if I wanted to k=4or k=5?

+4
source share
1 answer

Writing the right generalization for any type for any k would be difficult because the return type could be tuples of any size. Since you only want to work on String, it's pretty simple: a 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(),
    }
}
+3
source

Source: https://habr.com/ru/post/1677784/


All Articles