Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+12 votes

For the mutation method, dnaString is passed in as a parameter. Do we need to make a copy of this variable before altering it in python, or does it not matter?

asked in CSC320 by (1 point)

2 Answers

+6 votes
 
Best answer

Python strings are immutable, just like in Java. Thus, you don't need to make a copy... but also, it means you can't mutate a string by changing individual letters. Instead, you must return a new string that is a mutated version of the original.

answered by (3.5k points)
+1 vote

Yes, you should make a copy of the param string. For me, I use this line to split DNA into a list of rules to make mutating the DNA easier.

actions = dnaString[:-1].split('_')

Note that [:-1] makes a copy of the string up to the length - 2 index.

I'm doing this because all state machines have a trailing '_' and splitting that would result in a trailing empty string in my list.

If you don't want to remove that trailing '_', you can do dnaString[:] to make a copy of the string.

answered by (1 point)
...