我有一个名单。它们按当年最受欢迎的女宝宝名字排序。在下面的函数中,我将报告在给定年份范围内连续出现的名称。我正在测试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 :(得分: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']
答案 1 :(得分: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']))