Image

Imagephd wrote in Imageru_python

Простое - не простое

Красивое рег. выражение: ^1?$|^(11+?)\1+$ - проверяет, является ли число простым. Нашёл в http://slobin.livejournal.com/349243.html. Как оно работает кратко, но вполне понятно объяснено здесь: http://zmievski.org/2010/08/the-prime-that-wasnt. Вот центральная часть: "The (11+?) sub-pattern matches strings 11, 111, etc. The \1+ matches whatever the sub-pattern matched, one or more times. So on the first try, the engine will match 11 and then attempt to match the same thing one or more times in the rest of the string. If it succeeds, the number is not a prime. Why? Because it just proved that the length of the string is divisible by 2 (the length of 11), therefore the original number is divisible by 2. If the overall match fails, the engine backtracks to the beginning and tries to match 111 two or more times and so on successively. If the first sub-pattern gets long enough (n/2 basically), and the overall match still fails, the number is a prime."

На мой взгляд, гениально. На Питоне оно, к сожалению, не такое красивое (чисто визуально). Но работает:
import sys
n = int(sys.argv[1])

import re
test_prime = re.compile('^1?$|^(?P<n>11+?)(?P=n)+$')

for i in range(n):
    print i, 'is', 'not' if test_prime.match('1'*i) else '   ', 'a prime'