无法用代码解决这个问题

时间:2016-09-26 21:00:21

标签: python-3.x for-loop while-loop

我在这个问题上遇到了一些问题,我试图制作两个解决方案。第一个部分工作,但第二部分不工作。这就是问题 Question with which i am having the issue.Has sample input and output

以下是我编写的2个代码

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)

另一个逻辑已经在for循环的帮助下实现,其中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 个答案:

答案 0 :(得分:1)

你可以试试这个。它与您的for loop解决方案类似,但使用字符串索引更好。

对于第一个问题,我只是尽可能地扩展字符串,将所有w更改为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"))

答案 1 :(得分: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)
相关问题