-2

I have this string (61,62,63,64) and i want to tranform the string into (61,61,62,62,62,62,63,64).

I want to duplicate the numbers in the string n times, the 61 i want to duplicate twice, the 62 i want to duplicate four times, how do i code something that duplicates a number in the string n times?

Can you possible do something like have annother string that tells the computer how many times to duplicate each number? (61, 62, 63, 64,) (2,4,1,1)

2 Answers2

1

if both your inputs are strings:

a = '(61, 62, 63, 64,)'
b = '(2,4,1,1)'

a = [i for i in a[1:-1].strip().replace(" ","").split(",")]
a.remove('')
b = [int(i) for i in b[1:-1].strip().replace(" ","").split(",")]
result = "("
for i in range(len(b)):
    for j in  range(b[i]):
        result += a[i]
        result += ", "
result = result.strip()[:-1]+")"
print(result)
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
0

Here is a possible solution (if rep is a string and not a tuple, you just need to do rep = eval(rep)):

s = "(61,62,63,64)"
rep = (2,4,1,1)

# convert the string to a tuple
t = eval(s)
# compute the result as a tuple
result = tuple(x for i, x in enumerate(t) for _ in range(rep[i]))
# convert the result into a string
result = str(result)

If you want something more compact:

s = "(61,62,63,64)"
rep = (2,4,1,1)

result = str(tuple(x for i, x in enumerate(eval(s)) for _ in range(rep[i])))

Be careful with using eval!! Check this question for more info.

Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50