python幸运数字判断_找到Python中筛子生成的第n个幸运数字

I came up with this, but is there a better way?

事实是,总会有更好的方法,剩下的问题是:它是否足以满足您的需求?

一种可能的改进是将所有这些变成发电机功能.这样,您只会在消耗时计算新值.我想出了这个版本,我只验证了大约60个术语:

import itertools

def _idx_after_removal(removed_indices, value):

for removed in removed_indices:

value -= value / removed

return value

def _should_be_excluded(removed_indices, value):

for j in range(len(removed_indices) - 1):

value_idx = _idx_after_removal(removed_indices[:j + 1], value)

if value_idx % removed_indices[j + 1] == 0:

return True

return False

def lucky():

yield 1

removed_indices = [2]

for i in itertools.count(3, 2):

if not _should_be_excluded(removed_indices, i):

yield i

removed_indices.append(i)

removed_indices = list(set(removed_indices))

removed_indices.sort()

如果要从此生成器中提取例如第100个术语,则可以使用itertools nth recipe:

def nth(iterable, n, default=None):

"Returns the nth item or a default value"

return next(itertools.islice(iterable, n, None), default)

print nth(lucky(), 100)

我希望这有效,并且毫无疑问有更多的代码改进空间(但如前所述,总有改进的余地!).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值