【问题标题】:how can i create a geometrical progress program multiple of 10我如何创建一个 10 倍数的几何级数程序
【发布时间】:2018-11-23 22:20:13
【问题描述】:

我想在 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)

【问题讨论】:

    标签: python yield


    【解决方案1】:

    @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
    

    【讨论】:

      【解决方案2】:

      基于@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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-25
        • 1970-01-01
        • 2011-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        相关资源
        最近更新 更多