lintcode入门篇十一

488. 快乐数

中文English

写一个算法来判断一个数是不是"快乐数"。

一个数是不是快乐是这么定义的:对于一个正整数,每一次将该数替换为他每个位置上的数字的平方和,然后重复这个过程直到这个数变为1,或是无限循环但始终变不到1。如果可以变为1,那么这个数就是快乐数。

样例

例1:

输入:19
输出:true
说明:

19是一个快乐的数字

     1 ^ 2 + 9 ^ 2 = 82
     8 ^ 2 + 2 ^ 2 = 68
     6 ^ 2 + 8 ^ 2 = 100
     1 ^ 2 + 0 ^ 2 + 0 ^ 2 = 1

例2:

输入:5
输出:false
说明:

5不是一个快乐的数字

25->29->85->89->145->42->20->4->16->37->58->89
再次出现89。
class Solution:
    '''
    大致思路:
    1.一个方法写每个数的平方和
    2.另一个方法写循环,判断你是否可以到达1
    '''
    def isHappy(self,n):
        dic = [n]
        while n!=1:
            n = self.getsum(n)
            dic.append(n)
            if dic.count(n) > 1:
                return False
        return True

    def getsum(self,num):
        s = str(num)
        res = 0
        for i in range(len(s)):
            res = res + int(s[i])**2
        return res

496. 玩具工厂

中文English

工厂模式是一种常见的设计模式。请实现一个玩具工厂 ToyFactory 用来产生不同的玩具类。可以假设只有猫和狗两种玩具。

样例

例1:

输入:
ToyFactory tf = ToyFactory();
Toy toy = tf.getToy('Dog');
toy.talk(); 
输出:
Wow

例2:

输入:
ToyFactory tf = ToyFactory();
toy = tf.getToy('Cat');
toy.talk();
输出:
Meow
输入测试数据 (每行一个参数)如何理解测试数据?
class Toy:
    '''
    大致解释:
    1.Toy类里面的talk方法,主要作用是如果当前传入的type不是cat也不是dog的时候,就引发异常,调用Toy().talk()
    2.Dog类和Cat类分别都继承了Toy类,Toy类里面的talk方法也继承了。
    
    '''
    def talk(self):
        raise NotImplementedError('This method should have implemented.')

class Dog(Toy):
    # Write your code here
    def talk(self):
        print('Wow')
    
class Cat(Toy):
    # Write your code here
    def talk(self):
        print('Meow')


class ToyFactory:
    # @param {string} shapeType a string
    # @return {Toy} Get object of the type
    def getToy(self, type):
        # Write your code here
        if type == 'Cat':
            return Cat()
        if type == 'Dog':
            return Dog()

原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12483291.html