4

我有一个包含一行的文本文件。文本行是一大堆随机数。我需要确定 5 重复的最多次数并打印它重复了多少次。例如:numList: 1234555325146555。连续重复 5 的次数最多为 3 次,并且发生了 2 次。这是我到目前为止的代码,它向我展示了 5 的位置。我认为这是第一步,但无法弄清楚如何继续前进。

numbers = open("numbers.txt",'rU')
count = -1
numString = numbers.readline()
for num in numString:
    count += 1
    if num == '5':
        print count
        counter += 1
4

6 回答 6

4

你有正确的想法来找出 5 在哪个位置。

那么如何找出一排 5 的长度呢?想一想:

  1. 你需要知道你是否找到了一个 5,如果它是一个系列的一部分。跟踪以前的号码。如果这也是一个 5,那么你正在继续一个系列。
  2. 如果您要继续一个系列,那么请使用另一个计数器来跟踪它的持续时间。
  3. 如果达到的数字不是 5,则需要重置计数器。但在重置之前,您需要存储该值。
  4. 对于问题的下一部分(找出有多少个 5 的系列),尝试使用额外的“元”变量来跟踪您迄今为止拥有的最长系列以及您已经看过多少次。

祝你好运!并继续提问

于 2012-07-11T17:55:05.610 回答
3

我经常发现像这样的任务我问自己,如果问题足够大,我怎么会在没有电脑的情况下完成这项工作,我无法记住所有内容。所以在这里,我会一直走到找到 5。然后我会查看下一个数字,如果是 5,继续前进,直到连续没有更多的 5。因此,在您的示例中,我会连续找到 3 个 5。我会记下我发现的最长的是 3 个 5。然后我会继续下一个5。

然后我会再次计算连续有多少个 5。在这种情况下,我会看到只有 1。所以我不会费心做任何事情,因为我会看到它小于 3。然后我会继续下一个 5。

我会看到连续有 3 个,我会回到我的论文中,看看我找到的最长的有多长,我会看到它是 3。然后我会记下我看到的2组3个一排。

如果我找到 4 个或更多,我会忘记我拥有的关于 3 组的所有信息,并从 4 组或其他任何内容重新开始。

所以尝试在你的循环中实现这种想法。

于 2012-07-11T17:55:01.700 回答
2

这是一个相当简单的方法来解决这个问题:

>>> import re
>>> numString = '1234555325146555'
>>> fives = re.findall(r'5+', numString)
>>> len(max(fives))          # most repetitions
3
>>> fives.count(max(fives))  # number of times most repetitions occurs
2
于 2012-07-11T17:49:56.810 回答
1

我会不断检查给定字符串中是否有特定的 5 字符串,直到它不再存在(每次添加一个 '5')。然后我备份 1 并使用count字符串的方法——像这样(伪代码如下——注意这不是语法上有效的python。这取决于你,因为这是家庭作业。)

str5='5'
while str5 in your_string
    concatenate '5' with str5

#your string is too long by 1 element
max_string=str5 minus the last '5'
yourstring.count(max_string)
于 2012-07-11T17:49:00.950 回答
0
#  First step: Find at most how many times 5 comes in a row.
# For this I have a counter which increases by 1 as long 
# as I am dealing with '5'. Once I find a character other 
# than '5' I stop counting, see if my counter value is greater
# than what I have found so far and start counting from zero again.

numbers = open("numbers.txt",'rU')
count = -1
numString = numbers.readline()
maximum = -1;

for num in numString:
    count +=1
    if num== '5':
        counter += 1
    else:
        maximum=max(maximum, counter)
        counter = 0;

#  Second step: Find how many times this repeats.
# Once I know how much times it comes in a row, I find consequent fives
# with the same method and see if the length of them is equal to my maximum

count=-1
amount = 0
for num in numString:
    count +=1
    if num== '5':
        counter += 1
    else:
        if maximum == counter:
            amount += 1
        counter = 0;

希望能帮助到你 :)

于 2012-07-11T18:01:29.707 回答
0
from collections import defaultdict, Counter
from itertools import groupby

num_str = '112233445556784756222346587'

res = defaultdict(Counter)
for dig,seq in groupby(num_str):
    res[dig][len(list(seq))] += 1

print res['5'].most_common()

返回

[(1, 2), (3, 1)]

(意味着“5”被看到了两次,“555”被看到了一次)

于 2012-07-11T17:53:27.877 回答