wsndc 发表于 2021-11-1 18:29:09

求助

本帖最后由 wsndc 于 2021-11-1 18:46 编辑

python3的题
从键盘里输入一个字符串,然后在显示其中出现最多的三个字符,咋做啊?用什么函数?

傻眼貓咪 发表于 2021-11-1 19:01:02

代码:def func(s: str) -> str:
    A = 0; B = 0; C = 0
    a = None
    for i in s:
      if s.count(i) > A:
            A = s.count(i)
            a = i
    for i in s:
      if s.count(i) > B and i != a:
            B = s.count(i)
            b = i
    for i in s:
      if s.count(i) > C and i != a and i != b:
            C = s.count(i)
            c = i   
    return a, b, c

string = "bananasdgfykasyqawgdaulgsda"

print(func(string))输出:('a', 's', 'd')

wsndc 发表于 2021-11-1 19:19:44

本帖最后由 wsndc 于 2021-11-1 19:21 编辑

傻眼貓咪 发表于 2021-11-1 19:01
代码:输出:

是在运行之后,你打一个字符串,然后再由python输出三个出现最多的字符,就和抛硬币一样,你先输入你要抛 的次数,然后python再给你返回

傻眼貓咪 发表于 2021-11-1 19:22:35

wsndc 发表于 2021-11-1 19:19
是在运行之后,你打一个字符串,然后再由python输出三个出现最多的字符,就和抛硬币一样,你先输入你要 ...

def func(s: str) -> str:
    A = 0; B = 0; C = 0
    a = None
    for i in s:
      if s.count(i) > A:
            A = s.count(i)
            a = i
    for i in s:
      if s.count(i) > B and i != a:
            B = s.count(i)
            b = i
    for i in s:
      if s.count(i) > C and i != a and i != b:
            C = s.count(i)
            c = i   
    return a, b, c

string = input("请输入字符串:")

print(f"出现最多的三个字符:", func(string))

wsndc 发表于 2021-11-1 19:25:24

傻眼貓咪 发表于 2021-11-1 19:22


谢谢大佬

wsndc 发表于 2021-11-1 19:49:39

傻眼貓咪 发表于 2021-11-1 19:22


你def后面那串啥意思啊?我不理解

傻眼貓咪 发表于 2021-11-1 19:51:05

wsndc 发表于 2021-11-1 19:49
你def后面那串啥意思啊?我不理解

没有特别意思,只是函数名字,你也可以取别的名,比如:ABC

傻眼貓咪 发表于 2021-11-1 19:54:20

wsndc 发表于 2021-11-1 19:49
你def后面那串啥意思啊?我不理解

def func(s: str) -> str:

def 表示定义
func 表示函数名字(随意)
(s: str) 表示参数 s(: str 纯粹是想告知其他人,参数类型是字符串,没有特别功能,可有可无)
-> str 粹是想告知其他人,返回类型是字符串,没有特别功能,可有可无

wsndc 发表于 2021-11-1 19:55:55

傻眼貓咪 发表于 2021-11-1 19:54
def func(s: str) -> str:

def 表示定义


谢谢大佬,我会了{:10_254:}

心驰神往 发表于 2021-11-3 08:02:17

wsndc 发表于 2021-11-1 19:55
谢谢大佬,我会了

{:10_256:}

村里小黑 发表于 2021-11-3 08:28:08

{:10_255:}
页: [1]
查看完整版本: 求助