Find palindromic numbers in both binary and ternary bases: Difference between revisions

m
→‎Functional Python: (tidied top level)
m (→‎Functional Python: (tidied top level))
Line 1,638:
def palinBoth():
'''Non finite stream of dually palindromic integers.'''
yield (0, '0', '0')
yieldibt = (1, '1', '1')
 
n = 2
yield ibt
while True:
vibt = until(isBoth)(succpsucc)(npsucc(ibt))
yield nthPal(vint(ibt[2], 3), ibt[1], ibt[2])
n = succ(v)
 
 
# isBoth :: (Int, String, String) -> Bool
def isBoth(nibt):
'''True if the digitsbinary ofstring n areis palindromic in(as
the ternary string is already known to be).
both binary and ternary representations.
'''
sb = showBase3(n)ibt[1]
b = bin(int(s + '1' + s[::-1], 3))[2:]
return b == b[::-1]
 
 
# nthPalpsucc :: (Int, String, String) -> (Int, String, String)
def nthPalpsucc(nibt):
'''The successornext triple of aindex, value.binary
'''Palindromic number constructed
fromand (palindromic) ternary digits'''string
n = 2'''
s = showBase3(n)
returnd int(s= + '1' + sibt[::-10], 3)
s = showBase3(nd)
bpal = bin(int(s + '1' + s[::-1], 3))[2:]
return (d, bin(int(pal, 3))[2:], pal)
 
 
Line 1,676 ⟶ 1,678:
def main():
'''Integers with palindromic digits in both binary and ternary'''
 
def label(k):
def go(sw):
s, w = sw
return getattr(s, k)(w, ' ') + ' '
return lambda sw: go(sw)
 
xs = take(6)(palinBoth())
mxd, b, t = xs[-1]
dwbw = len(str(mx)b)
bwtw = len(bin(mxt)) - 2
tw = len(showBase3(mx))
 
print(
fTable(
label('rjust')(('Decimal', dwlen(str(d)))) +
''.join(map(
label('center'),
[('Binary', bw), ('Ternary', tw)]
)) + '\n'
)(compose(str)(strfst))(
lambda xp: bin(x)p[2:1].center(bw, ' ') + ' ' +
showBase3(x)' ' + p[2].center(tw, ' ')
)(identity)(xs)
)
 
 
# GENERIC -------------------------------------------------
 
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def succcompose(xg):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
 
 
# succfst :: Enum (a, => ab) -> a
def fst(tpl):
'''First member of a pair.'''
return tpl[0]
 
 
# identity :: a -> a
def identity(x):
'''The identity function.'''
return x
 
 
# showIntAtBase :: Int -> (Int -> String) -> Int -> String -> String
Line 1,722 ⟶ 1,735:
return lambda toChr: lambda n: lambda rs: (
wrap(toChr, n, rs)
)
 
 
# succ :: Enum a => a -> a
def succ(x):
'''The successor of a value.
For numeric types, (1 +).
'''
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
 
Line 1,762 ⟶ 1,765:
 
# FORMATTING ----------------------------------------------
 
# label :: Method String -> (String, Int)
def label(k):
'''Stringifiction, using the named justification
method (ljust|centre|rjust) of the label,
and the specified amount of white space.
)'''
def go(sw):
ns, w = succ(v)sw
return getattr(s, k)(w, ' ') + ' '
return lambda sw: go(sw)
 
 
# fTable :: String -> (a -> String) ->
9,655

edits