首页 > 解决方案 > 如何创建一个 10 倍数的几何进度程序

问题描述

我想在 Python 3 中编写一个程序,其中包含一个 myprice 函数,该函数返回从 1 开始呈几何级数增长的 X 值。我希望 X 的值是值的数量为 3,几何级数为 10..这样我的程序就会打印(1,10,100)。

我怎样才能做到这一点?

在此先感谢.. 南蒂亚

def myprice(X,geometrical progress):
    i=0
    i += 1 
    while i < X:
        i =

        yield i

for i in my price(3,10):
    print(i)

标签: pythonyield

解决方案


@技术用户。您可以编写如下内容:

def myprice(x, geometrical_factor=10):
    """
    A generator of a geometrical progression. The default factor is 10.

    The initial term is 'start = 1';

    Parameter:
    x : int
      number of terms to generate
    geometrical_factor: int
      geometrical factor [default: 10]
    """
    start = 1

    i = 0 # Geometrical term counter
    while i < xterm:
        if i == 0:
            yield start
        else:
            start = start * geometrical_factor
            yield start
        i += 1

推荐阅读