zoukankan      html  css  js  c++  java
  • Pure functions

    In the next few sections, we’ll write two versions of a function called add_time, which calculates the sum of two Time objects. They demonstrate two kinds of functions: pure functions and modifiers. They also demonstrate a development plan I’ll call prototype and patch, which is a way of tackling a complex problem by starting with a simple prototype and incrementally dealing with the complications.

    class Time:
        """ represents the time of day
            attributes: hour, minute, second"""
        def print_time(self):
            print('%d:%d:%d' % (self.hour,self.minute,self.second))
        def after(self,t):
            if(self.hour < t.hour):
                return False
            elif(self.hour == t.hour):
                if(self.minute < t.minute):
                    return False
                elif(self.minute == t.minute):
                    if(self.second <= t.second):
                        return False
                    else: return True
            return True
    
    def add_time(t1,t2):
        total = Time()
        total.hour = t1.hour + t2.hour
        total.minute = t1.minute + t2.minute
        total.second = t1.second + t2.second
        if(total.second >=60):
            total.second -= 60
            total.minute +=1
        if(total.minute >=60):
            total.minute -=60
            total.hour +=1
        return total
    
    time = Time()
    time.hour = 11
    time.minute = 59
    time.second = 30
    time1 = Time()
    time1.hour = 11
    time1.minute = 59
    time1.second = 36
    time2 = Time()
    time2.hour = 11
    time2.minute = 58
    time2.second = 55

    Although this function is correct, it is starting to get big. We will see a shorter alternative later.

    from Thinking in Python

  • 相关阅读:
    友链
    CF496E Distributing Parts(贪心)题解
    CF786C Till I Collapse(根号分治)题解
    CF578B "Or" Game(贪心)题解
    CF433C Ryouko's Memory Note(贪心)题解
    Luogu4177 [CEOI2008]order(网络流)题解
    骗分专辑
    CF718A Efim and Strange Grade(贪心)题解
    prufer序列--学习笔记
    bzoj3450 Tyvj1952 Easy(期望DP)题解
  • 原文地址:https://www.cnblogs.com/ryansunyu/p/4003924.html
Copyright © 2011-2022 走看看