cool RegExpr

原文在這裡

判另方程式是否有解
ax + by = c => /^(.*)\1{a-1}(.*)\2{b-1}$/ 而被match的文字是用任意字元重覆c次

實測:13x + 19y = 70

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> if re.search(r'^(.*)\1{12}(.*)\2{18}$', '1'*70):
...     print 'Has solution.'
... else:
...     print 'No solution.'
...
Has solution.
想一下其實原理不難。

判別質數
/^1?$|^(11+?)\1+$/

實測:3877
>>> if not re.search(r'^1?$|^(11+?)\1+$', '1'*3877):
...     print 'Is a prime.'
... else:
...     print 'Not a prime.'
...
Is a prime.
質因數分解驗証:

>>> from math import sqrt
>>> def decompose(num):
...     for i in range(2, int(sqrt(num))):
...             if num %i == 0:
...                     print i,
...                     while num % i == 0: num /= i
...     print
...
>>> decompose(3877)
(blank)
=>正確

Just for fun :)

留言

這個網誌中的熱門文章

決定了!!!

P.S. I Love You

Tips: PPTP client on Openwrt