Utilizzo ricorsivo per trovare happy number.Cosa c'è che non va nel mio codice Python contenente la funzione ricorsiva?
Quello che segue è il mio codice Python:
deepth = 0
def is_happy_number(number):
astring = str(number)
global deepth
digits = [int(char) for char in astring]
sum_digit = sum([digit**2 for digit in digits])
if sum_digit == 1:
deepth = 0
return True
else:
deepth += 1
if deepth >800:
return False
return is_happy_number(sum_digit)
print '7',is_happy_number(7)
for number in range(1,11):
print number,is_happy_number(number)
I risultati sono:
7 True
1 True
2 False
3 False
4 False
5 False
6 False
7 False
8 False
9 False
10 True
quando prova il numero 7 da sola, restituisce 'Vero'. Mentre eseguo gli ultimi due codici raw, il numero 7 restituisce 'False'.
Non so quale parte sia errata.
Dopo alcuni minuti, trovo la parte sbagliata nel mio codice Python. E aggiungo:
deepth = 0
dopo:
if deepth > 800:
Con la ricordano @Will, trovo un'altra soluzione a questo problema. codice modificato è la seguente:
def is_happy_number(number, deepth=0):
astring = str(number)
digits = [int(char) for char in astring]
sum_digit = sum([digit**2 for digit in digits])
if sum_digit == 1:
return True
else:
deepth += 1
if deepth >800:
return False
return is_happy_number(sum_digit,deepth)
print '7',is_happy_number(7,0)
for number in range(1,10):
if is_happy_number(number,0):
print number,
Un'ipotesi selvaggia: la variabile "deepth globale" ha qualcosa a che fare con esso (a proposito, dovrebbe essere scritto "profondità"). –