Global variables are evils, maybe. But what's wrong with a property of a class?!
class Solution(object): mem =  def isHappy(self, n): self.mem.append(n) S = 0 while n!=0: r = n%10 n = int(n/10) S += r*r if S == 1: return True elif S in self.mem: return False else: return self.isHappy(S)
You need to reset the global variable between test cases. Please read the FAQ for more details.