单字输入成功被交换,但不适用于问题奇怪的案例代码战士的句子?

问题描述 投票:0回答:2

[目前,我在cordwarrior中处理奇怪的案件问题。问题在于,将一个函数写入WeirdCase(在Ruby中为weirdcase),该函数接受一个字符串,并返回相同的字符串,每个单词的所有偶数索引字符均大写,每个单词的所有奇数索引字符均小写。刚说明的索引是从零开始的,因此第零个索引是偶数,因此该字符应大写。

我编写了该函数。它成功地交换了单个单词的大小写,但是不适用于多个单词或一个句子,因此我本来打算应用swapcase,但是它交换了所有不希望的句子单词。我不知道哪种情况适合::

   def to_weird_case(string):
    tot=""
    for i in range(len(string)):
        if i%2==0:
             tot+=string[i].upper()
        if i%2==1:
             tot+=string[i].lower()

    if string[i]==" " or i%2==1:
       to_weird_case(string[i:])
    return tot   

我得到此类型的错误:

 toWeirdCase
 should return the correct value for a single word (8 of 8 Assertions)
 should return the correct value for multiple words
'ThIs iS A TeSt' should equal 'ThIs Is A TeSt'
'LoOkS LiKe yOu pAsSeD' should equal 'LoOkS LiKe YoU PaSsEd'
'ThIs iS ThE FiNaL TeSt cAsE' should equal 'ThIs Is ThE FiNaL TeSt CaSe'
'JuSt kIdDiNg' should equal 'JuSt KiDdInG'
'Ok fInE YoU ArE DoNe nOw' should equal 'Ok FiNe YoU ArE DoNe NoW'\

链接到问题:https://www.codewars.com/kata/52b757663a95b11b3d00062d/train/python

我想到了另一种划分句子并将功能应用于每个单词的方法。


   def swap(string):
    tot=""
    for i in range(len(string)):
        if i%2==0:
             tot+=string[i].upper()
        if i%2==1:
             tot+=string[i].lower()
    if i%2==0:
        swap(string[i])
    return tot

  def to_weird_case(string):
      new=""
      for j in string:
          print(swap(j))
  print(to_weird_case('ThIs iS A TeSt'))

但是它使所有单词都大写。

python python-3.x string conditional-statements codewarrior
2个回答
1
投票
由于您的第一个功能对单个单词效果很好,所以我保留了它来实现真正的功能。

def to_weird_case(string): # actually your function tot="" for i in range(len(string)): if i%2==0: tot+=string[i].upper() if i%2==1: tot+=string[i].lower() if string[i]==" " or i%2==1: to_weird_case(string[i:]) return tot def to_weird_case_words(string): # my contribution, so that It work with strings with spaces return ' '.join([to_weird_case(s) for s in string.split(' ')]) print(to_weird_case('this is a test')) print(to_weird_case_words('this is a test'))

这里是我所做的解释:首先,有string.split('')组成一个单词列表。使用“这是一个测试”,输出为

[['this','is','a','test']。

然后,我用列表理解遍历它,并为每个单词应用您的函数。现在我们有了这个列表:

[['ThIs','Is','A','TeSt']。

现在我们需要加入该列表,在每个单词之间添加空格字符。这是通过''.join(list)完成的。因此,我们现在有了最终输出:

'Thiss a TeSt'

还有其他方法可以执行,但是我想使用您已经完成的操作。


0
投票
[Flag在True和False之间切换,如果出现空格,则将Flag设置为True,表示一个新单词正在开始;同样,如果遇到空格字符,则仅执行循环的以下部分
 if ch == " ":
            string += ch
            Flag = True
            continue

因为它具有continue语句

© www.soinside.com 2019 - 2024. All rights reserved.