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.
Related
I have given the sample input and sample output.
The EVEN index is only sorted and the ODD index are left as it is.
Sample Input :
5
3 9 1 44 6
Sample Output :
1 9 3 44 6
You can assign a striding subscript with the sorted values of that same subscript:
arr = [3, 9, 1, 44, 6]
arr[::2] = sorted(arr[::2]) # assign even items with their sorted values
print(arr) # [1, 9, 3, 44, 6]
Here's what you can do using modified bubble sort technique:
def sortEvens(arr):
arrLen = len(arr)
for i in range(0, arrLen, 2): # Jump by 2 units
for j in range(0, arrLen-i-2, 2): # Jump by 2 units
if arr[j] > arr[j+2]: # Comparing alternative elements
temp = arr[j]
arr[j] = arr[j+2]
arr[j+2] = temp
return arr
arr = [10, 45, 0, -34, 5, -899, 4]
print(sortEvens(arr))
# OUTPUT : [0, 45, 4, -34, 5, -899, 10]
positions-> 0 1 2 3 4 5 6
So, How to if given a list of integers and a number called x, return recursively the sum of every x'th number in the list.
In this task "indexing" starts from 1, so if x = 2 and nums = [2, 3, 4, -9], the output should be -6 (3 + -9).
X can also be negative, in that case indexing starts from the end of the list, see examples below.
If x = 0, the sum should be 0 as well.
For example:
print(x_sum_recursion([], 3)) # 0
print(x_sum_recursion([2, 5, 6, 0, 15, 5], 3)) # 11
print(x_sum_recursion([0, 5, 6, -5, -9, 3], 1)) # 0
print(x_sum_recursion([43, 90, 115, 500], -2)) # 158
print(x_sum_recursion([1, 2], -9)) # 0
print(x_sum_recursion([2, 3, 6], 5)) # 0
print(x_sum_recursion([6, 5, 3, 2, 9, 8, 6, 5, 4], 3)) # 15
I have been trying to do this function for 5 hours straight!!!
Would like do see how someone else would solve this.
This is the best i have come up with.
def x_sum_rec_Four(nums: list, x: int) -> int:
if len(nums) == 0:
return 0
elif len(nums) < x:
return 0
elif x > 0:
i = x - 1
return nums[i] + x_sum_rec_Four(nums[i + x:], x)
elif x < 0:
return x_sum_rec_Four(nums[::-1], abs(x))
My problem with this recursion is that the finish return should be:
if len(nums) < x:
return nums[0]
but that would pass things like ([2, 3, 6], 5)) -->> 2 when it should be 0.
If you really need to do it recursively, you could pop x-1 elements from the list before each call, follow the comments below:
def x_sum_recursion(nums, x):
# if x is negative, call the function with positive x and reversed list
if x < 0:
return x_sum_recursion(nums[::-1], abs(x))
# base case for when x is greater than the length of the list
if x > len(nums):
return 0
# otherwise remove the first x-1 items
nums = nums[x-1:]
# sum the first element and remove it from the next call
return nums[0] + x_sum_recursion(nums[1:], x)
print(x_sum_recursion([], 3)) # 0
print(x_sum_recursion([2, 5, 6, 0, 15, 5], 3)) # 11
print(x_sum_recursion([0, 5, 6, -5, -9, 3], 1)) # 0
print(x_sum_recursion([43, 90, 115, 500], -2)) # 158
print(x_sum_recursion([1, 2], -9)) # 0
print(x_sum_recursion([2, 3, 6], 5)) # 0
print(x_sum_recursion([6, 5, 3, 2, 9, 8, 6, 5, 4], 3)) # 15
However, you can do it in a one liner simple and pythonic way:
print(sum(nums[x-1::x] if x > 0 else nums[x::x]))
Explanation:
you slice the list using nums[start:end:increment] when you leave the end empty it slices from the starting position till the end of the list and increments by the increment specified
I am trying to work out a program that would calculate the diagonal coefficients of pascal's triangle.
For those who are not familiar with it, the general terms of sequences are written below.
1st row = 1 1 1 1 1....
2nd row = N0(natural number) // 1 = 1 2 3 4 5 ....
3rd row = N0(N0+1) // 2 = 1 3 6 10 15 ...
4th row = N0(N0+1)(N0+2) // 6 = 1 4 10 20 35 ...
the subsequent sequences for each row follows a specific pattern and it is my goal to output those sequences in a for loop with number of units as input.
def figurate_numbers(units):
row_1 = str(1) * units
row_1_list = list(row_1)
for i in range(1, units):
sequences are
row_2 = n // i
row_3 = (n(n+1)) // (i(i+1))
row_4 = (n(n+1)(n+2)) // (i(i+1)(i+2))
>>> def figurate_numbers(4): # coefficients for 4 rows and 4 columns
[1, 1, 1, 1]
[1, 2, 3, 4]
[1, 3, 6, 10]
[1, 4, 10, 20] # desired output
How can I iterate for both n and i in one loop such that each sequence of corresponding row would output coefficients?
You can use map or a list comprehension to hide a loop.
def f(x, i):
return lambda x: ...
row = [ [1] * k ]
for i in range(k):
row[i + 1] = map( f(i), row[i])
where f is function that descpribe the dependency on previous element of row.
Other possibility adapt a recursive Fibbonachi to rows. Numpy library allows for array arifmetics so even do not need map. Also python has predefined libraries for number of combinations etc, perhaps can be used.
To compute efficiently, without nested loops, use Rational Number based solution from
https://medium.com/#duhroach/fast-fun-with-pascals-triangle-6030e15dced0 .
from fractions import Fraction
def pascalIndexInRowFast(row,index):
lastVal=1
halfRow = (row>>1)
#early out, is index < half? if so, compute to that instead
if index > halfRow:
index = halfRow - (halfRow - index)
for i in range(0, index):
lastVal = lastVal * (row - i) / (i + 1)
return lastVal
def pascDiagFast(row,length):
#compute the fractions of this diag
fracs=[1]*(length)
for i in range(length-1):
num = i+1
denom = row+1+i
fracs[i] = Fraction(num,denom)
#now let's compute the values
vals=[0]*length
#first figure out the leftmost tail of this diag
lowRow = row + (length-1)
lowRowCol = row
tail = pascalIndexInRowFast(lowRow,lowRowCol)
vals[-1] = tail
#walk backwards!
for i in reversed(range(length-1)):
vals[i] = int(fracs[i]*vals[i+1])
return vals
Don't reinvent the triangle:
>>> from scipy.linalg import pascal
>>> pascal(4)
array([[ 1, 1, 1, 1],
[ 1, 2, 3, 4],
[ 1, 3, 6, 10],
[ 1, 4, 10, 20]], dtype=uint64)
>>> pascal(4).tolist()
[[1, 1, 1, 1], [1, 2, 3, 4], [1, 3, 6, 10], [1, 4, 10, 20]]
I'm attempting to write a function which takes a list and sums all the numbers in the list, except it ignores sections of the list starting with a list and extending to a 7, but continues to sum after the 7. Here is my code:
def sum67(nums):
i = 0
sum = 0
while i < len(nums):
k = 0
if nums[i] != 0:
sum += nums[i]
i += 1
if nums[i] == 6:
for j in range(i + 1, len(nums)):
if nums[j] != 7:
k += 1
if nums[j] == 7:
k += 2
i += k
Test cases show that 6 and proceeding numbers up until and including 7 are ignored while other numbers are added to the sum, and numbers after the 7 are also added to the sum (as was intended), but for some reason any 7 after the first 7 after a 6 is not summed - this is not what I want and I'm not sure why it's happening. Any suggestions?
Test case results:
[1, 2, 2 Expected: 5. My result: 5 (OK)
[1, 2, 2, 6, 99, 99, 7] Expected: 5. My result: 5 (OK)
[1, 1, 6, 7, 2] Expected: 4 My result: 4 (Chill)
[1, 6, 2, 2, 7, 1, 6, 99, 99, 7] Expected: 2 My result: 1 (Not chill)
[1, 6, 2, 6, 2, 7, 1, 6, 99, 99, 7] Expected: 2 My result: 1 (Not chill)
[2, 7, 6, 2, 6, 7, 2, 7] Expected: 18 My result: 9 (Not chill)
`
def sum67(nums):
# flag to know if we are summing
active = True
tot = 0
for n in nums:
# if we hit a 6 -> deactivate summing
if n == 6:
active = False
if active:
tot += n
# if we hit a seven -> reactivate summing
if n == 7 and not active:
active = True
return tot
The posted code is completely broken.
For example for a list without any 6,
i will be out of bounds of the list when reaching the nums[i] == 6 condition on the last element.
You need to completely rethink the conditions inside the loop.
Here's one approach that will work.
If the current number is 6,
then skip until you see a 7, without adding to the sum.
Otherwise add to the sum.
After performing either of these two actions (skipping numbers or adding to the sum),
increment i.
def sum67(nums):
i = 0
total = 0
while i < len(nums):
if nums[i] == 6:
for i in range(i + 1, len(nums)):
if nums[i] == 7:
break
else:
total += nums[i]
i += 1
return total
Here is an intermediate alternative for learning new Python techniques:
import itertools as it
def span_sum(iterable, start=6, end=7):
"""Return the sum of values found between start and end integers."""
iterable = iter(iterable)
flag = [True]
result = []
while flag:
result.extend(list(it.takewhile(lambda x: x!=start, iterable)))
flag = list(it.dropwhile(lambda x: x!=end, iterable))
iterable = iter(flag)
next(iterable, [])
return sum(result)
# Tests
f = span_sum
assert f([1, 2, 2]) == 5
assert f([1, 2, 2, 6, 99, 99, 7] ) == 5
assert f([1, 6, 2, 2, 7, 1, 6, 99, 99, 7]) == 2
assert f([1, 6, 2, 6, 2, 7, 1, 6, 99, 99, 7]) == 2
assert f([2, 7, 6, 2, 6, 7, 2, 7]) == 18
In principle, this function filters the input, collecting values into a result that meet your condition and drops the rest, then the sum is returned. In particular you can observe the following techniques:
extending a list
itertools, e.g. itertools.takewhile, itertools.dropwhile
iterators and generators
next() function and default values
sum() function
assertion testing
As part of my interest in learning Python, I've hit a stop when coming across an exercise that states:
Consider the expression (1 + x + x^2)^n and write a program which
calculates a modified Pascal’s triangle (known as the trinomial
triangle) for the coefficients of its expansion. Can you come up with
a simple rule (and prove that it works!) which would enable you to
write down the coefficients of this triangle?
So, I'm trying to write a code that prints out the trinomial triangle from a user input. This is the code I have so far:
import math
rows = 0 #We count how many rows we print
#We define a function that will calculate the triangle.
def calc(n, r):
if r == 0 or r == n:
return 1
return int(math.pow(1 + r + math.pow(r, 2), n))
#We define a function that append the values in an array.
def triangle(rows):
result = [] #We need an array to collect our results.
for count in range(rows): #For each count in the inputted rows
row = [] #We need a row element to collect the rows.
for element in range(count + 1):
#We add the function calculation to the row array.
row.append(calc(count, element))
#We add the row(s) to the result array.
result.append(row)
return result
number = int(input("How many rows do you want printed? "))
#We can now print the results:
for row in triangle(number):
rows += 1 #We add one count to the amount of rows
print("Row %d: %s" % (rows, row)) #Print everything
which returns
How many rows do you want printed? 5
Row 1: [1]
Row 2: [1, 1]
Row 3: [1, 9, 1]
Row 4: [1, 27, 343, 1]
Row 5: [1, 81, 2401, 28561, 1]
And as I understand it, the expected result should be:
1
1 1 1
1 2 3 2 1
1 3 6 7 6 3 1
1 4 10 16 19 16 10 4 1
I don't exactly know how to proceed from here. Any suggestions to point me in the right direction would be appreciated.
In the usual binomial version of Pascal's Triangle we can compute each value in a row by adding the two entries immediately above it. In the trinomial version we add three entries. The proof of this isn't hard, so I'll let you figure it out. ;)
Here's one way to do that in Python.
row = [1]
for i in range(8):
print(row)
row = [sum(t) for t in zip([0,0]+row, [0]+row+[0], row+[0,0])]
output
[1]
[1, 1, 1]
[1, 2, 3, 2, 1]
[1, 3, 6, 7, 6, 3, 1]
[1, 4, 10, 16, 19, 16, 10, 4, 1]
[1, 5, 15, 30, 45, 51, 45, 30, 15, 5, 1]
[1, 6, 21, 50, 90, 126, 141, 126, 90, 50, 21, 6, 1]
[1, 7, 28, 77, 161, 266, 357, 393, 357, 266, 161, 77, 28, 7, 1]
And just so that the line that I want to show appears as for example income 2 only shows me the second line of the triangle that is 1 1 1