【问题标题】:Program to find permutation of a string - Error查找字符串排列的程序 - 错误
【发布时间】:2019-10-03 17:51:56
【问题描述】:

Python 程序

x=input("Enter any string:")

接受用户的输入

z=len(x)*len(x)
y=len(x)-1
l,m=0,0

交换值的函数

def swap(s1,s2):
    g=s1
    s1=s2
    s2=g
    print(s1,s2)
    return s1,s2

在这个for循环中交换要打印的值之后

for i in range(0,z,1):
    s=x
    swap(s[l],s[m+1])
    print(s)
     m=m+1
     if m==y:
        l=l+1
        m=0

代码无法正常工作,但以错误 IndexError: string index out of range 结尾

【问题讨论】:

  • 我用过但不工作
  • 如果输入少于 2 个字符,代码会出错,因为 s[1] 意味着 x 至少需要两个字符长。
  • 你的 swap 函数返回新的交换值,但你没有在调用者中分配它们,你只是丢弃它们。您需要执行 s[l], s[m+1] = swap(s[l], s[m+1]) 才能使其生效。但是根本不需要这个函数,直接做s[l], s[m+1] = s[m+1], s[l]
  • 其实s[1]表示字符串s的第二个字符

标签: python string function loops permutation


【解决方案1】:

可能是缺少括号,例如,它可能必须是:

if (m == y):

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    相关资源
    最近更新 更多