Jump to content

Steady squares: Difference between revisions

→‎Python :: Functional: Updated first version to use concatMap and .endswith
(→‎Python :: Functional: Updated first version to use concatMap and .endswith)
Line 946:
<lang python>'''Steady squares'''
 
from itertools import count, takewhilechain
 
 
# isSteadysteadyPair :: Int -> Bool[(String, String)]
def isSteadysteadyPair(x):
'''TrueAn empty list if thex^2 squareis ofnot xsuffixed, in endsdecimal,
withby the decimal digits of x itself. 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)
)
 
 
# ------------------------- TESTTESTS -------------------------
# main :: IO ()
def main():
'''Roots of numbers with steady squares up to 10000
'''
xsns = takewhilerange(1, 1 + 10000)
xs = concatMap(steadyPair)(ns)
lambda x: 10000 > x,
w, w2 = [len(x) for x in count(0) if isSteady(x))xs[-1]]
 
print([n for n in ns if steadyPair(n)])
print()
)print(
'\n'.join([
f'{s.rjust(w, " ")} -> {s2.rjust(w2, " ")}'
for x(s, s2) in xs:
])
)
for x in xs:
print(f'{x} -> {x ** 2}')
 
 
# ----------------------- GENERIC ------------------------
 
# isSuffixOfconcatMap :: (Eq a) =-> [ab]) -> [a] -> Bool[b]
def isSuffixOfconcatMap(needlef):
'''TrueA ifconcatenated needlelist isover which a suffixfunction ofhas haystack.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(haystackxs):
dreturn = lenlist(haystack) - lenchain.from_iterable(needlemap(f, xs)))
return d >= 0 and (needle == haystack[d:])
return go
 
Line 990 ⟶ 998:
main()</lang>
{{Out}}
<pre>[1, 5, 6, 25, 76, 376, 625, 9376]
<pre>0 -> 0
 
1 -> 1
5 1 -> 25 1
6 5 -> 36 25
25 6 -> 625 36
76 25 -> 5776 625
376 76 -> 141376 5776
625 376 -> 390625 141376
625 -> 390625
9376 -> 87909376</pre>
 
9,659

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.