【发布时间】:2021-12-25 23:58:33
【问题描述】:
我是 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
【问题讨论】:
-
尝试在最里面的
if中添加print语句,例如print(f'str[{i}] was equal to str[{j}], so we will increment the count'),然后使用更简单的'xxx'输入来测试代码。你看到问题了吗? -
你真的有两个任务,对吧?找出字符串中有哪些字符(从起点开始),然后计算出每个字符出现了多少次。正确的?那么,如果您尝试分别解决这些任务怎么办?你能找到更简单的方法来解决这个问题吗?
-
@KarlKnechtel 是的,理解这个问题。
标签: python python-3.x frequency