我如何创建10的几何进度程序

时间:2018-11-23 22:20:14

标签: python yield

我想用Python 3编写一个程序,该程序包含一个myprice函数,该函数返回从1开始在几何上进展的X值。我希望X的值(即值的数量为3)和几何进展为10 ..这样我的程序将打印(1,10,100)。

我该怎么做?

先谢谢了。Nantia

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

        yield i

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

2 个答案:

答案 0 :(得分:0)

@techUser。您可以编写如下内容:

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

答案 1 :(得分:0)

基于@eapetcho的解决方案,

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

    The initial term is 1.

    Args:
        x   (int): number of terms to generate
        ftr (int): geometrical factor. Default is 10

    """

    start = 1

    i = 0
    while i < x:
        if i == 0:
            yield start
        else:
            start = start * fctr
            yield start
        i += 1

for n in myprice(20, 2):
  print(n)

输出

1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
131072
262144
524288