为什么我的 python 代码仅对某些输入给出错误答案?

Why is my python code giving wrong answers for only some inputs?

我是 python 的新手,我正在尝试编写一个程序,从特定点开始给出字符串中每个字母的频率。现在我的代码为一些输入提供了正确的输出,比如如果我输入“hheelloo”,我得到正确的输出,但是如果输入是“hheelllloooo”,h、e 和 l 的频率打印正确,但频率如果起点是索引 0,'o' 的结果为 7。有人能告诉我我做错了什么吗?

编写一个 Python 程序来计算字符在字符串中的出现次数(做 不使用内置计数功能。 修改上面的程序,让它开始计数 来自指定位置。

str = list(map(str, input("Enter the string : ")))
count = 1
c = int(input("Enter the location from which the count needs to start : "))
for i in range(c, len(str)):
    for j in range(i+1,len(str)):
        if str[i] == str[j]:
            count += 1
            str[j] = 0
    if str[i] != 0:
        print(str[i], " appears ", count, " times")
        count = 1
str = list(map(str, input("Enter the string : ")))
count = 1
c = int(input("Enter the location from which the count needs to start : "))
for i in range(c, len(str)):
    for j in range(i+1,len(str)):
        if str[i] == str[j]:
            count += 1
            str[j] = 0
    if str[i] != 0:
        print(str[i], " appears ", count, " times")
    count = 1 // <----- This line should be outside the if block.

错误是因为缩进。 我刚刚正确地缩进了最后一行。

谢谢,如果有用,请点赞。

string 模块可用于计算字符串中字母、数字和特殊字符的出现频率。

import string

a='aahdhdhhhh2236665111...//// '

for i in string.printable:
    z=0
    for j in a:
        if i==j:
            z+=1
    if z!=0:
        print(f'{i} occurs in the string a {z} times')

如果你想从一个特定的索引值计算字符的出现频率,你只需要稍微修改上面的代码如下:

import string

a='aahdhdhhhh2236665111...//// '
c = int(input("Enter the location from which the count needs to start : "))
for i in string.printable:
    z=0
    for j in a[c:]:
        if i==j:
            z+=1
    if z!=0:
        print(f'{i} occurs in the string a {z} times')

我认为你不需要 map strinputlist 因为 input() 总是 returns stringstring 本身就是一个 list 字符。还要确保您不使用内置函数作为变量名(如代码中使用的 str)。一种更简单的方法可以是:

input_word = input("Enter the string : ")
c = int(input("Enter the location from which the count needs to start : "))
# Dict to maintain the count of letters
counts = {}
for i in range(c, len(input_word)):
    # Increment 1 to the letter count
    counts[input_word[i]] = counts.get(input_word[i], 0)+1
    
for letter, freq in counts.items():
    print (f'{letter} appears {freq} times')

输出:

Enter the string : hheelllloooo
Enter the location from which the count needs to start : 2
e appears 2 times
l appears 4 times
o appears 4 times