在字符串中查找一个重复的字符,并确定它在python中一行重复多少次



我有一个文本文件,里面只有一行。这行文本是一大堆随机数。我需要确定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

你找到了5在哪个位置的正确想法。

那么,你怎么知道一排5的长度呢?想想:

  1. 你需要知道你是否找到了一个5,它是否是一个系列的一部分。记下以前的数字。如果这也是一个5,那么你就是在继续一个系列
  2. 如果你正在继续一个系列,那么用另一个计数器来记录它的长度
  3. 如果您达到的数字不是5,则需要重置计数器。但在重置之前,您需要存储该值
  4. 对于问题的下一部分(找出有多少个5的系列),试着使用额外的"元"变量来跟踪到目前为止你拥有的最长的系列以及你见过的次数

祝你好运!并不断提出问题

我经常发现,对于这样的任务,我会问自己,如果问题太大,我记不清所有内容,如果没有电脑,我该怎么做。所以在这里,我会一直走到我找到一个5。然后我会看下一个数字,如果是5,就继续看,直到连续没有5了。所以在你的例子中,我会连续找到3个5。我要注意的是,我发现的最长的是35岁。然后我会转到下一个5。

然后我会再次数出连续有多少个5。在这种情况下,我会看到只有1个。所以我不会麻烦做任何事情,因为我会看到它小于3。然后我会转到下一个5。

我会看到连续有3个,我会回到我的论文中,看看我发现的最长的是多长,我会看到是3个。然后我会记下,我已经连续看到了2组3个。

如果我找到了4个或更多,我会忘记所有关于3组的信息,从4组或其他什么开始。

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

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

>>> 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

我会不断检查给定字符串中是否有一个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)
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'被看到一次)

#  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;

希望,它有帮助:)

最新更新