>>> a = [1, 2] >>> type(a) <type 'list'> >>> type(iter(a)) <type 'listiterator'> >>> it = iter(a) >>> next(it) 1 >>> next(it) 2 >>> next(it) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> len(a) 2 >>> len(it) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type 'listiterator' has no len()
class count_iterator(object):
n = 0
def __iter__(self):
return self
def next(self):
y = self.n
self.n += 1
return y
>>> counter = count_iterator() >>> next(counter) 0 >>> next(counter) 1 >>> next(counter) 2 >>> next(counter) 3 >>> list(counter) # This will result in an infinite loop!
class SimpleList(object):
def __init__(self, *items):
self.items = items
def __getitem__(self, i):
return self.items[i]
>>> a = SimpleList(1, 2, 3) >>> it = iter(a) >>> next(it) 1 >>> next(it) 2 >>> next(it) 3 >>> next(it) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
Q(n)=Q(n-Q(n-1))+Q(n?Q(n?2))
class qsequence(object):
def __init__(self, s):
self.s = s[:]
def next(self):
try:
q = self.s[-self.s[-1]] + self.s[-self.s[-2]]
self.s.append(q)
return q
except IndexError:
raise StopIteration()
def __iter__(self):
return self
def current_state(self):
return self.s
>>> Q = qsequence([1, 1]) >>> next(Q) 2 >>> next(Q) 3 >>> [next(Q) for __ in xrange(10)] [3, 4, 5, 5, 6, 6, 6, 8, 8, 8][b]Generators [/b]
def count_generator(): n = 0 while True: yield n n += 1
>>> counter = count_generator() >>> counter <generator object count_generator at 0x106bf1aa0> >>> next(counter) 0 >>> next(counter) 1 >>> iter(counter) <generator object count_generator at 0x106bf1aa0> >>> iter(counter) is counter True >>> type(counter) <type 'generator'>
def hofstadter_generator(s):
a = s[:]
while True:
try:
q = a[-a[-1]] + a[-a[-2]]
a.append(q)
yield q
except IndexError:
return
import random
def bernoulli_process(p):
if p > 1.0 or p < 0.0:
raise ValueError("p should be between 0.0 and 1.0.")
while True:
yield random.random() < p
def von_neumann_extractor(process):
while True:
x, y = process.next(), process.next()
if x != y:
yield x
>>> def tent_map(mu, x0): ... x = x0 ... while True: ... yield x ... x = mu * min(x, 1.0 - x) ... >>> >>> t = tent_map(2.0, 0.1) >>> for __ in xrange(30): ... print t.next() ... 0.1 0.2 0.4 0.8 0.4 0.8 0.4 0.8 0.4 0.8 0.4 0.8 0.4 0.8 0.4 0.8 0.4 0.799999999999 0.400000000001 0.800000000003 0.399999999994 0.799999999988 0.400000000023 0.800000000047 0.399999999907 0.799999999814 0.400000000373 0.800000000745 0.39999999851 0.79999999702
def collatz(n): yield n while n != 1: n = n / 2 if n % 2 == 0 else 3 * n + 1 yield n
>>> # If the Collatz conjecture is true then list(collatz(n)) for any n will ... # always terminate (though your machine might run out of memory first!) >>> list(collatz(7)) [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] >>> list(collatz(13)) [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] >>> list(collatz(17)) [17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] >>> list(collatz(19)) [19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1][b]Recursive Generators [/b]
def permutations(items):
if len(items) == 0:
yield []
else:
pi = items[:]
for i in xrange(len(pi)):
pi[0], pi[i] = pi[i], pi[0]
for p in permutations(pi[1:]):
yield [pi[0]] + p
>>> for p in permutations([1, 2, 3]): ... print p ... [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1][b]Generator Expressions [/b]
>>> g = (x ** 2 for x in itertools.count(1)) >>> g <generator object <genexpr> at 0x1029a5fa0> >>> next(g) 1 >>> next(g) 4 >>> iter(g) <generator object <genexpr> at 0x1029a5fa0> >>> iter(g) is g True >>> [g.next() for __ in xrange(10)] [9, 16, 25, 36, 49, 64, 81, 100, 121, 144]
>>> g = (random.random() < 0.4 for __ in itertools.count()) >>> [g.next() for __ in xrange(10)] [False, False, False, True, True, False, True, False, False, True]
>>> sum(x ** 2 for x in xrange(10)) 285
from itertools import combinations, product
n = 4
d = 3
def visit(*indices):
print indices
# Loop through all possible indices of a 3-D array
for i in xrange(n):
for j in xrange(n):
for k in xrange(n):
visit(i, j, k)
# Equivalent using itertools.product
for indices in product(*([xrange(n)] * d)):
visit(*indices)
# Now loop through all indices 0 <= i < j < k <= n
for i in xrange(n):
for j in xrange(i + 1, n):
for k in xrange(j + 1, n):
visit(i, j, k)
# And equivalent using itertools.combinations
for indices in combinations(xrange(n), d):
visit(*indices)
import itertools import math def inversion_number(A): """Return the number of inversions in list A.""" return sum(1 for x, y in itertools.combinations(xrange(len(A)), 2) if A[x] > A[y]) def total_inversions(n): """Return total number of inversions in permutations of n.""" return sum(inversion_number(A) for A in itertools.permutations(xrange(n)))
>>> [total_inversions(n) for n in xrange(10)] [0, 0, 1, 9, 72, 600, 5400, 52920, 564480, 6531840] >>> [math.factorial(n) * n * (n - 1) / 4 for n in xrange(10)] [0, 0, 1, 9, 72, 600, 5400, 52920, 564480, 6531840]
def count_fixed_points(p): """Return the number of fixed points of p as a permutation.""" return sum(1 for x in p if p[x] == x) def count_partial_derangements(n, k): """Returns the number of permutations of n with k fixed points.""" return sum(1 for p in itertools.permutations(xrange(n)) if count_fixed_points(p) == k)
# Usage: >>> [count_partial_derangements(6, i) for i in xrange(7)] [265, 264, 135, 40, 15, 0, 1]
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有