4 ms·
True, you'd need to re create the generator expression. Still, the other implementation seemed too naive.
by santiagobasulto 5y ago
True, you'd need to re create the generator expression. Still, the other implementation seemed too naive.
- _dain_ 5y agoThere's probably some itertools trick to do it with only one iteration. 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.
- jhgb 5y ago> There's probably some itertools trick to do it with only one iteration. 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.