Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with itertools.product and lists in python 3

I'm trying to create a possible list of codons given a protein sequence.

Basically, the script i'm trying to create will process a given string input and outputs a possible combinations of another set of strings the input represents.

For example, the character 'F' represents either 'UUU' or 'UUC'; the character 'I' represents either 'AUU', 'AUC', or 'AUA'.

Given the input 'FI', the script I'm trying to create should output: 'UUUAUU', 'UUUAUC', 'UUUAUA', 'UUCAUU', 'UUCAUC', and 'UUCAUA'.

I'm currently stuck with this code:

import itertools

F = ['UUU', 'UUC']
I = ['AUU', 'AUC', 'AUA']

seq, pool = 'FI', []

for i in seq:
   pool.append(eval(i))

for n in itertools.product(pool):
   print(n)

It works when I replace pool in itertools.product with pool[0], pool[1]. But I can't figure out how to make it work so that the user can input a string with more than 2 character (i.e. not to make it hard-coded).

Thanks in advance for the help!

like image 892
bow Avatar asked Feb 24 '10 10:02

bow


People also ask

How do I use Itertools in Python 3?

The itertools. combinations() function takes two arguments—an iterable inputs and a positive integer n —and produces an iterator over tuples of all combinations of n elements in inputs . >>> list(it. combinations(bills, 3)) [(20, 20, 20), (20, 20, 10), (20, 20, 10), ... ]

What does product () do in Python?

product() is used to find the cartesian product from the given iterator, output is lexicographic ordered. The itertools. product() can used in two different ways: itertools.

How do you create a Cartesian product of two lists in Python?

Practical Data Science using Python As we know if two lists are like (a, b) and (c, d) then the Cartesian product will be {(a, c), (a, d), (b, c), (b, d)}. To do this we shall use itertools library and use the product() function present in this library. The returned value of this function is an iterator.

What Does product do in Itertools?

The product() method of the itertools module returns the cartesian product of the input iterables. The method takes an optional argument called repeat , which when used returns the cartesian product of the iterable with itself for the number of times specified in the repeat parameter.


1 Answers

You can use *pool to "unpack" the list when calling product():

for n in itertools.product(*pool):
   print(n)

This syntax expands the list pool into separate positional parameters.

like image 141
sth Avatar answered Sep 23 '22 03:09

sth