如何修复末尾出现的多余单词?

huangapple go评论86阅读模式
英文:

How do I fix the extra word coming in the end?

问题

Your code appears to be working correctly for the most part. However, I've noticed an issue in the logic for handling cases where the length of the first string is greater than the length of the second string. To fix this issue, you can update the code like this:

words1 = "rmiiab"
words2 = "eanna"
if len(words1) > len(words2):
    maxLength = len(words1)
else:
    maxLength = len(words2)
result = []
for i in range(0, maxLength):
    if i < len(words1):
        result.append(words1[i])
    if i < len(words2):
        result.append(words2[i])
for letter in result:
    print(letter, end="")

With this modification, your code should produce the correct output: "remaininaab" when the length of the first string is greater than the length of the second string.

英文:

I am writing a code for adding strings alternatively. It is like this:
If we have 2 strings:

a = &quot;abcd&quot;
b = &quot;efgh&quot;

When we add them the solution should be "aebfcgdh". If there is any extra part of string in any variable it should be added in the end. Now moving onto my code. Here it is:

words1 = &quot;rmiiab&quot;
words2 = &quot;eanna&quot;
if len(words1) &gt; len(words2):
    maxLength = len(words1)
elif len(words1) == len(words2):
    maxLength = len(words1)
else:
    maxLength = len(words2)
result = []
extras = []
for i in range(0, maxLength):
    try:
        result.append(words1[i])
        result.append(words2[i])
    except IndexError:
        remainingWords = maxLength - i
        if len(words1) &gt; len(words2):
            extras.append(words1[-remainingWords])
        else:
            extras.append(words2[-remainingWords])
for word in extras:
    result.append(word)
for letter in result:
    print(letter, end=&quot;&quot;)

It is working completely fine but for one test case that is when the length of first string is greater than the length of string 2. In that case my code adds the last letter of extra words twice. I am unable to find the error. May someone help me. For the below code the output is:
remaininaabb when it should be remaininaab instead.

答案1

得分: 1

这是发生的原因是因为你在同一个try语句中首先索引了words1,然后是words2。在这种情况下,赋值操作被正确完成,但然后在第二个追加语句上失败,并再次追加了第一个数组的最后一个字母。你可以通过为每个追加操作创建单独的try语句或者事先计算每个迭代的精确次数,避免整个try/catch的想法来修复这个问题。

希望这能帮助!

英文:

This is happening because you are indexing words1 first and words2 second in the same try statement. In this case the assignment is being completed correctly, but then failing on the second append statement and appending the last letter of the first array again. You can fix this by creating separate try statements for each append or calculating an exact number of iterations for each beforehand and avoiding the whole try/catch idea.

Hope this helps!

答案2

得分: 0

except后面的代码会在字符串不均匀的情况下执行多次,因为它没有中断for循环。

try:
    result.append(words1[i])
    result.append(words2[i])

在这部分中,第一个append不会引发IndexError,因此会执行,并且即使第二个append引发IndexError,也会添加该字母。

你应该在except子句中的某个地方添加break以停止循环。

英文:

The code after except in executed multiple times if your strings are uneven, because it doesn't break for loop.

try:
    result.append(words1[i])
    result.append(words2[i])

In this part the first append does not cause IndexError, therefore is executed and the letter is added even if the second append throws IndexError.

You should add break somewhere in except clause to stop looping.

答案3

得分: 0

"zip"这两个单词,找到最短单词的长度,将任何更长的部分添加到collector中。

words1 = "rmiiab"
words2 = "eanna"

collector = ""
for a, b in zip(words1, words2): collector += a + b
min_len = min(map(len, (words1, words2)))
collector += words1[min_len:] + words2[min_len:]

print(collector) #remaininaab
英文:

zip the two words, find the length of the shortest word and add anything longer to the collector.

words1 = &quot;rmiiab&quot;
words2 = &quot;eanna&quot;

collector = &quot;&quot;
for a, b in zip(words1, words2): collector += a + b
min_len = min(map(len, (words1, words2)))
collector += words1[min_len:] + words2[min_len:]

print(collector) #remaininaab

答案4

得分: 0

标准库的做法是使用 itertools.zip_longest,它的工作方式类似于内置的 zip,但允许不同大小的可迭代对象:

from itertools import zip_longest, chain

words1 = "rmiiab"
words2 = "eanna"

"".join(chain(*zip_longest(words1, words2, fillvalue="")))
# 'remaininaab'

fillvalue 用于填充较短的可迭代对象。

文档:

英文:

The standard library way of doing this uses itertools.zip_longest which works like the built-in zip but allows for iterables of varying sizes:

from itertools import zip_longest, chain

words1 = &quot;rmiiab&quot;
words2 = &quot;eanna&quot;

&quot;&quot;.join(chain(*zip_longest(words1, words2, fillvalue=&quot;&quot;)))
# &#39;remaininaab&#39;

fillvalue is used to pad the shorter iterables.

Docs:

huangapple
  • 本文由 发表于 2023年6月22日 01:01:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定