簡體   English   中英

如何在不使用集合類型的情況下計算每個字母在字符串中出現的次數?

[英]How do I count the number of times each alphabet occurs in a string without using collection types?

正如標題所暗示的,我正在做一個 python 作業,問題要求我在不使用集合類型的情況下計算每個字母在字符串中出現的次數?

例如:

ID='AAAABBBCCD'

打印結果應為“4A 3B 2C 1D”。

到目前為止我已經嘗試過:

def count_occurence(ID, to_find):
    number = 0
    for x in range(len(ID)):
        if ID[x] == to_find:
            number +=1
    return number

ID=(input("Enter ID: "))
first_check = count_occurence(ID,'A')
second_check = count_occurence(ID,'B')
print(first_check,second_check)

但我不認為它是有效的,因為我必須創建一個從“A”到“Z”的檢查。

注意:集合類型有 set、list 和 dict。

ID='AAAABBBCCD'
n = 0
verify = []
output = ''
for i in ID:
    count = 0
    char = ID[n]
    if not char in verify  :
        verify.append(char)
        for z in range(len(ID)):
            if char == ID[z]:
                count += 1

        output +=' ' + str(count) + char

    n += 1
print(output)

您可以使用evalexec解決它。

這是代碼:

def count_str(id_str):
    for i in range(65, 65 + 26):
        exec("var_" + chr(i) + " = 0")
    for c in id_str:
        exec("var_" + c + " = " + "var_" + c + " + 1")
    rtn_str = ""
    for i in range(65, 65 + 26):
        if eval("var_" + chr(i) + " > 0"):
            rtn_str = rtn_str + str(eval("var_" + chr(i))) + chr(i) + " "
    if(len(rtn_str) >0):
        rtn_str = rtn_str[0: -1]
    return rtn_str

測試:

>>> count_str("AAAABBBCCD")
'4A 3B 2C 1D'
>>> count_str("AAAABBBCCDAB")
'5A 4B 2C 1D'
>>> count_str("AAAABBBCCDABEEFG")
'5A 4B 2C 1D 2E 1F 1G'

查找代碼中的注釋以進行解釋

ID='AAAABBBCCD'

# create an empty dictionary
output = {}

# iterate over the string ID
for each_alphabet in ID:
    # check whether it exists in output dictionary
    if each_alphabet in output.keys():
        output[each_alphabet] += 1 # increment the value to 1
    else:
        output[each_alphabet] = 1

# finally generate the result
final_result = ' '.join([f'{v}{k}' for k,v in output.items()])

print(final_result)
4A 3B 2C 1D

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM