Python Array Addition recursion - python

So I was doing coderbyte's challenge and I have problems with one:
ArrayAdditionI, here's the statement of the problem:
'''
Using the Python language, have the function ArrayAdditionI(arr) take the array of numbers stored in arr
and return the string true if any combination of numbers in the array can be added up to equal the largest number in the array,
otherwise return the string false.
For example: if arr contains [4, 6, 23, 10, 1, 3] the output should return true because 4 + 6 + 10 + 3 = 23.
The array will not be empty, will not contain all the same elements, and may contain negative numbers.
'''
Since I couldn't do it, I researched for a solution and I found this:
def countFor(arr, m, s0):
if len(arr) == 0:
return False
a0 = arr[0]
ar = arr[1:]
sw = s0 + a0
if sw == m:
return True
if countFor(ar, m, sw):
return True
if countFor(ar, m, s0):
return True
return False
def ArrayAdditionI(arr):
m = max(arr)
arr.remove(m)
return str(countFor(arr, m, 0)).lower()
Now, I'm trying to understand what exactly the code does on every loop, I printed out the output for every loop of this list [4, 6, 23, 10, 1, 3]:
Input: [4, 6, 10, 1, 3] 23 0
a0: 4
ar: [6, 10, 1, 3]
sw: 4
Input: [6, 10, 1, 3] 23 4
a0: 6
ar: [10, 1, 3]
sw: 10
Input: [10, 1, 3] 23 10
a0: 10
ar: [1, 3]
sw: 20
Input: [1, 3] 23 20
a0: 1
ar: [3]
sw: 21
Input: [3] 23 21
a0: 3
ar: []
sw: 24
Input: [] 23 24
Input: [] 23 21
Input: [3] 23 20
a0: 3
ar: []
sw: 23
True
and I follow and understand what's going on, until the last three loops, I don't what part of the code makes it go from "Input: [] 23 24" to "Input : [] 23 21" to "Input: [3] 23 20".

Alright - here are the calls. Child calls are indented with respect to their parents:
Call countFor([4, 6, 10, 1, 3], 23, 0)
Call countFor([6, 10, 1, 3], 23, 4) from the first if
Call countFor([10, 1, 3], 23, 10) from the first if
Call countFor([1, 3], 23, 20) from the first if
Call countFor([3], 23, 21) from the first if
Call countFor([], 23, 24) from the first if
Call countFor([], 23, 21) from the second if
Call countFor([3], 23, 20) from the second if
Key point is that the second recursive call in countFor is not in an elif - it is an if in its own right, so after we come back up the call-stack, the second recursive call can also happen.

You haven't traced all of the logic, just the input and update at the top of the routine.
At [] 23 24, let's follow the logic:
if sw == m:
Nope ... that's 24 vs 23 ...
if countFor(ar, m, sw):
This produces your [] 23 24 line.
Since the array has 0 elements, the call immediately returns False.
if countFor(ar, m, s0):
This produces your [] 23 21 line. Again, the empty array gets an immediate False.
We fall one more line and return a False to the previous call.
The call that produced this one was the first countFor, calling with
if countFor([3], 23, 21):
where that 21 is the value of sw. We drop to the second call, the one with s0. At this point, s0 is 20, so the call looks like:
if countFor([3], 23, 20):
... and this call sees that 20+3 = 23 = m, so it returns True.
Does that clarify things for you?

just use the package itertools.combinations:
from itertools import combinations
def arrayChallenge(numbers):
expected_sum = max(numbers)
numbers.remove(expected_sum)
result = [seq for i in range(len(numbers), 0, -1)
for seq in combinations(numbers, i)
if sum(seq) == expected_sum]
return len(result) > 0
print(arrayChallenge([4, 6, 23, 10, 1, 3]))

Related

How can I print integers in one line inside the brackets (Fibonacci sequence with nth value)

Is it possible to print integers in one line inside the brackets? I would like my output to look like this:
[0 1 1 2 3 5 8 13 21 34]
But due to the way I wrote my code I can add brackets at the end of the list 0 1 1 2 3 5 8 13 21 34[] but not start and end.
My code:
n = int(input("Input a number to create Fibonacci sequence: "))
def fibo(n):
if n <=0:
print("Incorrect input")
return []
if n == 1:
return [0]
a,b = 0,1
for i in range(0,n):
print(a , end = " ",)
#assign a=b and b=a+b to get the sequence
a,b=b,a+b
print()
fibo(n)
The output format you are looking for is the one you get when you print a list.
You can use recursion to progressively build th eresulting list:
def fibo(n,a=0,b=1): return [a]+fibo(n-1,b,a+b) if n else [a]
print(fibo(10)) # fibonacci up to index 10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
It can also be done iteratively
n = 10 # first 10 fibonacci numbers
fibo = [0,1]
while len(fibo) < n: fibo.append(sum(fibo[-2:]))
print(fibo[:n])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

String to n*n matrix in python

I am an undergraduate student who loves programming. I encountered a problem today and I don't know how to solve this problem.
I looked for "Python - string to matrix representation" (Python - string to matrix representation) for help, but I am still confused about this problem.
The problem is in the following:
Given a string of whitespace separated numbers, create an nxn matrix (a 2d list where with the same number of columns as rows)and return it. The string will contain a perfect square number of integers. The int() and split() functions may be useful.
Example:
Input: '1 2 3 4 5 6 7 8 9'
Output: [[1,2,3],[4,5,6],[7,8,9]]
Example 2:
Input: '1'
Output: [[1]]
My answer:
import numpy as np
def string_to_matrix(str_in):
str_in_split = str_in.split()
answer = []
for element in str_in_split:
newarray = []
for number in element.split():
newarray.append(int(number))
answer.append(newarray)
print (answer)
The test results are in the following:
Traceback (most recent call last):
File "/grade/run/test.py", line 20, in test_whitespace
self.assertEqual(string_to_matrix('1 2 3 4'), [[1,2],[3,4]])
AssertionError: None != [[1, 2], [3, 4]]
Stdout:
[[4]]
as well as
Traceback (most recent call last):
File "/grade/run/test.py", line 15, in test_small
self.assertEqual(string_to_matrix('1 2 3 4'), [[1,2],[3,4]])
AssertionError: None != [[1, 2], [3, 4]]
Stdout:
[[4]]
as well as
Traceback (most recent call last):
File "/grade/run/test.py", line 10, in test_one
self.assertEqual(string_to_matrix('1'), [[1]])
AssertionError: None != [[1]]
Stdout:
[[1]]
as well as
Traceback (most recent call last):
File "/grade/run/test.py", line 25, in test_larger
self.assertEqual(string_to_matrix('4 3 2 1 8 7 6 5 12 11 10 9 16 15 14 13'), [[4,3,2,1], [8,7,6,5], [12,11,10,9], [16,15,14,13]])
AssertionError: None != [[4, 3, 2, 1], [8, 7, 6, 5], [12, 11, 10, 9], [16, 15, 14, 13]]
Stdout:
[[13]]
I am still confused how to solve this problem. Thank you very much for your help!
Assuming you don't want numpy and want to use a list of lists:
def string_to_matrix(str_in):
nums = str_in.split()
n = int(len(nums) ** 0.5)
return list(map(list, zip(*[map(int, nums)] * n)))
nums = str_in.split() splits by any whitespace, n is the side length of the result, map(int, nums) converts the numbers to integers (from strings), zip(*[map(int, nums)] * n) groups the numbers in groups of n, list(map(list, zip(*[map(int, nums)] * n))) converts the tuples produced by zip into lists.
Assuming you want to make this dynamic.
str_in = '1 2 3 4 5 6 7 8 9'
a = str_in.split(" ")
r_shape = int(math.sqrt(len(a)))
np.array([int(x) for x in a]).reshape(r_shape, r_shape)
Use split, create the 1D numpy array, then use reshape:
>>> s = '1 2 3 4 5 6 7 8 9'
>>> np.array([s.split(), dtype=int).reshape(3,3)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
If you don't know the size of the array, but you know it's square (same width / height), then you can use math.sqrt to get the inputs for reshape:
>>> import math
>>> s = '1 2 3 4 5 6 7 8 9'
>>> arr = np.array(s.split(), dtype=int)
>>> size = int(math.sqrt(len(arr)))
>>> arr.reshape(size, size)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Given that you will always get perfect square number of ints:
import numpy as np
input_strings = '1 2 3 4 5 6 7 8 9'
arr = np.array(input_strings.split(), dtype=int)
n = int(len(arr) ** 0.5)
arr.reshape(n, n)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Note: in your case, str.split is better off without explicit sep in order to work fine with multiple whitespaces in between the digits.
import numpy as np
def string_to_matrix(str_in):
str_in_split = str_in.split()
numbers = list(map(int, str_in_split))
size = r_shape = int(np.sqrt(len(numbers)))
return np.array(numbers).reshape(r_shape, r_shape)
This is why you always got: AssertionError: None != ...
assertEqual(A, string_to_matrix("...")) verifies if A is equals to the value returned by string_to_matrix. In your code you don't return anything so it is None
The other issue is how you splitted the string, the easier options is to split everything and convert to number, and then reshape to sqrt(number of elements). This assumes that input length can be splited to form a nxn matrix
import math
string = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16"
stringItems = string.split(" ")
numberOfItems = len(stringItems)
if math.sqrt(numberOfItems) - int(math.sqrt(numberOfItems)) == 0:
width = int(math.sqrt(numberOfItems))
array = []
finalArray = []
for i in range (0, width):
for j in range (0, width):
array.insert(j, stringItems[0])
stringItems.pop(0)
finalArray.insert(i, array)
array = []
print finalArray
else:
print "I require a string with length equal to a square number please"

Python Recursion in pascal's triangle [duplicate]

As a learning experience for Python, I am trying to code my own version of Pascal's triangle. It took me a few hours (as I am just starting), but I came out with this code:
pascals_triangle = []
def blank_list_gen(x):
while len(pascals_triangle) < x:
pascals_triangle.append([0])
def pascals_tri_gen(rows):
blank_list_gen(rows)
for element in range(rows):
count = 1
while count < rows - element:
pascals_triangle[count + element].append(0)
count += 1
for row in pascals_triangle:
row.insert(0, 1)
row.append(1)
pascals_triangle.insert(0, [1, 1])
pascals_triangle.insert(0, [1])
pascals_tri_gen(6)
for row in pascals_triangle:
print(row)
which returns
[1]
[1, 1]
[1, 0, 1]
[1, 0, 0, 1]
[1, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
However, I have no idea where to go from here. I have been banging my head against the wall for hours. I want to emphasize that I do NOT want you to do it for me; just push me in the right direction. As a list, my code returns
[[1], [1, 1], [1, 0, 1], [1, 0, 0, 1], [1, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1]]
Thanks.
EDIT: I took some good advice, and I completely rewrote my code, but I am now running into another problem. Here is my code.
import math
pascals_tri_formula = []
def combination(n, r):
return int((math.factorial(n)) / ((math.factorial(r)) * math.factorial(n - r)))
def for_test(x, y):
for y in range(x):
return combination(x, y)
def pascals_triangle(rows):
count = 0
while count <= rows:
for element in range(count + 1):
[pascals_tri_formula.append(combination(count, element))]
count += 1
pascals_triangle(3)
print(pascals_tri_formula)
However, I am finding that the output is a bit undesirable:
[1, 1, 1, 1, 2, 1, 1, 3, 3, 1]
How can I fix this?
OK code review:
import math
# pascals_tri_formula = [] # don't collect in a global variable.
def combination(n, r): # correct calculation of combinations, n choose k
return int((math.factorial(n)) / ((math.factorial(r)) * math.factorial(n - r)))
def for_test(x, y): # don't see where this is being used...
for y in range(x):
return combination(x, y)
def pascals_triangle(rows):
result = [] # need something to collect our results in
# count = 0 # avoidable! better to use a for loop,
# while count <= rows: # can avoid initializing and incrementing
for count in range(rows): # start at 0, up to but not including rows number.
# this is really where you went wrong:
row = [] # need a row element to collect the row in
for element in range(count + 1):
# putting this in a list doesn't do anything.
# [pascals_tri_formula.append(combination(count, element))]
row.append(combination(count, element))
result.append(row)
# count += 1 # avoidable
return result
# now we can print a result:
for row in pascals_triangle(3):
print(row)
prints:
[1]
[1, 1]
[1, 2, 1]
Explanation of Pascal's triangle:
This is the formula for "n choose k" (i.e. how many different ways (disregarding order), from an ordered list of n items, can we choose k items):
from math import factorial
def combination(n, k):
"""n choose k, returns int"""
return int((factorial(n)) / ((factorial(k)) * factorial(n - k)))
A commenter asked if this is related to itertools.combinations - indeed it is. "n choose k" can be calculated by taking the length of a list of elements from combinations:
from itertools import combinations
def pascals_triangle_cell(n, k):
"""n choose k, returns int"""
result = len(list(combinations(range(n), k)))
# our result is equal to that returned by the other combination calculation:
assert result == combination(n, k)
return result
Let's see this demonstrated:
from pprint import pprint
ptc = pascals_triangle_cell
>>> pprint([[ptc(0, 0),],
[ptc(1, 0), ptc(1, 1)],
[ptc(2, 0), ptc(2, 1), ptc(2, 2)],
[ptc(3, 0), ptc(3, 1), ptc(3, 2), ptc(3, 3)],
[ptc(4, 0), ptc(4, 1), ptc(4, 2), ptc(4, 3), ptc(4, 4)]],
width = 20)
[[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1]]
We can avoid repeating ourselves with a nested list comprehension:
def pascals_triangle(rows):
return [[ptc(row, k) for k in range(row + 1)] for row in range(rows)]
>>> pprint(pascals_triangle(15))
[[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1],
[1, 5, 10, 10, 5, 1],
[1, 6, 15, 20, 15, 6, 1],
[1, 7, 21, 35, 35, 21, 7, 1],
[1, 8, 28, 56, 70, 56, 28, 8, 1],
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1],
[1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1],
[1, 11, 55, 165, 330, 462, 462, 330, 165, 55, 11, 1],
[1, 12, 66, 220, 495, 792, 924, 792, 495, 220, 66, 12, 1],
[1, 13, 78, 286, 715, 1287, 1716, 1716, 1287, 715, 286, 78, 13, 1],
[1, 14, 91, 364, 1001, 2002, 3003, 3432, 3003, 2002, 1001, 364, 91, 14, 1]]
Recursively defined:
We can define this recursively (a less efficient, but perhaps more mathematically elegant definition) using the relationships illustrated by the triangle:
def choose(n, k): # note no dependencies on any of the prior code
if k in (0, n):
return 1
return choose(n-1, k-1) + choose(n-1, k)
And for fun, you can see each row take progressively longer to execute, because each row has to recompute nearly each element from the prior row twice each time:
for row in range(40):
for k in range(row + 1):
# flush is a Python 3 only argument, you can leave it out,
# but it lets us see each element print as it finishes calculating
print(choose(row, k), end=' ', flush=True)
print()
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
1 17 136 680 2380 6188 12376 19448 24310 24310 19448 12376 6188 2380 680 136 17 1
1 18 153 816 3060 8568 18564 31824 43758 48620 43758 31824 18564 8568 3060 816 ...
Ctrl-C to quit when you get tired of watching it, it gets very slow very fast...
I know you want to implement yourself, but the best way for me to explain is to walk through an implementation. Here's how I would do it, and this implementation relies on my fairly complete knowledge of how Python's functions work, so you probably won't want to use this code yourself, but it may get you pointed in the right direction.
def pascals_triangle(n_rows):
results = [] # a container to collect the rows
for _ in range(n_rows):
row = [1] # a starter 1 in the row
if results: # then we're in the second row or beyond
last_row = results[-1] # reference the previous row
# this is the complicated part, it relies on the fact that zip
# stops at the shortest iterable, so for the second row, we have
# nothing in this list comprension, but the third row sums 1 and 1
# and the fourth row sums in pairs. It's a sliding window.
row.extend([sum(pair) for pair in zip(last_row, last_row[1:])])
# finally append the final 1 to the outside
row.append(1)
results.append(row) # add the row to the results.
return results
usage:
>>> for i in pascals_triangle(6):
... print(i)
...
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
Without using zip, but using generator:
def gen(n,r=[]):
for x in range(n):
l = len(r)
r = [1 if i == 0 or i == l else r[i-1]+r[i] for i in range(l+1)]
yield r
example:
print(list(gen(15)))
output:
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 15, 6, 1], [1, 7, 21, 35, 35, 21, 7, 1], [1, 8, 28, 56, 70, 56, 28, 8, 1], [1, 9, 36, 84, 126, 126, 84, 36, 9, 1], [1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1], [1, 11, 55, 165, 330, 462, 462, 330, 165, 55, 11, 1], [1, 12, 66, 220, 495, 792, 924, 792, 495, 220, 66, 12, 1], [1, 13, 78, 286, 715, 1287, 1716, 1716, 1287, 715, 286, 78, 13, 1], [1, 14, 91, 364, 1001, 2002, 3003, 3432, 3003, 2002, 1001, 364, 91, 14, 1]]
DISPLAY AS TRIANGLE
To draw it in beautiful triangle(works only for n < 7, beyond that it gets distroted. ref draw_beautiful for n>7)
for n < 7
def draw(n):
for p in gen(n):
print(' '.join(map(str,p)).center(n*2)+'\n')
eg:
draw(10)
output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
for any size
since we need to know the max width, we can't make use of generator
def draw_beautiful(n):
ps = list(gen(n))
max = len(' '.join(map(str,ps[-1])))
for p in ps:
print(' '.join(map(str,p)).center(max)+'\n')
example (2) :
works for any number:
draw_beautiful(100)
Here is my attempt:
def generate_pascal_triangle(rows):
if rows == 1: return [[1]]
triangle = [[1], [1, 1]] # pre-populate with the first two rows
row = [1, 1] # Starts with the second row and calculate the next
for i in range(2, rows):
row = [1] + [sum(column) for column in zip(row[1:], row)] + [1]
triangle.append(row)
return triangle
for row in generate_pascal_triangle(6):
print row
Discussion
The first two rows of the triangle is hard-coded
The zip() call basically pairs two adjacent numbers together
We still have to add 1 to the beginning and another 1 to the end because the zip() call only generates the middle of the next row
# combining the insights from Aaron Hall and Hai Vu,
# we get:
def pastri(n):
rows = [[1]]
for _ in range(1, n+1):
rows.append([1] +
[sum(pair) for pair in zip(rows[-1], rows[-1][1:])] +
[1])
return rows
# thanks! learnt that "shape shifting" data,
# can yield/generate elegant solutions.
def pascal(n):
if n==0:
return [1]
else:
N = pascal(n-1)
return [1] + [N[i] + N[i+1] for i in range(n-1)] + [1]
def pascal_triangle(n):
for i in range(n):
print pascal(i)
Beginner Python student here. Here's my attempt at it, a very literal approach, using two For loops:
pascal = [[1]]
num = int(input("Number of iterations: "))
print(pascal[0]) # the very first row
for i in range(1,num+1):
pascal.append([1]) # start off with 1
for j in range(len(pascal[i-1])-1):
# the number of times we need to run this loop is (# of elements in the row above)-1
pascal[i].append(pascal[i-1][j]+pascal[i-1][j+1])
# add two adjacent numbers of the row above together
pascal[i].append(1) # and cap it with 1
print(pascal[i])
Here is an elegant and efficient recursive solution. I'm using the very handy toolz library.
from toolz import memoize, sliding_window
#memoize
def pascals_triangle(n):
"""Returns the n'th row of Pascal's triangle."""
if n == 0:
return [1]
prev_row = pascals_triangle(n-1)
return [1, *map(sum, sliding_window(2, prev_row)), 1]
pascals_triangle(300) takes about 15 ms on a macbook pro (2.9 GHz Intel Core i5). Note that you can't go much higher without increasing the default recursion depth limit.
I am cheating from the popular fibonacci sequence solution. To me, the implementation of Pascal's triangle would have the same concept of fibonacci's. In fibonacci we use a single number at a time and add it up to the previous one. In pascal's triangle use a row at a time and add it up to the previous one.
Here is a complete code example:
>>> def pascal(n):
... r1, r2 = [1], [1, 1]
... degree = 1
... while degree <= n:
... print(r1)
... r1, r2 = r2, [1] + [sum(pair) for pair in zip(r2, r2[1:]) ] + [1]
... degree += 1
Test
>>> pascal(3)
[1]
[1, 1]
[1, 2, 1]
>>> pascal(4)
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
>>> pascal(6)
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
Note: to have the result as a generator, change print(r1) to yield r1.
# call the function ! Indent properly , everything should be inside the function
def triangle():
matrix=[[0 for i in range(0,20)]for e in range(0,10)] # This method assigns 0's to all Rows and Columns , the range is mentioned
div=20/2 # it give us the most middle columns
matrix[0][div]=1 # assigning 1 to the middle of first row
for i in range(1,len(matrix)-1): # it goes column by column
for j in range(1,20-1): # this loop goes row by row
matrix[i][j]=matrix[i-1][j-1]+matrix[i-1][j+1] # this is the formula , first element of the matrix gets , addition of i index (which is 0 at first ) with third value on the the related row
# replacing 0s with spaces :)
for i in range(0,len(matrix)):
for j in range(0,20):
if matrix[i][j]==0: # Replacing 0's with spaces
matrix[i][j]=" "
for i in range(0,len(matrix)-1): # using spaces , the triangle will printed beautifully
for j in range(0,20):
print 1*" ",matrix[i][j],1*" ", # giving some spaces in two sides of the printing numbers
triangle() # calling the function
would print something like this
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Here is a simple way of implementing the pascal triangle:
def pascal_triangle(n):
myList = []
trow = [1]
y = [0]
for x in range(max(n,0)):
myList.append(trow)
trow=[l+r for l,r in zip(trow+y, y+trow)]
for item in myList:
print(item)
pascal_triangle(5)
Python zip() function returns the zip object, which is the iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together. Python zip is the container that holds real data inside.
Python zip() function takes iterables (can be zero or more), makes an iterator that aggregates items based on the iterables passed, and returns the iterator of tuples.
I did this when i was working with my son on intro python piece. It started off as rather simple piece, when we targeted -
1
1 2
1 2 3
1 2 3 4
However, as soon as we hit the actual algorithm, complexity overshot our expectations. Anyway, we did build this -
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
Used some recursion -
def genRow(row:list) :
# print(f"generatig new row below {row}")
# printRow(row)
l = len(row) #2
newRow : list = []
i = 0
# go through the incoming list
while i <= l:
# print(f"working with i = {i}")
# append an element in the new list
newRow.append(1)
# set first element of the new row to 1
if i ==0:
newRow[i] = 1
# print(f"1:: newRow = {newRow}")
# if the element is in the middle somewhere, add the surroundng two elements in
# previous row to get the new element
# e.g. row 3[2] = row2[1] + row2[2]
elif i <= l-1:
# print(f"2:: newRow = {newRow}")
newRow[i] = row[i-1] + row[i]
else:
# print(f"3 :: newRow = {newRow}")
newRow[i] = 1
i+=1
# print(newRow)
return newRow
def printRow(mx : int, row:list):
n = len(row)
spaces = ' ' *((mx - n)*2)
print(spaces,end=' ')
for i in row:
print(str(i) + ' ',end = ' ')
print(' ')
r = [1,1]
mx = 7
printRow(mx,[1])
printRow(mx,r)
for a in range(1,mx-1):
# print(f"working for Row = {a}")
if len(r) <= 2:
a1 = genRow(r)
r=a1
else:
a2 = genRow(a1)
a1 = a2
printRow(mx,a1)
Hopefully it helps.

Algorithm or Code for creating array, rule is as specified?

I want to create 2D array as below:
For Example:
For level 3:
7 => Array[2]
3 6 => Array[1]
1 2 4 5 => Array[0]
i.e. Array = [[1,2,4,5], [3,6], [7]]
.
For level 4:
15 => Array[3]
7 14 => Array[2]
3 6 10 13 => Array[1]
1 2 4 5 8 9 11 12 => Array[0]
i.e. Array = [[1,2,4,5,8,9,11,12], [3,6,10,13], [7,14], [15]]
What I need is a function taking number of level as argument returning Array as mentioned above.
i.e:
def function(level):
''' ..........................
...........................'''
return Array
Your data structure is recursive, so it's natural to use a recursive function to produce it.
The root node of the tree of depth depth is n = 2 ** depth - 1; it's more efficient to calculate that using bit shifting. The left subtree has a root node of n // 2, the right subtree is identical except that n // 2 is added to all its nodes.
Here's a recursive generator that produces the desired list.
def btree(depth):
if depth < 1:
return
n = (1 << depth) - 1
yield [n]
a = n // 2
for seq in btree(depth - 1):
yield seq + [u + a for u in seq]
lst = list(btree(4))[::-1]
print(lst)
output
[[1, 2, 4, 5, 8, 9, 11, 12], [3, 6, 10, 13], [7, 14], [15]]
If you want to print the tree rows in top-down order, you can just do this:
for row in btree(5):
print(row)
output
[31]
[15, 30]
[7, 14, 22, 29]
[3, 6, 10, 13, 18, 21, 25, 28]
[1, 2, 4, 5, 8, 9, 11, 12, 16, 17, 19, 20, 23, 24, 26, 27]
Hint: Here is the last row of numbers
def last_row(level):
m = 2 ** (level - 1)
L = [0 for i in range(m)]
L[0] = 1
k = 1
while k < m:
incr = 2 * k - 1
for i in range(k):
L[k+i] = L[i] + incr
k = incr + 1
return L
Here is another recursive solution that I figured. The left sub-tree value is floor(current value) and the right sub-tree value is (current value -1).
I pre-calculate the necessary powers of 2, but the draw-back is my passing of additional arguments (lists): In any case, hopefully this will be helpful for clarity when building a solution.
def driver(level):
if level <= 0:
return None
# initialize the list to have (level) columns
lst = [[] for i in range(level)]
# pre-calculate the necessary powers of 2
powers = [1]
for i in range(1, level+1):
powers.append(powers[i-1] << 1)
# call the main calculation function
calc(level, powers[level]-1, lst, powers)
return lst
def calc(level, val, lst, powers):
# add the value in pre-order
lst[level-1].append(val)
# base case, level is 1,
# do not make additional recursive calls here
if level > 1:
# calculate values in the left sub-tree
calc(level-1, val - powers[level-1], lst, powers)
# calculate values in the right sub-tree
calc(level-1, val-1, lst, powers)
print(driver(4))

Python recursive function for Pascal's Triangle

I'm trying to do a recursive function that generates a pascal's triangle up till the nth row, n being the user input. This is my code so far:
def printPascal(l,n):
while n != 1:
temp = [None]*(len(l)+1)
temp[0] = 1
temp[len(l)] = 1
for i in range(1,len(temp)-1):
temp[i] = l[i] + l[i-1]
l = temp
print(temp)
n = n-1
printPascal(l,n)
n = int(input("Enter a value for n:"))
l = [1,1]
printPascal(l,n)
And this is the error it gives me:
Traceback (most recent call last):
File "C:\Users\User\Desktop\test.py", line 16, in <module>
printPascal(l,n)
File "C:\Users\User\Desktop\test.py", line 11, in printPascal
printPascal(l,n)
File "C:\Users\User\Desktop\test.py", line 7, in printPascal
temp[i] = l[i] + l[i-1]
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
The thing is i kinda understand the issue and have tried tracing it to no avail. I know that somehow in the temp[i] = l[i] + l[i-1] code either the l[i] or l[i -1] is a "None" and i don't know why.
Thanks for your time and help in this little predicament of mine.
You have too much of your code inside the "for" loop. You replace the value of l with the value of temp before you've finished filling in all the values in temp.
The for loop should only contain the first statement.
There was a little indentation error in your code.
def printPascal(l,n):
while n != 1:
temp = [0]*(len(l)+1)
temp[0] = 1
temp[len(l)] = 1
for i in range(1,len(temp)-1):
temp[i] = l[i] + l[i-1]
l = temp
print(temp)
n = n-1
printPascal(l,n)
Instead of fixing your code, I'll show you an optimized approach:
def pascal_triangle(n, triangle=[[1]]):
if n > len(triangle):
last_row = triangle[-1]
next_row = [a+b for (a, b) in zip([0] + last_row, last_row + [0])]
return pascal_triangle(n, triangle + [next_row])
return triangle
How you can run it:
n = int(input("Pascal's triangle size: "))
print(*pascal_triangle(n), sep="\n")
Example output for input 9:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
Or using a prettier printing command:
print(*[" ".join(map(str, line)).center(40) for line in pascal_triangle(9)], sep="\n")
It would look like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
See this code running on ideone.com
You get this error because you not calculate and you not return sufficient information to the function.
try to debug or to follow your code..
You will fined the problem easily :)

Categories

Resources