Saturday 15 January 2011

Fill in an array using loop with multiple variables (new to Python, old to C++ (back in the day)) -



Fill in an array using loop with multiple variables (new to Python, old to C++ (back in the day)) -

basically want create in python (this basic thought , not actual code):

n = 3 = n + 1 = [1, 3, 3, 1] b = [1, 2, 1] while n > 1:

check if n - if n even, in range(0,n), insert values array using formula below - b[n-i] = a[n-i-1] + a[n-i], value replace given value of b[] above code. - print out array - after each area filled, n+=1, i=n+1 applied, loop continues

check if n odd - same process except formula - a[n-i] = b[n-i-1] + a[n-i], value replace given value of a[] above code. - print out array - after each area filled, n+=1, i=n+1 applied, loop continues

this process loop , print each , go on on, arrays this: b = [1, 4, 6, 4, 1], = [1 5, 10, 10, 5, 1], b = [1, 6, 15, 20, 20, 15, 6, 1], etc.

here code have, i'm getting 'out of range' error.

n = 3 = n + 1 b = [1, 2, 1] = [1, 3, 3, 1] while n > 1: if n%2==0: print("even") in range(0,n): b[n-i].append(a[n-i-1]+a[n-i]) else: print("odd") in range(0,n): print("yay") a[n-i].append(b[n-i-1]+b[n-i]) if n%2==0: print(b) else: print(a) n +=1 = n + 1 print("loop")

the random prints throughout code test , see if making process. there previous code , haven't removed them yet.

hopefully can help me, can't find online loop increases size of array , fills @ same time.

sorry struggling code that's in sample. description can see want generate pascal's triangle. here's short snippet this.

a = [1, 1] _ in range(10): = [1] + [x+y (x,y) in zip(a[:-1], a[1:])] + [1] print

a[:-1] refers whole array except lastly element , a[1:] refers whole array except first element. zip combines first elements each array tuple , on. remains add together them , pad row ones 1 outside. _ used tell python, don't care variable - useful if want explicit not using range value except flow control.

python arrays

No comments:

Post a Comment