Home > Back-end >  Printing Each Element In a List Double The Amount Of The Previous One
Printing Each Element In a List Double The Amount Of The Previous One

Time:01-06

Hello Im a bit of a noob .. Im trying to make the program print each element double the amount of the previous element starting with one time .. I found a solution but it seems clunky .. is there a better version .. here is the code .

a=['h','ha','hah','jaja','kkkkk']     
s=.5        
for x in range(len(a)):
    s=int(s*2)
    n=1
    for j in range (s):
        print(str(n) str(a[x]))
        n =1

CodePudding user response:

Your code is readable and functional as is, but if you want to slim it down you can cut down some assignments by using enumerate(), which is a python builtin that generates the incrementing variables s and n for you so you don't have to manage them yourself:

a=['h','ha','hah','jaja','kkkkk']     
for s, x in enumerate(range(len(a))):
    for n, j in enumerate(range(2**s)):
        print(str(n 1), str(a[x]))

Going by this approach means we're calculating powers by doing 2**s instead of doubling s every iteration, but this isn't a terribly material change. Also, if you pass multiple variables as separate parameters to print(), as print(a,b) instead of print(a b), print() will fill in a space for you automatically which is nice for readability.

CodePudding user response:

You could use the pow() function to calculate the next multiple of 2 on each iteration and use that to repeat print():

for i in range(len(a)):
  for j in range(pow(2, i)):
    print(a[i])
  •  Tags:  
  • Related