Steady squares: Difference between revisions

Content added Content deleted
(→‎Python :: Functional: Updated first version to use concatMap and .endswith)
Line 946: Line 946:
<lang python>'''Steady squares'''
<lang python>'''Steady squares'''


from itertools import count, takewhile
from itertools import chain




# isSteady :: Int -> Bool
# steadyPair :: Int -> [(String, String)]
def isSteady(x):
def steadyPair(x):
'''True if the square of x ends
'''An empty list if x^2 is not suffixed, in decimal,
with the digits of x itself.
by the decimal digits of x. Otherwise a list
containing a tuple of the decimal strings of (x, x^2)
'''
'''
s, s2 = str(x), str(x**2)
return isSuffixOf(
str(x)
return [(s, s2)] if s2.endswith(s) else []
)(
str(x ** 2)
)




# ------------------------- TEST -------------------------
# ------------------------ TESTS -------------------------
# main :: IO ()
# main :: IO ()
def main():
def main():
'''Roots of numbers with steady squares up to 10000
'''Roots of numbers with steady squares up to 10000
'''
'''
xs = takewhile(
ns = range(1, 1 + 10000)
xs = concatMap(steadyPair)(ns)
lambda x: 10000 > x,
(x for x in count(0) if isSteady(x))
w, w2 = [len(x) for x in xs[-1]]

print([n for n in ns if steadyPair(n)])
print()
print(
'\n'.join([
f'{s.rjust(w, " ")} -> {s2.rjust(w2, " ")}'
for (s, s2) in xs
])
)
)
for x in xs:
print(f'{x} -> {x ** 2}')




# ----------------------- GENERIC ------------------------
# ----------------------- GENERIC ------------------------


# isSuffixOf :: (Eq a) => [a] -> [a] -> Bool
# concatMap :: (a -> [b]) -> [a] -> [b]
def isSuffixOf(needle):
def concatMap(f):
'''True if needle is a suffix of haystack.
'''A concatenated list over which a function has been
mapped.
The list monad can be derived by using a function f
which wraps its output in a list, (using an empty
list to represent computational failure).
'''
'''
def go(haystack):
def go(xs):
d = len(haystack) - len(needle)
return list(chain.from_iterable(map(f, xs)))
return d >= 0 and (needle == haystack[d:])
return go
return go


Line 990: Line 998:
main()</lang>
main()</lang>
{{Out}}
{{Out}}
<pre>[1, 5, 6, 25, 76, 376, 625, 9376]
<pre>0 -> 0

1 -> 1
5 -> 25
1 -> 1
6 -> 36
5 -> 25
25 -> 625
6 -> 36
76 -> 5776
25 -> 625
376 -> 141376
76 -> 5776
625 -> 390625
376 -> 141376
625 -> 390625
9376 -> 87909376</pre>
9376 -> 87909376</pre>