首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >计算python中的字符

计算python中的字符
EN

Stack Overflow用户
提问于 2019-08-27 13:21:48
回答 3查看 757关注 0票数 0

有一个任务,我必须输入名称,并在最后打印多少个不同的字符和多少重复。

“你的程序应该用多行输入来读取,直到输入一个空行。然后它应该打印出有多少个唯一的字符被命名,多少个被重复了。”

这是我的结果:

人物:医生

人物:玫瑰

人物:罗里

人物:克拉拉

人物: K-9

人物:大师

人物:博士

人物:艾米

人物:

你指定了8个字符

你重复了一次

这是我的密码:

代码语言:javascript
复制
count = []   
country = input('Character: ')
a = country.count(country)
b = 0
c = 0
while country:
 count.append(country)
  country = input('Character: ')
  if a == country:
    b = b + 1
  else:
    c = c + 1
c = c - b
count.sort()
print('You named',c,'character(s)')
print('You repeated',a,'time(s)')

应该说:

人物:博士

人物:玫瑰

人物:罗里

人物:克拉拉

人物: K-9

人物:大师

人物:博士

人物:艾米

人物:

你指定了7个字符。

你重复了一次。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-08-27 13:56:22

代码语言:javascript
复制
country = input('Character: ')

a = country.count(country)
b = 0
c = 0

while country:

 count.append(country)
 country = input('Character: ')
 if country in count:
   b = b + 1
 else:
   c = c + 1

count.sort()
print('You named',c,'character(s)')
print('You repeated',b,'time(s)')

结果:

人物:"AA“ 人物:"BB“ 字符:"CC“ 人物:"BB“ 人物:"“ (“你命名”,3,“人物”) (“你重复”,1,“时间”)

主要变动:

代码语言:javascript
复制
 if country in count:     //changed
代码语言:javascript
复制
   c = c - b             //removed
代码语言:javascript
复制
print('You named',c,'character(s)')        //changed
print('You repeated',b,'time(s)')          //changed
票数 0
EN

Stack Overflow用户

发布于 2019-08-27 14:02:47

你可以把字符和它们的出现数收集成一个小块。(也有collections.Counter(),它是专门针对这一点的,但是为了简单,但是一个常规的dict就可以了。)

代码语言:javascript
复制
character_counts = {}

while True:
    character = input("Character: ")
    if not character:  # Empty line?
        break  # Quit the loop
    # Get the current count for the character, or 0 if not found, increment with one,
    # assign back to the dict.
    character_counts[character] = character_counts.get(character, 0) + 1

# Get a list of characters who occur more than once.
repeated_characters = [
    character
    for (character, count) in character_counts.items()
    if count > 1
]

print("You named {} character(s)".format(len(character_counts)))
print("You repeated {} time(s)".format(len(repeated_characters)))
票数 0
EN

Stack Overflow用户

发布于 2019-08-27 13:30:35

可以使用以下代码段:

代码语言:javascript
复制
n<-ncol(data)

m<-mean(rowMeans(data))

exp_val<-mean(apply(data,1,var))

v<-var(rowMeans(data))-mean(apply(data,1,var))/n

z<-n/(n+exp_val/v)

premiums<-Z*rowMeans(data)+(1-z)*m
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57675640

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档