Are there any ways to improve this python code to count even numbers in a pascal triangle?

what is pascal's triangle used for
pascal's triangle example
pascal's triangle binomial expansion
nth row of pascal's triangle
pascal triangle java
pascal's triangle calculator
pascal's triangle row 10
odd numbers in pascal's triangle

This is a piece of code I wrote to count how many even numbers there are in the first 1023 rows of the pascal triangle. However, I feel like it may need to be improved, especially the function next_row.

def next_row(r):
    i = 0
    s = []
    while i < len(r) -1:
        s.append(r[i] + r[i+1])
        i += 1
    s.insert(0, 1)
    return s

def count_even(r):
    counter = 0
    for item in r:
        if item % 2 == 0:
            counter += 1
    return counter

def results(i, t, e):
    print('In the first ' + str(i) + ' lines of the pascal triangle, there are ' + str(t) + ' entries. ' + 
        str(e) + ' of them are even.')

r = [1]
even = 0
total = 0
for i in range (0, 1023):
    even += count_even(r)
    total += len(r)
    r = next_row(r)
    results(i+1, total, even)

For starter you should avoid both a while loop and an iteration over indices while reading the content of an array. Watch the loop like a native talk to get more insight. In your case, since you are interested in interating over consecutive values at once, you may have a look into the pairwise recipe.

Second, instead of patching your row after the computation of all central elements, you can provide a bigger row to start your computation from by adding 0 to both sides. And to avoid resizing lists in doing so, you can use itertools.chain for that.

Lastly, to get the 1023 first rows, you may want to provide a generator that gives an endless stream of rows from the pascal triangle and cut that generator short after 1023 rows using itertools.islice.

Revised code:

import itertools

def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

def next_row(row):
    larger_row = itertools.chain([0], row, [0])
    return [a + b for a, b in pairwise(larger_row)]

def pascal_triangle():
    row = [1]
    while True:
        yield row
        row = next_row(row)

def count_even(iterable):
    return sum(item % 2 == 0 for item in iterable)

def main(limit):
    even = total = 0
    for index, row in enumerate(itertools.islice(pascal_triangle(), limit), 1):
        even += count_even(row)
        total += len(row)
        print('In the first', index, 'lines of the pascal triangle, '
              'there are', total, 'entries.', even, 'of them are even.')

if __name__ == '__main__':

Is there an equation that represents the nth row in Pascal's triangle , is 1 5 10 10 5 1. Both numbers are the same. Write a Python program to check a triangle is equilateral, isosceles or scalene. An equilateral triangle is a triangle in which all three sides are equal. A scalene triangle is a triangle that has three unequal sides. An isosceles triangle is a triangle with (at least) two equal sides.

IMHO your code is OK, I would propose just using

for i in range(len(r) -1):
    s.append(r[i] + r[i+1])

instead of

while i < len(r) -1:
    s.append(r[i] + r[i+1])
    i += 1

PS If you instead use

for i in range(len(r) -1):
    s.append(r[i] ^ r[i+1])

You'll see that the results do not change, as suggested by @John Coleman, it works. But the Pascal triangle degenerates into a collection of 0s and 1s, if you print it out.

In this case, you can simplify count_even:

def count_even(r):
    return len(r)-sum(r)

Pascal's Triangle, . The "!" is "factorial" and means to multiply a series of descending natural numbers. Examples: 4! = 4 × 3 × 2 × 1 = 24. 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

Just making your code (first two functions) slightly less verbose using list comprehensions. By doing so, you avoid the need of initializing i=0 and an empty list s=[] and the while loop to keep track of the i. In your count_even function, you can also use the following counter = len(r[r%2==0]) provided r is an array (In your code it's a list).

def next_row(r):
    s = [r[i] + r[i+1] for i in range(len(r)-1)]
    s.insert(0, 1)
    return s

def count_even(r):
    counter =  len([i for i in r if i%2 == 0])
#   counter = len(r[r%2==0]) #  If 'r' is an array
    return counter

Rest I kept the same.

Patterns In Pascal's Triangle by Olivia Bogle on Prezi, is made of one's, counting, triangular, and tetrahedral numbers. String count() Parameters. count() method only requires a single parameter for execution. However, it also has two optional parameters: substring - string whose count is to be found. start (Optional) - starting index within the string where search starts. end (Optional) - ending index within the string where search ends.

To make the code more readable and also more compact, I suggest you the following solution with comments, f-strings and comprehensions (instead of classic for loops). The main idea is to store the content of each line, the total count of element in each line and the count of even elements in each line inside 3 lists. This way you keep all values of the Pascal triangle in a list, if needed later:

# Initialize first line
lines  = [[1]]  # list of contents of each line (lists)
evens  = [0]    # list of counts of even elements in each line (integers)
totals = [1]    # list of total counts of elements in each line (integers)

# Build next lines
for i in range(1023):
    print(f'In the first {i+1} lines of the pascal triangle, there are {sum(totals)} entries. {sum(evens)} of them are even.')
    lines.append([1] + [lines[i][j] + lines[i][j+1] for j in range(len(lines[i])-1)] + [1])
    evens.append(len([v for v in lines[-1] if v%2 == 0]))

Sum of the rows of Pascal's Triangle., What is the sum of the numbers in rows of Pascal's triangle? Pascal's Triangle can show you how many ways heads and tails can combine. This can then show you the probability of any combination. For example, if you toss a coin three times, there is only one combination that will give you three heads (HHH), but there are three that will give two heads and one tail (HHT, HTH, THH), also three that give one head and two tails (HTT, THT, TTH) and one for all Tails (TTT).

Odd numbers in N-th row of Pascal's Triangle, Prerequisite : Pascal's Triangle | Count number of 1's in binary representation of N THEOREM : The number of odd entries in row N of Pascal's Triangle is 2 raised to the Function to get no of set Python code to find the count of Please Improve this article if you find anything incorrect by clicking on the "​Improve  The any () method takes an iterable (list, string, dictionary etc.) in Python. When you run the program, the output will be: The any () method works in similar way for tuples and sets like lists. In case of dictionaries, if all keys (not values) are false, any () returns False. If at least one key is true, any () returns True.

Sum of all elements up to Nth row in a Pascal triangle, of an Array with a given number K · Number of subsets with same AND, OR and XOR values in an Array Given a row number n, and the task is to calculate the sum of all elements of each row up to nth row. Better Solution: Let's have a look on pascal's triangle pattern Python program to find sum of all elements. Use the combinatorial numbers from Pascal’s Triangle: 1, 3, 3, 1. The likelihood of flipping zero or three heads are both 12.5%, while flipping one or two heads are both 37.5%. Top 10 secrets of

Pascal's triangle, In mathematics, Pascal's triangle is a triangular array of the binomial coefficients. In much of the The pattern of numbers that forms Pascal's triangle was known well before Pascal's time. However, there is no possible way p itself can show up in the denominator, Parity: To count odd terms in row n, convert n to binary. The third row consists of the triangular numbers: 1, 3, 6, 10, \ldots. The fourth row consists of tetrahedral numbers: 1, 4, 10, 20, 35, \ldots. The fifth row contains the pentatope numbers: 1, 5, 15, 35, 70, \ldots. "Pentatope" is a recent term. Regarding the fifth row, Pascal wrote that since there are no fixed names for them, they might

  • Code Review
  • If all you want is the count of the even numbers, why bother to even calculate the numbers? Work mod 2. Make a 0-1 triangle and use the fact that exclusive or (the operator ^) corresponds to addition mod 2.
  • John Coleman I don't see what you mean, looks to me you are not dealing with the problem.
  • Maybe I catch it, you mean using only 0 or 1s instead of the full numbers? - Yes they are sufficient to get parity information.
  • The 0-1 triangle that it "degenerates" to is actually rather interesting: it is essentially Sierpinski's triangle. In any event, good answer.
  • I did not know... But you are right.…
  • making the code more compact does not necessarily increase its readability. In this case I think the original code is much more readable.
  • @Lorenzo Of course compaction is not readability. Most often they are not compatible. However I think that the application here is simple enough to be coded as I did with enough readability, but it's only my opinion. I also added comments detailing the data structures used.