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
answer: []

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
answer: []

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
 
Top Bottom