Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

Counting total number of unique characters for Python string

enter image description here

For my question above, I'm terribly stuck. So far, the code I have come up with is:

def count_bases():
    get_user_input()
    amountA=get_user_input.count('A')
    if amountA == 0:
        print("wrong")
    else:
        print ("right",amountA)

def get_user_input():
    one = input("Please enter DNA bases: ")
    two=list(one)
    print(two)

My line of thinking is that I first:
1. Ask user to enter the DNA bases (ATCG)
2. Change the user input into a list
3. Going back to the main (count_bases) function, I count the number of 'A', 'T', 'C', 'G'
4. Use 4 if-else statements for the four different bases.

So far, my code only works up to the output of the user's input into a list. After that, an error just pops up.
Appreciate it if someone can point the right path out to me!
Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use collections.Counter

from collections import Counter

def get_user_input():
    input_str = input("Please enter DNA bases: ")
    c = dict(Counter('ACCAGGA'))
    return c

def count_bases():
    counts = get_user_input()
    dna_base = list("ATCG")
    for base in dna_base:
        if base not in counts.keys():
            print(f"{base} not found")
        else:
            print(f"{base} count: {counts[base]}")

output when I call count_bases()

Please enter DNA bases: >? ACCAGGCA
A count: 3
T not found
C count: 2
G count: 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...