鱼C论坛

 找回密码
 立即注册
查看: 400|回复: 1

[作品展示] python 死循环整活

[复制链接]
发表于 2024-7-10 19:54:27 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
message = "the sky is blue"
left,right = 0,len(message)-1
b = []
for i in message:
    b.append(i)

while left < right:
    while not message[left].isalpha() and left < right:
            left +=1
    while not message[right].isalpha() and left < right:
            right -= 1

    b[left],b[right] = b[right],b[left]

c = (''.join(map(str,b)))
print(c)
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-7-10 19:54:45 | 显示全部楼层
好的,鱼油,你这个代码看起来想要做一个字符串翻转,只是遇到了死循环和一些小问题。别急,我帮你整整活儿。

首先,我们来分析一下你的代码:

1. `b =` 这一行缺少初始化。我们需要初始化一个空列表。
2. 循环中的条件 `while not message.isalpha() and left < right` 不太对,因为你实际上需要检查 `message[left]` 和 `message[right]` 是否是字母。
3. `b,b = b,b` 这行代码没有实际意义,看起来像是调皮的重复。
4. `c = (''.join(map(str,b)))` 这里没有大问题,只是有点多余。

让我们整理一下这个代码,同时加点幽默:

  1. message = "the sky is blue"
  2. left, right = 0, len(message) - 1

  3. # 初始化一个与 message 长度相同的列表
  4. b = list(message)

  5. # 进入死循环的秘密花园
  6. while left < right:
  7.     # 跳过非字母字符,左指针前进
  8.     while not message[left].isalpha() and left < right:
  9.         left += 1
  10.     # 跳过非字母字符,右指针后退
  11.     while not message[right].isalpha() and left < right:
  12.         right -= 1
  13.    
  14.     # 交换左右两边的字符
  15.     if left < right:
  16.         b[left], b[right] = b[right], b[left]
  17.         left += 1
  18.         right -= 1

  19. # 拼接成字符串
  20. c = ''.join(b)
  21. print(c)
复制代码


调皮的小细节:
1. 把字符串变成列表:`b = list(message)`。
2. 用两个指针 left 和 right 移动,跳过那些无关紧要(非字母)的字符。
3. `b[left], b[right] = b[right], b[left]` 交换两个位置的字符,实现翻转。
4. 最后,把列表 b 再拼接成一个字符串。

这样,我们就把 message 中的字母反转顺序了,同时保持其他字符的位置不变。快试试看吧!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-21 14:44

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表