by santiagobasulto · 5y ago · 0 comments
lines = (line for line in lines("orthocoronavirinae.fasta") if not line.startswith(">"))
gc_lines = (1 if ('G' in line or 'C' in line) else 0 for line in lines)
gc = sum(gc_lines)
total = len(list(gc_lines))
# Alternatively, a more "memory efficient" total would be:
total = sum(1 for _ in lines)
Edit: my code is not perfect (I’m typing from my phone, I’m surprised I could even match parentheses).My point is: this is a highly I/O bound program. The implementation matters. With the correct implementation there shouldn’t be much difference between the languages.
That won't work properly; you've already exhausted the gc_lines generator in the previous line.
EDIT: you can do it with functools.reduce and a generator of tuples:
from functools import reduce
with open("orthocoronavirinae.fasta") as f:
lines = (line.strip() for line in f if not line.startswith(">"))
sums = ((len(line), sum(1 for ch in line if ch in "CG")) for line in lines)
total, gc = reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), sums)
Besides, I really don't think that any of our solutions will be that much faster than the one in the OP. All of them are using lazy iteration on the file object, just written differently. The differences amount to micro-optimizations. The real way to speed it up would be to use something like pandas, where the loading and summing calls into fast C implementations.Or an arithmetic trick. Since there's the `1 if ('G' in line or 'C' in line) else 0 for line in lines` construct in the code, if you simply replace 1 with (len(line)<<K)+1 and 0 with len(line)<<K (for a suitable value of K), you can extract the two results using div/mod.