【问题标题】:python, exponentiaiton with 'def' and 'for-loop'python,带有'def'和'for-loop'的指数
【发布时间】:2022-01-24 04:36:03
【问题描述】:

输入:

numbers = [1,2,3]
increment = 5

预期输出:

[1, 32, 243]

我的代码结果:

1
32
243

代码:

def power(x, y):

    if (y == 0): return 1
    elif (int(y % 2) == 0):
        return (power(x, int(y / 2)) *
            power(x, int(y / 2)))
    else:
        return (x * power(x, int(y / 2)) *
                power(x, int(y / 2)))

for number in numbers:
    exponentiation = power(number,increment)
    print(exponentiation)

我试图在没有 pow() 和 '**' 函数的列表中找到数字的平方根。我找到了每个数字的平方根,但我想知道如何将它们放在一个列表中。

【问题讨论】:

    标签: python for-loop if-statement increment exponentiation


    【解决方案1】:

    您正在打印指数,但您想要输出列表。 这就是你想要做的:

    # your function code above
    
    answer = []
    for number in numbers:
        exponentiation = power(number,increment)
        answer.append(exponentiation)
    
    print(answer)
    

    这将给出:

    [1, 32, 243]
    

    【讨论】:

      【解决方案2】:

      您应该在 for 循环之前创建一个空列表,然后在 for 循环内部,而不是打印每个数字,将其附加到列表中。然后在最后打印列表。

      def power(x, y):
      
          if (y == 0): return 1
          elif (int(y % 2) == 0):
              return (power(x, int(y / 2)) *
                  power(x, int(y / 2)))
          else:
              return (x * power(x, int(y / 2)) *
                      power(x, int(y / 2)))
      
      output_list = []
      
      for number in numbers:
          exponentiation = power(number,increment)
          output_list.append(exponentiation)
      
      print(output_list)
      

      【讨论】:

        【解决方案3】:

        你可以使用单行循环 -

        exponentiation = [power(number,increment) for number in numbers]
        print(exponentiation)
        #[1,32,243]
        

        【讨论】:

          【解决方案4】:

          你可以使用python库的pow函数在列表中追加值并打印列表而不是单个值

          numbers = [1,2,3]
          increment = 5
          l=[]
          for i in numbers:
              ex=pow(i,increment )
              l.append(ex)
          print(l)
          

          输出

          [1, 32, 243]
          

          【讨论】:

          • 感谢您的评论。但是,如果我是你,我会使用这个代码。(Exponentiation = [number ** increment for number in numbers])
          猜你喜欢
          • 1970-01-01
          • 2021-12-24
          • 1970-01-01
          • 2020-07-20
          • 1970-01-01
          • 1970-01-01
          • 2017-10-02
          • 2016-08-08
          • 1970-01-01
          相关资源
          最近更新 更多