2014-10-12 4 views
0

У меня есть список имен. Они сортируются по году, когда они были самым популярным именем женского ребенка того года. В следующей функции я должен сообщить имя, которое появляется наиболее последовательно в данном диапазоне. Я проверяю в диапазоне 2004 до 2007Подсчет последовательных имен

В списке для этого является следующее:

['Emily','Emily','Emily','Isabel'] 

Нужный выход:

Emily occurred consecutively the most in this range at 3 time/s 

Однако я получаю

Emily occurred consecutively the most in this range at 2 time/s 

Я отправлю свой код ниже.

пример Мне дали следовать.

['A', 'A', 'B', 'C', 'C', 'C'] 
bestName = 'A', bestCount = 1, currentName = 'A', currentCount = 1 

['A', 'B', 'C', 'C', 'C'], next name = 'A' 
currentName = nextName, so currentCount = 2 

[ 'B', 'C', 'C', 'C'], next name = 'B' 
currentName != nextName, and currentCount > bestCount, so bestName = 'A', bestCount = 2, 
now currentName = 'B', currentCount = 1 

['C', 'C', 'C'] next name = 'C' 
currentName != nextName, and currentCount not greater than bestCount 
now currentName = 'C', currentCount = 1 

['C', 'C'] next name = 'C' 
currentName = nextName, so currentCount = 2 

['C'] next name = 'C' 
currentName = nextName, so currentCount = 3 

[] no next name, loop ends 
currentCount > bestCount, so bestName = 'C', bestCount = 3 

И код:

def mostConsecutiveYears(names): 
    """ 
    Compute which name occurs the most times consecutively in a 
    list of names. 
    :param names (list of Name): A list of name objects 
    :return: A tuple containing best name (str) and the count (int) 
    :rtype: tuple 
    """ 
    bestName = names[0].name 
    bestCount = 1 
    currentName = names[0].name 
    currentCount = 1 

    for i in range(1,len(names)): 
     if names[i].name == currentName: 
      currentCount += 1 

     if currentCount > bestCount: 
      bestName = currentName 
      bestCount = currentCount 
      currentCount = 1 
      currentName = names[i].name 

    if currentCount > bestCount: 
     bestName = currentName 
     bestCount = currentCount 

    return bestName, bestCount 
+0

Я пробовал, но я до сих пор не думаю, что отступ правилен. Можете ли вы исправить свое заявление? – Andy

+0

Да. Извини за это. – acloudypsychopass

+0

Теперь он идентичен тому, что у меня есть в моей среде IDE. – acloudypsychopass

ответ

1

Просто так (обратите внимание, что names список строк в моем коде)

def mostConsecutiveYears(names): 
    """ 
    Compute which name occurs the most times consecutively in a 
    list of names. 
    :param names (list of Name): A list of name objects 
    :return: A tuple containing best name (str) and the count (int) 
    :rtype: tuple 
    """ 
    bestName = names[0] # Be careful you can get an error if your list is empty 
    bestCount = 1 
    currentName = names[0] 
    currentCount = 1 

    for name in names[1:]: 

     if name == currentName: 
      currentCount += 1 
     else: 
      currentCount = 1 
      currentName = name 

     if currentCount > bestCount: 
      bestName = currentName 
      bestCount = currentCount 

    return bestName, bestCount 

print(mostConsecutiveYears(['Emily','Emily','Emily','Isabel'])) 
+0

Не совсем правильно. Если у меня есть список '[a, b, b, b, b, b, b, c, c, d, d]', он вернет c как наиболее последовательный вместо b. – acloudypsychopass

+0

О, вы правы, ответ исправлен – Dica

+0

Ответ близок, но есть еще один случай, когда у меня есть '[a, a, b, b, c, c, c, c, c, c, c]'. он будет возвращаться c последовательным 6 раз вместо 7. Это ошибка, которую я имел вначале. – acloudypsychopass

2

Взгляните на itertools.groupby. Это не полное решение, но должно дать вам представление о том, как действовать.

names = ['a', 'a', 'a', 'b', 'c', 'c', 'a', 'b', 'c', 'c', 'c'] 
names = ['Emily', 'Emily', 'Emily', 'Isabel', 'Mary', 'Mary', 'Isabel', 'Emily'] 
groups = [] 
for a, b in itertools.groupby(names): 
    items = list(b) 
    groups.append((len(items), a)) 

count, name = sorted(groups, reverse=True)[0] 
print("{} occurred consecutively the most in this range at {} time{}".format(name, count, "s" if count > 1 else "")) 

ВЫВОД

Emily occurred consecutively the most in this range at 3 times 

Реальный вопрос заключается в том, как вы хотите, чтобы обрабатывать ввод как

['Emily', 'Isabel', 'Mary'] 
Смежные вопросы