[英]Prime numbers function from R to Python
I wanted to rewrite my own "Prime numbers" fuction from R to Python. 我想将我自己的“ Prime数字”功能从R重写为Python。 In R it looks like this: 在R中,它看起来像这样:
prime_numbers <- function(x)
{
p <- 2
result <- NULL
while (p <= x)
{
if (x<3) lp <- c(2) else if (x<5) lp <- c(2,3) else if (x<7) l<- c(2,3,5) else lp <- c(2,3,5,7)
if (p%%2!=0 && p%%3!=0 && p%%5!=0 && p%%7!=0) result <- c(result,p)
p <- p+1
}
return(c(lp,result))
}
It's working properly. 运作正常。 I just have to set a number as a parameter and it prints all prime numbers smaller than this number. 我只需要设置一个数字作为参数,它就会打印所有小于此数字的素数。
I wrote this function in Python. 我用Python编写了此函数。
def prime_numbers (x):
p = 2
result = None
while p <= x:
if x<3:
lp = 2
elif x<5:
lp = [2,3]
elif x<7:
lp = [2,3,5]
else:
lp = [2,3,5,7]
if p%2!=0 and p%3!=0 and p%5!=0 and p%7!=0:
result = [result,p]
p = p+1
return [lp,result]
The result is close to being proper, but I receive something like this in console when I use 50 for example as a parameter. 结果几乎是正确的,但是当我使用50作为参数时,我在控制台中收到类似的信息。
[[2, 3, 5, 7], [[[[[[[[[[[None, 11], 13], 17], 19], 23], 29], 31], 37], 41], 43], 47]] [[2,3,5,7],[[[[[[[[[[[[[[[[[[[None,11],13],17],19],23],29],31],37],41] ,43],47]]
None is printed and list is composed in a weird way to me. 对我而言,没有打印任何内容,并且列表的编制方式很奇怪。 It seems to me as lists in Python are not as easy and flexible as vectors in R. 在我看来,Python中的列表不像R中的向量那样容易和灵活。
How can I get the same effect in Python as in R with using as much similar syntax as possible? 如何使用尽可能多的相似语法在Python中获得与R中相同的效果?
This should do it: 应该这样做:
def prime_numbers(x):
p = 2
result = [] # instead of "result = None"
while p <= x:
if x<3:
lp = 2
elif x<5:
lp = [2,3]
elif x<7:
lp = [2,3,5]
else:
lp = [2,3,5,7]
if p%2!=0 and p%3!=0 and p%5!=0 and p%7!=0:
result.append(p) # instead of "result = [result, p]"
p = p+1
return lp + result # instead of "[lp, result]"
>>> prime_numbers(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Like Professor_joykill mentioned, you should instantiate result as an empty list instead of as the value None. 就像上面提到的Professor_joykill一样,您应该将结果实例化为空列表而不是值None。
Then use append(p) to add your prime number to the list of prime numbers > 7. 然后使用append(p)将素数添加到素数> 7的列表中。
Lastly you concatenate your lists by using '+' instead of incorporating two lists into another list. 最后,您使用“ +”连接列表,而不是将两个列表合并到另一个列表中。
Hope this helps, 希望这可以帮助,
Koen 高恩
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.