2016-09-26 108 views
0

我有第一個工程部分,但第二個不not.Here是問題 Question with which i am having the issue.Has sample input and output無法解決這一問題

這個問題了,我試圖讓2 solutions.The一些問題的代碼

以下是其中我寫

number=int(input()) 
S=input() 
w=list(S[:]) 



w_count=0 
other_count=0 
v_count=0 
vv_count=0 

i=0 

while(i<(len(w))): 
    try: 

     if w[i]=='w': 
      w_count+=1 
     elif w[i]=='v' and w[i+1]=='v': 
      vv_count+=1 
      i+=1 
     else: 
      other_count+=1 
    except IndexError: 
     pass 
    i+=1 

max_length=w_count*2+other_count+v_count 
min_length=0 

min_length=w_count+other_count+vv_count 
print(min_length,max_length) 

其他邏輯已經用的幫助下用於環路中實現的2碼爲哪些3測試用例傳遞

for value in range(len(w)): 
    try: 
     if w[value]=='w': 
      w_count+=1 
     elif w[value]=='v' and w[value+1]=='v': 
      vv_count+=1 
     else: 
      other_count+=1 
    except IndexError: 
     pass 
+2

問題尋求幫助調試(**「爲什麼不是這個代碼的工作? 「**)必須包含所需的行爲,*特定的問題或錯誤*,以及*在問題本身**中重現**所需的最短代碼。沒有**明確問題陳述**的問題對其他讀者沒有用處。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 – MattDMo

回答

1

如果認爲你可以把它簡單的搭配:

my_string = "avwvb" 
max_len = len(my_string.replace("w", "vv")) 
min_len = len(my_string.replace("w", "vv").replace("vv", "w")) 
print(max_len, min_len) 

或者更快一點:

my_string = "avwvb" 
max_string = my_string.replace("w", "vv") 
min_string = max_string.replace("vv", "w") 
max_len = len(max_string) 
min_len = len(min_string) 
print(max_len, min_len) 
1

你可以試試這個。它類似於你的for loop解決方案,但使用字符串索引更好一點。

對於第一個問題,我只是儘可能地擴大字符串,將所有w s更改爲2 v s。

第二個有點棘手。我首先使用前面的方法擴展字符串,然後構建一個新字符串,其中任何vv組合可以變成w。我使用2個索引,i用於較長的字符串,j用於較短的字符串版本,以避免索引錯誤。

def longer(s): 
    for i in range(0,len(s)): 
     x = s[i] 
     if x == 'w': 
      new_str = s[:i] + 'v' + s[i+1:] 
      if (i + 1 >= len(s)): 
       new_str = new_str + 'v' 
      else: 
       new_str = new_str[:i] + 'v' + new_str[i:] 
      s = new_str 
    return s 

def shorter(s): 
    long_str = longer(s) 
    short_str = long_str[0] 
    j = 1 
    for i in range(1,len(long_str)): 
     x = long_str[i] 
     if x == 'v' and short_str[j-1] == 'v': 
      short_str = short_str[:j-1] + 'w' 
      j = j -1 
     else: 
      short_str = short_str + x 
     j = j +1 
    return short_str 

print len(longer("avwvb")) 
print len(shorter("avwvb")) 
+0

我可以得到您的電子郵件ID user3543300 ??因爲我爲同一個問題開發了不同的算法,但它工作有點不同 –

+0

我試過另一種方法,但它不工作,有人可以幫忙嗎? –