2016-09-26 91 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

我试过另一种方法,但它不工作,有人可以帮忙吗? –