python code not running..

ritvij

rated R
here's the question:
define a procedure that takes in two inputs a list and a number(n) and outputs a new list that contains the original elements of list but repeated n times..

for ex:
if input list a is [1, 2, 3] and n=2
answer: [1,1, 2, 2, 3, 3]
or
if input list is [1, 0, 1] and n=0

my code:
Code:
def explode_list(a, n):
while(n!=0):
for e in a:
a.append(e)
n=n-1
a=a.sort()
return a

can anyone help as to where i went wrong..

nbaztec

Master KOD3R
here's the question:
define a procedure that takes in two inputs a list and a number(n) and outputs a new list that contains the original elements of list but repeated n times..

for ex:
if input list a is [1, 2, 3] and n=2
answer: [1,1, 2, 2, 3, 3]
or
if input list is [1, 0, 1] and n=0

my code:
Code:
def explode_list(a, n):
while(n!=0):
for e in a:
a.append(e)
n=n-1
a=a.sort()
return a

can anyone help as to where i went wrong..

You are destroying/decrementing the value of n after each while iteration. Make the while loop as
Code:
for i in range(0, n):
...

A better approach is scanning each element and duplicating it in a new list.

Code:
b = []
for e in a
for i in range(0, n):
b.append(e)
return b

• ritvij

ritvij

rated R
thanks a lot.. BTW, what was wrong in degrading the value of n??

nbaztec

Master KOD3R
thanks a lot.. BTW, what was wrong in degrading the value of n??

Since you need that value for each element e. The next element will have 0 value of n from your while loop.