2012-07-11 118 views
4

我有一個文本文件,其中包含單行。文本行是一大堆隨機數字。我需要確定一個5重複次數的最多次數並打印它重複的次數。例如:numList:1234555325146555.連續重複5次的次數是3次,發生2次。這是我迄今爲止的代碼,它顯示了我在哪些位置出現了5。我認爲這是第一步,但不知道如何繼續前進。查找字符串中的重複字符並確定它在python中重複的次數

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

回答

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) 
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 
+0

這被標記爲功課,它可能是更好的不僅僅是放棄的答案嗎? – Justin 2012-07-11 17:56:43

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'被看到一次)

3

我經常發現這樣的任務我問自己,如果問題足夠大,我會怎麼做,不要忘記一切。所以在這裏,我會走到我找到一個5.然後我會看看下一個數字,如果它是一個5,繼續前進,直到沒有更多的5連續。所以在你的例子中,我會連續找到3 5個。我會記下我發現的最長時間是3 5。然後,我會繼續前進到下一個5.

然後我會再次計算連續有多少個5。在這種情況下,我會看到只有1個。所以我不會做任何事情,因爲我會看到它小於3.然後我將繼續前進到下一個5.

我會看到有連續3次,我會回到我的論文,看看我發現的最長的時間是多少,我會看到它是3.所以,然後我會記下,我已經看到2組3行。

如果我發現4個或更多,我會忘記所有關於3個套件的信息,並從4個套件開始。

所以在你的循環中嘗試實現這種想法。

+1

+1用於提供方法而非解決方案 – 2012-07-11 17:58:36

4

你有以找出5是在該位置,正確的想法。

那麼,你如何找出5的一排是多久?想想:

  1. 你需要知道,如果你已經找到了5,如果它是一個系列的一部分。跟蹤以前的號碼。如果這也是一個5,那麼你將繼續一系列。
  2. 如果你正在繼續一個系列,然後有另一個計數器來跟蹤它是多久。
  3. 如果您達到的數字不是5,則需要重置計數器。但在重置之前,您需要存儲該值。
  4. 對於問題的下一部分(找出5個系列中有多少系列),嘗試使用額外的「元」變量,記錄迄今爲止最長的系列以及您已經看過多少次系列。

祝你好運!並不斷問問題

+2

用於提供方法而不是解決方案 – 2012-07-11 17:58:58

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; 

希望,它可以幫助:)

相關問題