Prajeeth Muthukumar
Prajeeth Muthukumar

Reputation: 27

Not able to change the value of the variable

def paper_doll(text):
    text = list(text)
    l = len(text)
    i = 0
    while i < l:
        letter = text[i]`enter code here`
        print(text[i])
        text.insert(i+1, letter)
        text.insert(i+2, letter)
        i += 1
    return "".join(text)

*This Code is Made for the Following question Given a string, return a string where for every character in the original there are three characters In the while the value of the letter always remains the first character of the given string I would be grateful if somebody says me how to avoid this problem Thanks at advance

Upvotes: 0

Views: 48

Answers (1)

azro
azro

Reputation: 54168

Fix

The issue is that you update the same variable that you read one

With "abcd"

i=0 letter=a => insert a, becomes => aabcd
i=1 letter=a => insert a, becomes => aaabcd
...

To fix that : use another variable to be updated, and don't use i as indice, because it will be wrong after first iteration, and get aabcddcbabcd

You need to insert using the new position of the letter in the result

def paper_doll(text):
    result = list(text)
    l = len(text)
    i = 0
    while i < l:
        letter = text[i]
        j = result.index(letter)
        result.insert(j + 1, letter)
        result.insert(j + 2, letter)
        i += 1
    return "".join(result)

Improve

So I suggest another logic, an easier one : for each char, append it 3 times to a result

def paper_doll(text):
    result = ""
    for letter in text:
        result += letter * 3
    return result

Or even

def paper_doll(text):
    return "".join(letter * 3 for letter in text)

Upvotes: 2

Related Questions