Recursive function question 55 from the Python Euler project

Asked 2 years ago, Updated 2 years ago, 97 views

def func(list,n):
    list1 = []
    for i in list:
        int1 = Lychrel(i)
        if symmetry(int1) == False:
            list1.append(int1)
    if n > 0:
        return func(list1,n-1)
    else:
        return len(list1)

I solved question 55 in Euler's project, but the recursive function looks a bit awkward You want to call a particular function 50 times and get a result, but instead of putting 50 in n in the above function, Is there any other way to write a function neatly?

python recursive

2022-09-20 19:36

1 Answers

from functools import lru_cache


# # @lru_cache
def lycrhrel(x: str, n: int) -> int:
    rev_sum = int(x) + int(x[::-1])
    n += 1
    x = str(rev_sum)
    print(f"   {x} {n} >", end="")
    if x == x[::-1]:
        print(f" !! {x} {n} !! |")
        return n
    if n > 50:
        print(" !!!! ")
        return 51
    return lycrhrel(x, n)


for n in range(1, 1000, 137):
    k = lycrhrel(str(n), 0)
    # # print()
    print(n, k)
    print("----")

   2 1 > !! 2 1 !! |
1 1
----
   969 1 > !! 969 1 !! |
138 1
----
   847 1 >   1595 2 >   7546 3 >   14003 4 >   44044 5 > !! 44044 5 !! |
275 5
----
   626 1 > !! 626 1 !! |
412 1
----
   1494 1 >   6435 2 >   11781 3 >   30492 4 >   59895 5 > !! 59895 5 !! |
549 5
----
   1372 1 >   4103 2 >   7117 3 > !! 7117 3 !! |
686 3
----
   1151 1 >   2662 2 > !! 2662 2 !! |
823 2
----
   1029 1 >   10230 2 >   13431 3 > !! 13431 3 !! |
960 3
----


2022-09-20 19:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.