Hofstadter Figure-Figure sequences: Difference between revisions

→‎Using cyclic iterators: replace with simpler and faster code: implicit stuff seem to work better
(→‎Using cyclic iterators: replace with simpler and faster code: implicit stuff seem to work better)
Line 1,085:
===Using cyclic iterators===
{{trans|Haskell}}
Following the pattern of [[Formal power series#Using cyclic iterators]], definesDefining R and S in terms of each other recursively, andas producesmutually infiniterecursive iteratorsgenerators. Follows directly from the definition of the R and S sequences.
<lang python>from itertools import islice, tee, count
 
def hofstadter_RSR():
n = 1
def deferred_R():
yield n
for i in R_temp:
for s in S():
yield i
n += s
def deferred_S():
yield n;
for i in S_temp:
yield i
 
def R_genS(S):
R_result, R_copy1 = tee(deferred_R(), 2)
yield 2
S_result, S_copy1 = tee(deferred_S(), 2)
yield 4
u = 5
for sr in countR(5):
if r <= u: continue;
for x in range(u, r): yield x
u = r + 1
 
def lst(s, n): return list(islice(s(), n))
def R_gen(S):
r = 1
yield r
for s in S:
r += s
yield r
R_temp = R_gen(S_copy1)
def S_gen(R):
yield 2
yield 4
next(R)
next(R)
r = next(R)
for s in count(5):
if s == r:
r = next(R)
else:
yield s
S_temp = S_gen(R_copy1)
 
print "R:", lst(R, 10)
return R_result, S_result
print(list(islice "S:", lst(S, 10)))
print sorted(lst(R, 40) + lst(S, 960)) == list(range(1,1001))
 
# perf test case
R, S = hofstadter_RS()
# print sum(list(islicelst(R, 10)10000000))</lang>
print(list(islice(S, 10)))
R, S = hofstadter_RS()
print(list(range(1, 1001)) == sorted(list(islice(R, 40)) + list(islice(S, 960))))</lang>
{{out}}
<pre>R: [21, 43, 57, 612, 818, 926, 1035, 1145, 1356, 1469]
<pre>
S: [12, 34, 75, 126, 188, 269, 3510, 4511, 5613, 6914]
[2, 4, 5, 6, 8, 9, 10, 11, 13, 14]
True
</pre>
Anonymous user