我试图解决以下问题:
Suppose a virus that infected a university database and changed the AR (Academic Registry) of students. After some time, it has been found that the AR generated by the virus (ARV = x1 x2 x3 x4 x5 x6 x7 x8 x9) the correct AR (ARC = y1 y2 y3 y4 y5 y6 y7 y8 y9) could be obtained through the following operations:
y1 = x1, y2 = x2, y3 = x8, y4 = x7, y5 = x5, y6 = x6, y7 = x3, y8 = x4, y9 = x9
e.g., ARV = 197845602 --> ARC = 190645782
Make a program that reads ARV and gives ARC.
我的代码如下所示:
pt = input('Type the AR affected by the virus: ')
arv = list(pt)
arc = arv
arc[2] = arv[7]
arc[3] = arv[6]
arc[6] = arv[2]
arc[7] = arv[3]
jarc = ''.join(arc)
print('\nCorrect AR:',jarc)
运行代码时,您会看到生成的弧不是上面示例中的弧。为什么?我找到了。“arv”随着“arc”的变化而变化,它应该保持不变。你知道吗
在我看来,python创建了一个指向arv的变量arc的指针。有人能解释一下为什么会这样吗?我怎样才能正确地解决这个问题呢?你知道吗
解决方案是复制列表内容,而不是列表描述符:
或者
原因是语言就是这样定义的。您可以在各种Python站点上阅读历史;完整的解释超出了StackOverflow的一般用途范围。你知道吗
从较高的层次上讲,Python就是这样实现基本指针的:对象分配是对原始对象的,而不是复制。这就避免了虚假的对象复制:如果您想要一个新的拷贝,您必须明确地分配更多的存储。你知道吗
请注意,您原来的arvarv不是“不变的”:这是一个Python技术术语。列表是可变的对象;元组是不可变的同源对象。你知道吗
正确的做法是复制:
相关问题 更多 >
编程相关推荐