The Computer Language
24.11 Benchmarks Game

k-nucleotide Python 3 #8 program

source code

# The Computer Language Benchmarks Game
#   https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
#
#   Naive transliteration from bearophile's program
#   contributed by Isaac Gouy 

from sys import stdin

def seq_lines():
    for line in stdin:
        if line.startswith(">THREE"):
            break
    lines = []
    for line in stdin:
        if line.startswith(">"):
            break
        lines.append( line[:-1] )       
    return lines
    
def base_counts(bases, seq):  
    counts = {}
    size = len(seq) + 1 - bases
    for i in range(size):  
        nucleo = seq[i: i + bases]  
        if nucleo in counts:   
            counts[nucleo] += 1  
        else:
            counts[nucleo] = 1
    return counts               
    
def sorted_freq(bases, seq):  
    keysValues = base_counts(bases, seq).items()
    size = len(seq) + 1 - bases    
    sorted_ =  sorted(keysValues, reverse=True, key=lambda kv: kv[1])     
    return [ (kv[0], 100.0 * kv[1] / size) for kv in sorted_ ]  
      
def specific_count(code, seq):  
    return base_counts(len(code), seq).get(code,0)   
    
def main():
    lines = seq_lines()
    seq = "".join([s.upper() for s in lines])
        
    for base in 1,2:        
        for kv in sorted_freq(base, seq):
           print("%s %.3f" % (kv[0], kv[1]))
        print()      
      
    for code in "GGT", "GGTA", "GGTATT", \
            "GGTATTTTAATT", "GGTATTTTAATTTATAGT":     
        print("%d\t%s" % (specific_count(code, seq), code))       
 
if __name__ == '__main__':
  main()  
    

notes, command-line, and program output

NOTES:
64-bit Ubuntu quad core
Python 3.13.0


 Fri, 01 Nov 2024 23:58:10 GMT

MAKE:
mv knucleotide.python3-8.python3 knucleotide.py
pyright .
0 errors, 0 warnings, 0 informations 

2.99s to complete and log all make actions

COMMAND LINE:
 /opt/src/Python-3.13.0/bin/python3 -OO knucleotide.py 0 < knucleotide-input25000000.txt

PROGRAM OUTPUT:
A 30.295
T 30.151
C 19.800
G 19.754

AA 9.177
TA 9.132
AT 9.131
TT 9.091
CA 6.002
AC 6.001
AG 5.987
GA 5.984
CT 5.971
TC 5.971
GT 5.957
TG 5.956
CC 3.917
GC 3.911
CG 3.909
GG 3.902

1471758	GGT
446535	GGTA
47336	GGTATT
893	GGTATTTTAATT
893	GGTATTTTAATTTATAGT