Yuyu
Yuyu

Reputation: 17

Returning a list in Python 3 as result of a function to make a geometric sequence

I got a task from my professor. The deadline is already over, but I am curious what the solution could be. I had to make a function which creates a geometric progression. It has three arguments, x0 - the initial value -, q - the common ratio -, and N - number of elements. The funtion has to work so, that if you give it only one parameter, q automatically sets to 0,5 and N to 10, if you give it 2 parameters, N shall be 10. And then of course it has to make this list of the geometric progression.

So I wrote this code:

def geometric_progression(x0,q=None,N=None):
"""This function creates a geometric progression consisting of N elements""" # Docstring

    sequence = []
    i = 1

    if (q and N) is None:
        q = 0,5
        N = 10
        while i<N+2:
            sequence.append(x0*(q**(i-1))
    return sequence
    elif N is None:
        N = 10
        while i<N+2:
            sequence.append(x0*(q**(i-1)))
    return sequence
    else: 
        while i<N+2:
            sequence.append(x0*(q**(i-1)))
    return sequence

But unfortunately it doesn't seem to work. Could you help me out?

Upvotes: 0

Views: 188

Answers (4)

Sergey Miletskiy
Sergey Miletskiy

Reputation: 487

Here is the answer, but I recommend you to read about default values for args in functions.

def geometric_progression(x0, q=0.5, N=10):
    """
    This function creates a geometric progression consisting of N elements
    :param x0: initial value
    :param q: common ratio
    :param N: number of elements
    :return: list of geometric sequence
    """

    sequence = [x0, ]

    for i in range(N - 1):
        x0 = x0 * q
        sequence.append(x0)

    return sequence

Upvotes: 0

H&#229;ken Lid
H&#229;ken Lid

Reputation: 23064

You can use a list comprehension:

def geometric_progression(x0, q=0.5, n=10):
    return [x0 * q ** p for p in range(n)]

Upvotes: 1

Mushif Ali Nawaz
Mushif Ali Nawaz

Reputation: 3866

I've corrected the syntactical and logical mistakes:

def geometric_progression(x0, q=0.5, n=10):
    sequence = []
    i = 1

    while i < n+2:
        sequence.append(x0*(q**(i-1)))
        i += 1

    return sequence

Upvotes: 0

Harsh Bhut
Harsh Bhut

Reputation: 238

If you do not give any parameter value to q & N then it automatically takes input as 5,10 respectively.

def geometric_progression(x0,q=5,N=10):
    sequence = []
     i = 1
     while i<N+2:
        sequence.append(x0*(q**(i-1)))
        i=i+1
     return sequence

Upvotes: 0

Related Questions