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 |
from itertools import chain |
||
# |
# steadyPair :: Int -> [(String, String)] |
||
def |
def steadyPair(x): |
||
''' |
'''An empty list if x^2 is not suffixed, in decimal, |
||
by the decimal digits of x. Otherwise a list |
|||
containing a tuple of the decimal strings of (x, x^2) |
|||
''' |
''' |
||
⚫ | |||
return isSuffixOf( |
|||
return [(s, s2)] if s2.endswith(s) else [] |
|||
⚫ | |||
⚫ | |||
⚫ | |||
# |
# ------------------------ 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 |
||
''' |
''' |
||
ns = range(1, 1 + 10000) |
|||
xs = concatMap(steadyPair)(ns) |
|||
lambda x: 10000 > x, |
|||
w, w2 = [len(x) for x in xs[-1]] |
|||
print([n for n in ns if steadyPair(n)]) |
|||
print() |
|||
⚫ | |||
'\n'.join([ |
|||
f'{s.rjust(w, " ")} -> {s2.rjust(w2, " ")}' |
|||
⚫ | |||
⚫ | |||
) |
) |
||
⚫ | |||
print(f'{x} -> {x ** 2}') |
|||
# ----------------------- GENERIC ------------------------ |
# ----------------------- GENERIC ------------------------ |
||
# |
# concatMap :: (a -> [b]) -> [a] -> [b] |
||
def |
def concatMap(f): |
||
''' |
'''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( |
def go(xs): |
||
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 |
|||
1 -> 1 |
|||
5 -> 25 |
|||
6 -> 36 |
|||
25 -> 625 |
|||
76 -> 5776 |
|||
376 -> 141376 |
|||
625 -> 390625 |
|||
9376 -> 87909376</pre> |
9376 -> 87909376</pre> |
||