python - For Loop and Accumulator Pattern -


an old legend has wise man, when offered reward desired, requested first grandchild receive 1 coin, second grandchild receive twice many first, third receive twice many second, , on. how many coins last grandchild receive? how many coins grandchildren receive in all? function should accept number of grandchildren , return statement addressing both questions. ihave far

def grandchild_coins(number_of_grand_children):# not finished     coins=1     grand_child in range(number_of_grand_children):         coins=coins*2     return ' grand child' + str(grand_child) + ' ' + str(coins) + ' coins'    grandchild_coins(10)    out[33]: ' grand child9 1024 coins' 

how list how coins each grand child has ?

thanks guys

def grandchild_coins(number_of_grand_children):               # initalizes coins 1     coins=1     total_coins=[]  # grand_child in range entered code ran grand_child in range(number_of_grand_children):      # if grand_child number not 0 coins = coins*2     if grand_child !=0:         coins=coins*2         # prints coins each grand_child     print ' grand_child' + str(grand_child)  + str( coins)     total_coins.append(coins)          # returns total amount of coins    return sum(total_coins) + ' coins in total' 

it because return last element in range (grand_child equal 9 - range (10) means iteration 0 9) so, advice (keeping close code):

def grandchild_coins(number_of_grand_children):     coins=1     grand_child in range(number_of_grand_children):         if grand_child != 0: #where need keep 1 coinn first son             coins=coins*2         print(' grand child' + str(grand_child + 1) + ' ' + str(coins) + 'coins')       return true  grandchild_coins(10) 

and output:

 grand child1 1coins  grand child2 2coins  grand child3 4coins  grand child4 8coins  grand child5 16coins  grand child6 32coins  grand child7 64coins  grand child8 128coins  grand child9 256coins  grand child10 512coins 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -