입력

2013-06-09 2 views
1

내가 입력을하지 않는 함수를 작성하는 것을 시도하고있다 동안 어떻게 계산하려면, 대신에 이름을 요청합니다. 빈 문자열을 입력하면이 함수는 모든 이름에 대해 동일한 이름을 가진 사람들의 수를 인쇄해야합니다. 예를 들어입력

:

>>>name() 
Enter a name: Paul 
Enter a name: Bill 
Enter a name: John 
Enter a name: Paul 
Enter a name: Nick 
Enter a name: Bill 
Enter a name: Bill 
Enter a name:  
There is 1 person named John 
There is 1 person named Nick 
There are 2 people named Paul 
There are 3 people named Bill 

지금까지 내가 가진 :

def name(): 
    name = input ('Enter a name: ') 
    count = 0 

    while name: 
     if name == input ('Enter a name: '): 
      count = count + 1 
     else: 
      print (count) 

내가 제대로 계산 아니에요 확신 해요. 어떻게이 기능을 적절하게 수행하고 다양한 입력을 구별하고 얼마나 많은 다른 이름이 있을지 모를 때 어떻게 계산합니까? 가능하면 나는 아직도 효율적인없는 경우에도 배우고있는 동안

또한, 나는 기본 코드를 싶습니다.

답변

3

Counter을했다.

import collections 

counts = collections.Counter() 

while True: 
    name = input('Enter a name: ') 
    if not name: 
     break 
    counts[name] += 1 

for name, count in counts.items(): 
    print('There is {} person named {}'.format(count, name)) 

당신이 최소한의 공통 가장하기 위해 결과를 원하는 경우에, Counter는 수, most_common에 의해 정렬 기능이 있습니다. 당신이 그들을 이름으로 분류 않으려면,

for name, count in reversed(counts.most_common()): 
    print('There is {} person named {}'.format(count, name)) 

을 또는 :

for name, count in sorted(counts.items()): 
    print('There is {} person named {}'.format(count, name)) 
3
from collections import defaultdict 
dic = defaultdict(int) 
while True: 
    name = input ('Enter a name: ') 
    if name: 
     dic[name] += 1 
    else: 
     for k,v in sorted(dic.items(), key = lambda x: (x[1],x[0])): 
      print ("There is {} person named {}".format(v,k)) 
     break  

데모 :

$ python3 so.py 
Enter a name: Paul 
Enter a name: Bill 
Enter a name: John 
Enter a name: Paul 
Enter a name: Nick 
Enter a name: Bill 
Enter a name: Bill 
Enter a name: 
There is 1 person named John 
There is 1 person named Nick 
There is 2 person named Paul 
There is 3 person named Bill 
+0

에 대한 람다 무엇인가? – M15671

+0

@ M15671 값과 키를 기반으로 사전 항목을 정렬합니다. –

+0

매우 유사한 기능이지만 조금 더 간결합니다 :'k in sorted (dic, key = dic.get) :'. –

4

그냥 재미를 위해 한 - 라이너가이 작업을 수행하려면 :

>>> collections.Counter(iter(functools.partial(input, "Enter a name: "), "")) 
Enter a name: Paul 
Enter a name: Bill 
Enter a name: John 
Enter a name: Paul 
Enter a name: Nick 
Enter a name: Bill 
Enter a name: Bill 
Enter a name: 
Counter({'Bill': 3, 'Paul': 2, 'Nick': 1, 'John': 1}) 

이 아마 실제 코드에서 그것을 할 수있는 방법은 없습니다. 파이썬은 특별히 계산을 위해 만든 모음과 함께 제공

+0

+1 - 이것이 내가 파이썬을 좋아하는 이유 중 하나입니다. – duffymo

+0

나는 2 개의 인수를'iter'의 좋은 사용을 사랑하고, 정말, 이것은 실제 코드로 나쁜 유일한 이유는 그것이 이해가되지 않습니다하지 않는 것이, 한 줄에 모두 가득 한 것입니다. 하지만 어쩌면 내가 배우는 동안 "기본 코드"에 맞지 않을 수도 있습니다. – abarnert

+0

@abarnert : 예, 확실히 "기본"자격이 없습니다. 그러나 그것은 또한 "읽을 수있는"것으로 실제로 자격을 부여하지 않으므로 대상 독자와 상관없이이 솔루션을 사용하지 않을 것입니다. 어쨌든 그것은 재미 있다고 생각합니다. –

1

당신은 단순한 파이썬 맵을 사용할 수 있습니다 불행히도, 뒤로 ​​...하지만 당신은 reversed를 호출하여이 문제를 해결할 수 있습니다. 이 기능 :

names = {} 

while True: 
    name = raw_input('Enter a name: ') 
    if not name: 
     break 
    if name not in names: 
     names[name] = 0 
    names[name] = names[name] + 1 

for name in sorted(names, key=names.get): 
    if names[name] < 2: 
     print 'There is %d person named %s' % (names[name], name) 
    else: 
     print 'There are %d people named %s' % (names[name], name)