Python Forum
Python for loops giving error
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python for loops giving error
#1
Dear all,

I am new to python programming. I wrote a code, but this code works partially. So what I basically did is writing a dictionary with keys and values. Then writing code to read a file and append all the values from the dictionary that are equivalent to the sequences present in the file.
This works and then I wrote a code to multiply all the values of the list and printing the answers. But this is where I get stuck.
Can someone help me to improve my code so that the end result can be printed?

aa_code = {
    'A': 4, 'C': 2, 'D': 2, 'E': 2, 'F': 2,
    'G': 4, 'H': 2, 'I': 3, 'K': 2, 'L': 6, 
    'M': 1, 'N': 2, 'P': 4, 'Q': 2, 'R': 6, 
    'S': 6, 'T': 4, 'V': 4, 'W': 1, 'Y': 2,
}# this is the dict
from Bio import SeqIO
for protein_seq in SeqIO.parse("protein.fasta","fasta"):
    for i in list(protein_seq):
        combinations = list()
        for value in list(protein_seq):
                combinations.append(aa_code[value])
    print(combinations)# this is the code to get values from the dictionary equivalent to sequence in protein file
answers were:
Output:
[4, 2, 2, 6] [2, 2, 2, 4, 4] [6, 4, 2, 4] [6, 1, 6, 1, 3, 2, 2, 4, 2, 2, 2] [2, 2, 4, 4, 4, 1, 4, 2, 2, 4, 2]
These answers were right as protein sequences were something like this:
VFHL
YKDTT
RTKT
RMLMIDYVCFQ
DKGTPMAEQTY

Then I tried to multiply all the list elements together and I expected to get something like this:
96, 128, 192, 13824, 32768
But my code doesn't work. I tried it like this:

import functools
from Bio import SeqIO
for protein_seq in SeqIO.parse("protein.fasta","fasta"):
    for i in list(protein_seq):
        combinations = list()
        for value in list(protein_seq):
                combinations.append(aa_code[value])
    print(list(combinations))
           for i in list(combinations):
             new_value = list()
        print(functools.reduce(lambda a,b: a*b,(list(combinations[new_value])
So I imported functools so that I can use the functool to reduce or multiply all the elements in the lists. But I am getting error Because my code is not able to recruit all the lists from the list(combinations).
Please help mee!!
Reply
#2
I am confused, do you want to multiply every number by the same constant or multiply them with a corresponding number in another list?

If you want to do the second, don't use functools.
Do this:
lista = [1, 2, 3, 4]
listb = [2, 3, 4, 5]
print([a*b for a,b in zip(lista,listb)])
would give:
Output:
[2, 6, 12, 20]
Reply
#3
No, I just want to multiply every single value inside the list with each other.
For example [4,2,2,6] => gives 96 as answer. And for that, I introduce the function tool and reduce to multiply all the values.
But what I really want to do is read the whole thing as one single code and get the answers. And the possible answers are given above such as 96, 128...
Reply
#4
(Jan-07-2019, 10:56 PM)Petrus Wrote: No, I just want to multiply every single value inside the list with each other.

Two possible ways to achieve that below. It is recommended to keep what you do and how you do separate. Therefore functions are used:

# without any import

def sequence_product(sequence):
    """Return sequence elements product; if empty return zero."""
    
    if not sequence:
        return 0
    else:
        total = 1
        for el in sequence:
            total *= el
        return total

# with reduce and mul

from functools import reduce
from operator import mul

def sequence_product(sequence):
    """Return sequence elements product; if empty return zero."""

    if not sequence:
        return 0
    else:
        return reduce(mul, sequence)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
(Jan-08-2019, 05:37 AM)perfringo Wrote:
(Jan-07-2019, 10:56 PM)Petrus Wrote: No, I just want to multiply every single value inside the list with each other.

Two possible ways to achieve that below. It is recommended to keep what you do and how you do separate. Therefore functions are used:

# without any import

def sequence_product(sequence):
    """Return sequence elements product; if empty return zero."""
    
    if not sequence:
        return 0
    else:
        total = 1
        for el in sequence:
            total *= el
        return total

# with reduce and mul

from functools import reduce
from operator import mul

def sequence_product(sequence):
    """Return sequence elements product; if empty return zero."""

    if not sequence:
        return 0
    else:
        return reduce(mul, sequence)

But the question remains I don't know how to glue this code with other code containing the combinations like [4,2,2,6]and so on. Because at the end of the day I am trying to write a function that can read the combinations and multiply all the numbers inside the list.
Only 1 function that can read sequences, append the values from a dictionary (which already works) and the combinations should multiply and give answers like 96 and so on.
Reply
#6
Can please someone help me to combine the code?
Reply
#7
I am not familiar with biopython at all. I was able to find description of Bio.SeqIO.parse. According to documentation: "Turn a sequence file into an iterator returning SeqRecords.". I have no idea what format 'fasta' files are or what is the content of 'protein.fasta' or what SeqRecord is.

However, you wrote:

"These answers were right" / "Then I tried to multiply all the list elements together"

You just wrap your 'right answers' into function and you will get product of said list:

print(sequence_product(right_answers))
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#8
(Jan-08-2019, 11:58 AM)perfringo Wrote: I am not familiar with biopython at all. I was able to find description of Bio.SeqIO.parse. According to documentation: "Turn a sequence file into an iterator returning SeqRecords.". I have no idea what format 'fasta' files are or what is the content of 'protein.fasta' or what SeqRecord is.

However, you wrote:

"These answers were right" / "Then I tried to multiply all the list elements together"

You just wrap your 'right answers' into function and you will get product of said list:

print(sequence_product(right_answers))

I tried it like this :
[python]sequence_productx(combinations)/python]

and this gives 32768 as an answer.
Which is correct for the last list combination but the other 4 are not printed out.
Reply
#9
Is the code you provided intended correctly?

It suspect that problem is that you overwriting combination value with every loop iteration and therefore you get only last result.

>>> combinations = list()
>>> for i in range(3):
...     combinations.append([1, 2, 3])
...
>>> combinations
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> for row in combinations:
...     print(sequence_product(row))
...
6
6
6
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#10
(Jan-08-2019, 12:48 PM)perfringo Wrote: Is the code you provided intended correctly?

It suspect that problem is that you overwriting combination value with every loop iteration and therefore you get only last result.

>>> combinations = list()
>>> for i in range(3):
...     combinations.append([1, 2, 3])
...
>>> combinations
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> for row in combinations:
...     print(sequence_product(row))
...
6
6
6

I think the problem is when I tried the combinations in new code this does not work.
So what I do now is:
1 step)=> run the code until containing print(combinations), this will give me a result(see solution box above)

2 step )=> Use this code given
 
from functools import reduce
from operator import mul
 
def sequence_productx(combinations):
    """Return sequence elements product; if empty return zero."""
 
    if not combinations:
        return 0
    else:
        return reduce(mul, combinations)
3 step ) =>
sequence_productx(combinations)
sequence_productx(combinations) # this print out 32768

4 step ) = > problem is I don't get answer 96, 128, 192, 13824, 32768.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  New to python! Loops Seeley307 3 59,547 May-15-2020, 02:27 PM
Last Post: ibreeden
  Error in loops, new to Python jhall710 20 12,298 Apr-25-2017, 05:18 AM
Last Post: smbx33

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020