你可以用有序的數字的迭代器從左至右這樣
>>> import math
>>> number = int(123456789)
>>> #Get the maximum power of 10 using a logarithm
>>> max_digit = int(math.log10(number))
>>> range_pow = xrange(max_digit, 0, -1)
>>> # pot is an iterator with 1000, 100, 10, 1...
>>> pot = (10**x for x in range_pow)
>>> #Get the digits one by one on an iterator
>>> digits = ((number/x)%10 for x in pot)
>>> l = list(digits)
>>> print l
[1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L]
然後你可以檢查序列存在......我在尋找一個簡單的方法來做到這一點通過迭代器,類似於狀態機來分析結果,但我不確定是否有內置的方法來執行此操作,而無需自行創建列表或製作有限狀態機...
您可以去這樣的事情,但我認爲它會殺死性能(與在迭代器上進行低級別的有限狀態解析相比),因爲您需要構建列表,而不是直接與迭代工作:
>>> print l
[1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L]
>>> find = [1,2,3]
>>> lf = len(find)
>>> for i in xrange(len(l)):
... if find == l[i:i+lf]:
... print 'Found!', i
Found! 1
Found! 11
編輯: 我特地用一種更具有迭代的方式來做事...的數字參數可以是 細化到從數創建列表,如有必要。
import math
from itertools import count
def find_digits_in_number(digits, number):
#Get the maximum power of 10 using a logarithm
max_digit = int(math.log10(number))
range_pow = xrange(max_digit, -1, -1)
# pot is an iterator with 1000, 100, 10, 1...
pot = (10 ** x for x in range_pow)
#Get the digits one by one on an iterator
dig = ((number/x) % 10 for x in pot)
#Current will store a moving windows with the
#size of the digits length to check if present
current = []
for i in digits:
current.append(next(dig))
digits = list(digits)
founds = []
#The basic loop is this...
#for digit, i in zip(dig, count()):
# if current == digits:
# founds.append(i)
# current.pop(0)
# current.append(digit)
#But it can also be optimized like this list comprehension,
#while it's much less readable
[ (founds.append(i) if current == digits else None,\
current.pop(0), current.append(digit)) \
for digit, i in zip(dig, count()) ]
#Check last posibility, with the last values
if current == digits:
founds.append(i + 1)
return founds
if __name__ == '__main__':
assert find_digits_in_number((3, 4, 5), 123456789) == [2, 12]
assert find_digits_in_number((3, 4), 123456789034) == [2, 10]
好像你真正想要的是一種能夠產生所有這樣的數字,而不是一種方法來測試,如果一些適合與否,因爲這將是更有效的,這是正確的? – James 2010-01-11 15:59:55
我不認爲有可能有一個發電機,而不是過濾器/篩,但如果你有我如何能夠這樣,這將是偉大的建議。 – Vincent 2010-01-11 18:19:26
我會指出在我們的宇宙中,289數字的整數幾乎是無用的。這是一個比宇宙中電子數量大得多的數字。實際上沒有一個架構可以存儲一個數字,就像一個單詞或其他任何東西一樣大,所以你並不是真的把它當作一個整數對字符串來處理。 – Triptych 2010-01-11 18:55:31