[Shootout-list] reverse-complement and harmonic in Python

Jacob Lee artdent@freeshell.org
Wed, 23 Mar 2005 21:35:51 -0600


The existing Python implementation of reverse-complement gives an error.
The following code works (I diffed it to the sample input and output).

Everything between the dashes is code:

--
#!/usr/bin/python
# 
# The Great Computer Language Shootout
# http://shootout.alioth.debian.org/
# 
# contributed by Jacob Lee, Steven Bethard, et al
#

import sys, string

def show(seq, table=string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy',
                                     'TGVHCDM\nKNSYAAWBRTGVHCDMKNSYAAWBR')):
     seq = (''.join(seq)).translate(table)[::-1]
     for i in xrange(0, len(seq), 60):
         print seq[i:i+60]

def main():
     seq = []
     add_line = seq.append
     for line in sys.stdin:
         if line[0] in '>;':
             show(seq)
             print line,
             del seq[:]
         else:
             add_line(line[:-1])
     show(seq)

main()
--

Also, the existing implementation of harmonic in Python uses roughly
200x the memory of an average implementation in another language. Here
is the fixed code:

--
#!/usr/bin/python
# The Great Computer Language Shootout
# http://shootout.alioth.debian.org/
#
# contributed by comp.lang.python
#

import sys

print "%.9f" % sum(1.0/i for i in xrange(1, 1+int(sys.argv[1])))
--

Note: The contribution line is how it is because between the triviality
of the code, the similarity (in appearance, not in memory usage!) to the
previous submission, and the amount of people who gave opinions,
determining authorship is somewhat pointless. If this is not ok, feel
free to change it.

-- 
Jacob Lee
artdent@freeshell.org | www.nearestneighbor.net