2014-03-01 40 views
0

我試着計算一個數字中偶數位的最大長度,並打印序列開頭的索引和序列本身。序列計算問題

這裏是我開始的代碼,但它有一些缺陷:

num = int(eval(input("Please enter a positive integer: "))) 

length=0 
seq=None 
start = -1 
while num!=0: 
    d = num % 2 
    num = num /10 
    if d==0: 
     length=length+1 


print("The maximal length is", length) 
print("Sequence starts at", start) 
print("Sequence is", seq)} 
+2

什麼錯誤?你能詳細說明嗎? –

回答

0

我想象你看到一個NameError異常(但我不應該:當你與你的代碼問題報告重要的是要報告它的行爲,不要只說「它不起作用」,因爲有一百萬種方法可能會失敗)。 [注:我懷疑這只是因爲代碼被格式化系統弄壞了,所以我認爲你實際上是在num中讀取一個數字]。

只有在開始時才能找到運行嗎?那麼345666678呢?您目前沒有任何代碼可以將開始點向前移動。但是你的代碼顯示了許多正確的想法,所以讓我們來討論算法的策略應該是什麼。

由於數字中可能存在許多運行的可能性,因此任務會縮短爲查找所有運行並選擇最長運行。因此,首先將longest_run設置爲零,如果該號碼只包含奇數位,則該位置應保持爲零。

當你發現一個奇怪的數字(在字符串的結尾),比較當前run_lengthlongest_run和替換它,如果長時間(這必須是一個運行結束,即使長度的運行零),然後將run_length設置回零。當你找到一個偶數時,在run_length上加1。

您似乎是一個初學者,所以恭喜您獲得正確的問題這麼多元素。

0

一個簡單的解決方案可能是以下幾點:

a = int(eval(input("Please enter a positive integer: "))) 
# Items in the sequence to look for 
even = ['0','2','4','6','8'] 
# Length of the current sequence 
le = 0 
# and starting position 
st = -1 
# Length of the longest sequence 
maxLe = 0 
# and starting position 
maxSt = -1 

# Loop through the digits of the number 
for idx,num in enumerate(str(a)): 
    if num in even: 
     le += 1 
     if le == 1: 
      # If it is a new sequence, save the starting position 
      st = idx 
    else: 
     # If there are no more even digits, check if it is the longest sequence 
     if le > maxLe: 
      maxLe = le 
      maxSt = st 
     # Reset to look for the next sequence 
     le = 0 
+0

我不明白這個部分: 對於idx,num枚舉(str(a)): idx和枚舉是什麼意思? – Tam211

+0

如果在循環中使用「枚舉」,則會收到兩個值:「索引」(或數組內的位置)和「值」,這是您通常在循環中使用的值。 – Javier

+0

無論如何,如果此代碼起作用,請選擇我的答案並將問題標記爲「已回答」。謝謝! – Javier

0

的Python 2.x版(目前還不清楚你想要哪一個):

from __future__ import print_function 
import sys 

even = '02468' # even = ''.join(range(0,10,2)) 

# in python 2.x is very unsafe and unreliable, use raw_input 
answer = raw_input('Please enter a positive integer: ') 
# in python 3.x you can use input(), but just cast it to desired 
# type and catch errors with 'except ValueError:' clause or... 

# check here if all characters are digits: 
if not answer.strip().isdigit(): 
    print ("Wrong input.") 
    sys.exit(1) 

sequence = answer 

# this returns number of consecutive even digits 
def even_len(sequence): 
    for i, digit in enumerate(sequence): 
     if digit not in even: 
      return i # early break on the first odd digit 
    return i 

start, length = 0, 0 
i, n = 0, len(sequence) 
while i < n: 
    this_len = even_len(sequence[i:]) # search for rest of input 
    if this_len > length: 
     length = this_len 
     start = i 
    i += this_len + 1 # let's skip already checked digits 

print("The maximal length is", length) 
print("Sequence starts at", start) 
print("Sequence is", sequence[start : start+length])