zoukankan      html  css  js  c++  java
  • Modifiers

    Sometimes it is useful for a function to modify the objects it gets as parameters. In that case, the changes are visible to the caller. increment, which adds a given number of seconds to a Time object, can be written naturally as modifier.

    def increment(self,seconds):
            self.second += seconds
            if (self.second>=60):
                self.second-=60
                self.minute+=1
            if(self.minute>=60):
                self.minute-=60
                self.hour+=1

    Is this function correct? What happens if the parameter seconds is much greater than sixty? In that case, it is not enough to carry once; we have to keep doing it until time.second is less than sixty. One solution is to replace the if statements with while statements. That would make the function correct, but not very efficient.

    Write a correct version of increment that doesn’t contain any loops

    def increment(self,seconds):
            self.second += seconds
            temp = int(self.second / 60)
            if (temp>=1):
                self.second-=60*temp
                self.minute+=temp
            temp = int(self.minute / 60)
            if(temp >=1):
                self.minute-=60*temp
                self.hour+=temp
            temp = int(self.hour / 24)
            if(temp>=1):
                self.hour-= 24*temp

    Anything that can be done with modifiers can also be done with pure functions. In fact, some programming languages only allow pure functions. There is some evidence that programs that use pure functions are faster to develop and less error-prone than programs that use modifiers. But modifiers are convenient at times, and functional programs tend to be less efficient.

    from Thinking in Python

     

  • 相关阅读:
    Educational Codeforces Round 66 (Rated for Div. 2)
    数学模板整理
    多项式全家桶
    [Scoi2016]背单词(trie+贪心)
    Codeforces Round #563 (Div. 2) 划水记
    应届生秋招可能会遇到的三个问题
    基于vue(element ui) + ssm + shiro 的权限框架
    ASP.NET 分页+组合查询 练习
    登录,注册页面练习
    HTML css 样式表
  • 原文地址:https://www.cnblogs.com/ryansunyu/p/4004022.html
Copyright © 2011-2022 走看看