【问题标题】:how to reverse a sentence with a while loop如何用while循环反转句子
【发布时间】:2016-04-25 15:16:05
【问题描述】:

对于一个作业,我需要使用while 循环来反转一个列表,我就是做不到。

这是我必须帮助我开始的示例代码:

sentence = raw_int ("   ")
length = len(sentence) # determines the length of the sentence (how many characters there are)
index = length - 1 #subtracts one from the length because we will be using indexes which start at zero rather than 1 like len

while... #while the index is greater than or equal to zero continue the loop
letter = sentence[index] #take the number from the index in the sentence and assigns it to the variable letter

我需要在我的解决方案中使用它。

【问题讨论】:

  • 我不懂 Python,但很明显,您的 While 循环将查看变量“index”(因此,“while index > 0”)。在 while 循环中,您可能会从 index 中减去 1,变量“letter”将是您打印的字符。

标签: python while-loop reverse


【解决方案1】:
sentence = raw_input("   ")
length = len(sentence)
index = length - 1
reversed_sentence = ''

while index >= 0:
    #letter is the last letter of the original sentence
    letter = sentence[index] 
    #make the first letter of the new sentence the last letter of the old sentence
    reversed_sentence += letter 
    #update the index so it now points to the second to last letter of the original sentence
    index = index - 1 

print reversed_sentence

【讨论】:

    【解决方案2】:

    因为这是一个作业,我不会给你完整的代码。但我会给你两个“提示”。 1)如果每个字符都被“翻转”,则句子被颠倒。例如,'I ran fast'——翻转这句话首先交换'I'和'f',然后是空格和's'等等。 2)您可以使用如下语法:

    Sentence[i], sentence[len(sentence)-i] = sentence[len(sentence)-i], Sentence[i]
    

    这绝对足以让你继续前进。

    【讨论】:

      【解决方案3】:

      你可以这样做:

      new_sentence = list()
      sentence = list(raw_input("   "))
      
      while sentence:
          new_sentence.append(sentence.pop(-1))
      else:
          sentence = ''.join(new_sentence)
      

      【讨论】:

        猜你喜欢
        • 2021-11-16
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 2021-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-30
        相关资源
        最近更新 更多