首页 > 解决方案 > 在 python grok 中计算字符

问题描述

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

'你的程序应该读入多行输入,直到输入一个空行。然后它应该打印出有多少个独特的字符被命名,有多少被重复了。

这是我的结果:

角色:医生
角色:玫瑰
角色:罗里
角色:克拉拉
角色:K-9
角色:大师
角色:医生
角色:艾米
角色:
您命名了 8 个角色
您重复了 1 次

这是我的代码:

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 个角色。
您重复了 1 次。

标签: pythongrok

解决方案


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,'时间( s)')

主要变化:

 if country in count:     //changed

   c = c - b             //removed

print('You named',c,'character(s)')        //changed
print('You repeated',b,'time(s)')          //changed

推荐阅读