【问题标题】:Unable to solve this issue with the code无法使用代码解决此问题
【发布时间】:2016-09-26 21:00:21
【问题描述】:

我在这个问题上遇到了一些问题,我试图提出 2 个解决方案。第一个部分有效,但第二个无效。这是问题 Question with which i am having the issue.Has sample input and output

这是我写的两个代码

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

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误和在问题本身中重现它所需的最短代码。没有明确的问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable Example。

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


【解决方案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)

【讨论】:

    【解决方案2】:

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

    对于第一个问题,我只是尽可能地扩展字符串,将所有ws 更改为 2 个vs。

    第二个有点棘手。我首先使用前面的方法扩展字符串,然后构建一个新字符串,其中任何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"))
    

    【讨论】:

    • 我可以获取您的电子邮件 ID user3543300 吗?因为我已经为同一个问题开发了不同的算法,但它的工作方式几乎没有什么不同
    • 我尝试了另一种方法,但它不起作用,有人可以帮忙吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 2017-10-28
    • 1970-01-01
    • 2021-10-29
    • 2021-10-10
    相关资源
    最近更新 更多