为什么我的代码中有回溯和索引器?

2024-09-27 09:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我正在学习《程序员学徒》一书中的Python,我偶然发现了一个练习,我觉得我几乎解决了这个问题,但是当我执行程序时,我遇到了一个错误

以下是练习:

Write a program that takes a string and produces a new string that contains the exact characters that the first string contains, but in order of their ASCII-codes. For instance, the string "Hello, world!" should be turned into " !,Hdellloorw". This is relatively easy to do with list functions, which will be introduced in a future chapter, but for now try to do it with string manipulation functions alone.

我已经添加了下面的代码和错误消息作为图片

from pcinput import getString

entString=getString("Enter your string here: ")
yourString=entString.strip()


def positioner(oldPosition):
    newPosition=0
    x=0
    while x<len(yourString):
        if ord(yourString[oldPosition])>ord(yourString[x]):
            newPosition+=1
        x+=1
    return newPosition

i=0
y=0
newString=""

while y<len(yourString):
    if positioner(i)==y:
        newString+=yourString[i]
        y+=1
    elif positioner(i)<y:
        newString+=yourString[i]
    if i<len(yourString):
        i+=1
    else:
        i=0

print(newString)

我做错了什么?我是编程新手


Tags: thetoinstringlenifthat错误
1条回答
网友
1楼 · 发布于 2024-09-27 09:31:38

您得到了一个索引错误,因为调用行if positioner(i)==y:的值i等于yourString的长度yourString[oldPosition]正在访问一个不存在的索引

发生这种情况是因为循环条件(y<len(yourString))没有对i的值进行任何检查,而这正是导致问题的原因

其他一些快速评论:

  • 您可以使用yourString = input("Enter your string here: ")替换前四行,因为我不确定pcinput是什么,并且找不到任何同名的包
  • 代替使用while/x+=1构造,您可以使用for x in range(len(yourString)),这更整洁一些

相关问题 更多 >

    热门问题