使用する要件(コメントでdel
言及したもの)を質問に追加することをお勧めします。
とにかく、これが私がそれを行う方法です。
def primesTo50():
'''Generator for prime numbers up to 50'''
primes = {2, 3, 5, 7, 9, 11 , 13 , 17, 19, 23, 29, 31, 37, 41, 43, 47}
yield from primes
def delIndices(L, indices, maxIndex = None):
'''Delete indices of the list up to list length or to the
max index if it is provided'''
if maxIndex is None:
maxIndex = len(L) - 1
indices_set = set(sorted(indices)) #don't try to delete the same index twice
for i in reversed(range(maxIndex + 1)): #must delete in reverse order
if i in indices_set: #check if i is in the indices to be removed
try:
del L[i]
except IndexError: #ignore error from trying to delete invalid indices
pass
return L
#testing
print(delIndices([1,2,3,4], primesTo50(), 50)) # [1, 2]
print(delIndices([1,2,3,4], (0,100), 200)) # [2,3,4]
次のような素数ジェネレーターを実行することもできます。
def primes(max):
'''Generator for prime numbers up to (not including) max'''
r = range(max)
for i in r:
divisors = range(2, i)
prime = True
for d in divisors:
if r%d == 0:
prime = False
break
if prime:
yield i
この問題には他にも多くの優れた解決策があります。私はこれを非常に迅速に作成しました(テストしていません-非常に遅いと確信しています)。素数の生成は数論の独自の分野であるため、IMO では、上記のように 50 までの素数をリストするだけの方がはるかに優れています。