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