你可以用有序的数字的迭代器从左至右这样
>>> 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