1

I'm taking computer science courses at my school I need to figure out some code for an exam, I need to change the variable name after I print it in a for-loop after decoding RLE. It's hard for me to explain but I hope you understand.

I've tried to look it up online but I can't find the proper way to phrase the problem I have.

import re

def decode(string):
    return re.sub(r'(\d+)(\D)', lambda m: int(m.group(1)) * m.group(2), string)

ch=int(input())

for x in range(0, ch):
    globals()['line%s' % x]=input()

for x in range(0, ch):
    print(decode(['line%s' % x]))

The result I'm looking for is after entering the RLE line by line (ch is the amount of lines), the function I made takes the variable names created by the for loop (so their names are line0, line1, line2 etc... until line(ch)) and then proceeds to decompress and print the RLE but I cant seem to get it to work

Edit: I might have made my problem not obvious and I apologize, I want to fix the last two lines of code so that the RLE is decompressed and printed in one for loop, I don't know if this is possible but I just want to know how (if) I can somehow make print(decode(['line%s' % x])) work, so like the variable line followed by a number gets changed while in the variable. Sorry I'm terrible at explaining things.

7
  • 7
    Why adding to globals? Add inputs into a list, loop over list and feed data to decode - this looks abusive - poor python. Commented May 1, 2019 at 20:37
  • 1
    @J decoding RLE : "5e" -> "eeeee" - some kind of reverse run length decoder Commented May 1, 2019 at 20:40
  • 3
    Don't create lists of variables like that. Use a real list! Commented May 1, 2019 at 20:40
  • 6
    Any time you find yourself creating variables with sequential names like line0, line1, line2, etc. you should just use a list. Other dynamic variable names should be dictionaries. Commented May 1, 2019 at 20:42
  • 1
    Seriously, sequentially named variables are a bad idea. Use a list so you can simply refer to line[0], line[1], ... line[x]. Commented May 1, 2019 at 20:50

1 Answer 1

5

Creating variable names on the fly is almost always the wrong thing to do. You just need a simple list of values:

lines = []
for x in range(ch):
    lines.append(input())

# or as a list comprehension,
# lines = [input() for x in range(ch)]

for x in lines:
    print(decode(x))
Sign up to request clarification or add additional context in comments.

1 Comment

I see the error of my ways now, i was horrifically over complicating things and should have just gone with the simple solution. Thank you so much @chepner !!!!

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.