I don't think toString() or matches() doesn't use loops at all. The same applies to any other library functions like log() or pow(), or even round(). Quite possibly there are some loops inside, for no one says the CPU must support FPU intrinsic instructions.
1.Define the powers outside of the method, therefor it will be created only once. It should be in the constructor of the class but I'm not sure if Leetcode is creating an instance for every test or not.
2.You can use a set instead of a list to improve the search performance.
powers = set([pow(3, i) for i in xrange(200)])
def isPowerOfThree(self, num):
return num in powers