开发者

Python. Project Euler Q35. Got a solution but I don't understand why other method doesn't work.

def rot_dig(x):
    y=''
    output=[x]
    listing=list(x)
    for i in range(1,len(x)):
        listing.append(listing[0])
     开发者_Python百科   del(listing[0])
        for i in listing:
            y=y+i
        output.append(y)
        y=''
    return output

import math

def prime_is(x,prime):
    for m in prime:
        if m<=math.sqrt(x):
            if x%m==0:
                return False
        else:
            return True

prime=[2]
for x in range(3,1000000):
    if prime_is(x,prime):
        prime.append(x)

primestr=[]
for x in prime:
    primestr.append(str(x))

sums=0
for x in primestr:
    count=0
    for y in rot_dig(x):
        if y in primestr:
            count+=1        
    if count==len(x):
        sums+=1
    else:
        for y in rot_dig(x):
            if y in primestr:
                primestr.remove(y)

print sums

When run with the bold code the solutions miss the final rotation. So if it looks at say 1193, it includes 1193, 3119, 9311 but not 1931. I have spent a while trying to work out why but I don't get it.

I have since edited the code to make it much quicker and solved the problem I had by simply removing the block of code, but I can't understand why it happens since surely that block of code will only be executed on non circular primes.


It's probably because your outer loop is for x in primestr: and the marked code removes items from primestr. You don't want to change primestr while looping over it that way. You could use a loop like while i < len(primestr) instead.

Some other improvements would be to compute sqrt outside the loop; to use a list comprehension instead of a loop to create primestr; and especially to use string slicing in rot_dig, it's way more complicated than it needs to be.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜