简体   繁体   English

Python中的梅森数公式

[英]Mersenne number formula in Python

A Mersenne number is any number that can be written as 2^p−1 for some p.梅森数是对于某个 p 可以写成 2^p−1 的任何数。 For example, 3 is a Mersenne number (2^2-1) as is 31 (2^5-1).例如,3 是梅森数 (2^2-1),31 (2^5-1) 也是。 Write a function that accepts an exponent p and returns the corresponding Mersenne number.编写一个接受指数 p 并返回相应梅森数的 function。

def mersenne number(p):
   return ((2**p)-1)

I'm just at the start of my programming course and I get stuck in simply things.我刚刚开始我的编程课程,我陷入了简单的事情。 I wrote that so far and have no idea how to make it to the end, and even if that is correct so far.到目前为止,我写了那篇文章,但不知道如何写到最后,即使到目前为止这是正确的。 I''l be grateful for any help from your side.我会很感激你的帮助。

You cannot have spaces in your function names. function 名称中不能有空格。

Usually in Python, we use underscores to separate words in functions:通常在 Python 中,我们使用下划线来分隔函数中的单词:

def mersenne_number(p):
   return ((2**p)-1)

Link to: PEP 8 -- Style Guide for Python Code链接到: PEP 8 -- Python 代码的样式指南

That's fine, except for one thing: The name of the function must not contain spaces.没关系,除了一件事:function 的名称不能包含空格。 So you might want to write def mersenne_number(p) instead.所以你可能想改写def mersenne_number(p) And you might want to validate that p is actually an integer:您可能想要验证p实际上是 integer:

def mersenne_number(p: int) -> int:
   if not isinstance(p, int):
       raise TypeError("p must be integer")

   return ((2**p)-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM