【问题标题】:Year to Century Function年到世纪功能
【发布时间】:2018-03-03 13:36:30
【问题描述】:

问题:给定一年,返回它所在的世纪。第一个世纪从第 1 年到第 100 年,第二个世纪从第 101 年到第 200 年,以此类推。

我的代码:

def centuryFromYear(year):
    century = year/100 
    decimal = int(str(century[-2:-1]))
    integer = int(str(century)[:2])

    if decimal > 0:
        return integer + 1
    else:
        return integer

print(centuryFromYear(2017))

这在某些情况下似乎不起作用。比如年 = 2001 或年 = 2000。

谁能提供一段更简单的代码?

【问题讨论】:

    标签: python python-3.x algorithm


    【解决方案1】:

    我用 PHP 解决了这个问题。

    function centuryFromYear($year) {
        if ($year % 100 == 0){
            return $year/100;
        }
        else {
            return ceil($year/100);
        }
    }
    

    注意:-

    1. ceil() 函数将数字向上舍入为最接近的整数。
    2. 要将数字向下舍入到最接近的整数,请查看 floor() 函数。
    3. 要对浮点数进行四舍五入,请查看 round() 函数。

    【讨论】:

      【解决方案2】:

      我实际上有一个最优雅的代码之一,我将与你分享 C 版本。

      #include<math.h>
      #include<stdio.h>
      
      int main() {
        float x;
        int y;
      
        fscanf(stdin, "%f", &x);
        x = x / 100;
        y = ceil(x);
      
        fprintf(stdout, "Century %d ", y);
      
        return 0;
      }
      

      【讨论】:

        【解决方案3】:

        这对我有用:

        def whatCenturyIsX(x):
        
            #turn our input into a string for modification
            x = str(x)
            #separate the characters of x into a list for further use
            xlist = list(x)
            #set a boolean to contatin negativity or positivity of the number
            #if the "minus" sign is in x, set the boolean to true and remove the "minus" for easier handling of the variable
            #(the minus doesn't tell us anything anymore because we already set the boolean)
            negative = False
            if "-" in xlist:
                negative = True
                xlist.remove("-")
                for i in xlist:
                    x += i
        
            #to define what century year x is in, we are going to take the approach of adding 1 to the first n characters, when N is the number of digits - 2. This is proved. So:
            
            #also, we need the string to be at least 4 characters, so we add 0's if there are less
        
            if len(xlist) >= 4:
                pass
                
            
            else:
                if len(xlist) == 3:
                    xlist.insert(0, 0)
                    x = ""
                    for i in xlist:
                        x += str(i)
                elif len(xlist) == 2:
                    xlist.insert(0, 0)
                    xlist.insert(1, 0)
                    x = ""
                    for i in xlist:
                        x += str(i)
                elif len(xlist) == 1:
                    
                    xlist.insert(0, 0)
                    xlist.insert(1, 0)
                    xlist.insert(2, 0)
                    x = ""
                    for i in xlist:
                        x += str(i)
                
        
            n = len(xlist) - 2
            #j is the number formed by the first n characters.
            j = ""
            for k in range(0, n):
                #add the first n characters to j
                j += str(xlist[k])
                #finally form the century by adding 1 to j and calling it c.
            c = int(j) + 1
        
        
        
            #for the final return statement, we add a "-" and "B.C." if negative is true, and "A.C." if negative is false.
            if negative:
                xlist.insert(0, "-")
                x = ""
                for i in xlist:
                    x += str(i)
                return(str(x) + " is en the century " + str(c) + " B.C.")
            else:
                return(str(x) + " is en the century " + str(c) + " A.C.")
        

        【讨论】:

          【解决方案4】:
          • Python 简单单行解决方案 & JavaScript 单行解决方案

          • 在 javascript 中使用内置的数学函数进行单行回答

          • Math.ceil 函数总是将数字向上舍入到下一个最大值 整数或整数。

          // Python one-liner solution
          
          def centuryFromYear(year):
              return (year + 99) // 100
          
          
          // Javascript one-liner solution
          
          function centuryFromYear(year) {
          
              return Math.ceil(year/100)
          
          }
          

          【讨论】:

          • 为什么要发布一个针对python问题的js解决方案?
          • 对 Javascript 编码人员和算法查看很有帮助
          • 也发布了python解决方案
          • 请点赞,因为我已经发布了 python 解决方案并且所有测试用例都通过了
          【解决方案5】:
          year= int(input())
          century = (year - 1) // 100 + 1
          print(century)
          

          【讨论】:

          • 请解释它为什么起作用,OP 做错了什么以及如何纠正这个问题,以及为什么这个(岁)问题的其他答案不够好。 Ps 这看起来像是对另一个答案的改写
          【解决方案6】:

          首先从上下文中的year 中减去 1

          def centuryFromYear(year):
              return (year - 1) // 100 + 1
          

          适用于实现以下示例:

          print(centuryFromYear(2000))  # --> 20
          print(centuryFromYear(2001))  # --> 21
          print(centuryFromYear(2017))  # --> 21
          

          【讨论】:

            【解决方案7】:
            def centuryFromYear(year):
                return -(-year // 100)
            

            它相当古老,但这是正确的世纪输出。这是一个负面的楼层划分

            1700 // 100 = 17 1701 // 100 = 17 - (-1701 // 100) = 18

            它在 -1701//100 上进行楼层划分,即 -18

            适用于所有年份,并且只有 1 行

            【讨论】:

              【解决方案8】:

              您可以使用“数学”模块中提供的上限函数来获得所需的解决方案。

              def centuryFromYear(year):
               return math.ceil(year/100) 
              

              【讨论】:

                【解决方案9】:

                另一种适用于 0-9999 的替代方案更符合您的尝试。

                year = 2018
                cent = int(str(year).zfill(4)[:2])+1
                print(cent)
                

                返回:

                21
                

                【讨论】:

                  【解决方案10】:

                  这是正确答案:

                  def centuryFromYear(year):
                    if year % 100 == 0:
                      return year // 100 
                    else:
                      return year // 100 + 1
                  

                  【讨论】:

                    【解决方案11】:
                    a = int(input('Find the Century = ')) 
                    

                    将数字除以 100

                    century = a // 100 
                    

                    检查年份是否属于同一世纪

                    if(a%100 != 0):
                          century = century + 1
                    print(century)
                    

                    【讨论】:

                      【解决方案12】:

                      在python 3中可以使用整数除法,运算符//

                      def centuryFromYear(year):
                          return (year) // 100 + 1    # 1 because 2017 is 21st century, and 1989 = 20th century
                      
                      print(centuryFromYear(2017))  # --> 21
                      

                      请注意:这不考虑公元前世纪,它使用Dec 31st xy99 的截止日期,有时严格定义为Dec 31st xy00
                      more info here

                      如果您想在Dec 31st xy00 上设置更严格的截止值,您可能希望这样做:

                      def centuryFromYear(year):
                          return (year - 1) // 100 + 1    # 1 because 2017 is 21st century, and 1989 = 20th century
                      
                      print(centuryFromYear(2017))  # --> 21
                      

                      【讨论】:

                      • 你需要 (year - 1) 或者你把 100 的倍数放在错误的世纪。
                      • 这是一个很好的观点,但显然不是 OP 的首要任务,它正在寻找一种方法来进行整数除法......我为此留下了一个警告,以及一个关于“实践”的讨论的链接"(最好的和次优的)在这个领域。这是相当蹩脚的挑剔,尤其是您似乎没有完整阅读我的答案!
                      【解决方案13】:

                      使用整数除法,2000 年和 2017 年都可以正常工作:

                      1 + (year - 1) // 100  
                      

                      【讨论】:

                      • "properly" 用词不当,表达意见; “严格”肯定更合适。普遍接受的做法,确实是不准确的,是在Dec 31st xx99
                      • @Reblochon Masque 我们的日历中没有第 0 年,所以第 1 世纪是 1-100,第 2 世纪是 101-200,依此类推。是的,我知道有些人两次庆祝第三个千年 :)
                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2021-08-11
                      • 2021-04-14
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多