1

Can someone help me with this problem. enter image description here

Here is my code but it is far away to the solution

def get_value_from_pyramid(l):
    for i in range(0,l):
        num=1
        for j in range(0,i+1):
            if i == j:
                num=1
            print(num, end=" ")
            num+=1
        print("\r")
aba2s
  • 452
  • 2
  • 18
  • You seem to have just 'tried' some code. I would take a long look at the image of the 'pyramid' and see if you can write a function which implements some of the more simple examples. For instance any of the calls where the `c` parameter is `0` should return `"1"`. I'm sure you could write that version of the function. Also note that the requirements seem to expect that the function `return`s a string rather than `print`ing things out. – quamrana Apr 15 '22 at 12:01
  • Los of thanks, for yours suggestions. I will implement this function since I know now it an C(n, p) one. – aba2s Apr 15 '22 at 12:34

1 Answers1

2

All you need is some basic math :)

If you are using python >= 3.8:

from math import comb

def get_value_from_pyramid(n, r):
    return comb(n, r)

If you're using an older version of python:

import operator as op
from functools import reduce

def get_value_from_pyramid(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer // denom

More info can be found here

Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50