0

I was trying to resolve the following problem:

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.

My code looks like this:

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)

When you run the code, you see that the generated ARC its not the ARC of the example above. Why? I found it. The "arv" changes with the "arc", and it should stay immutable.

Seems to me that python create a pointer of the variable "arc" to "arv". Can anyone explain me why this happen? And how I can solve the problem correctly?

7
  • is this a school assignment? Commented Nov 7, 2016 at 18:31
  • Because in Python assignment doesn't copy anything. Commented Nov 7, 2016 at 18:31
  • Its a college assignment @Olian04 Commented Nov 7, 2016 at 18:52
  • @Nelthar please read this meta.stackexchange.com/questions/18242/… Commented Nov 7, 2016 at 18:54
  • 1
    Please read Ned Batchelder's Facts and Myths about Python Names and Values. Commented Nov 7, 2016 at 19:15

2 Answers 2

2

The solution is to copy the list contents, instead of the list descriptor:

arc = arv[:]

or

arc = arv.copy()

The short reason is that this is how the language is defined. You can read about the history at various Python sites; the full explanation is beyond the range of StackOverflow's general purpose.

From a high level, this is how Python implements basic pointers: object assignment is to the original object, rather than making a copy. This saves on spurious object duplication: if you want a new copy, you have to be explicit about allocating more storage.

Please note that your original, arv, is not "immutable": that is a Python technical term. A list is a mutable object; a tuple is the immutable cognate.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help! xD
1

The correct thing to do is make a copy:

arc = arv.copy()

1 Comment

Thanks for this useful answer xD

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.