-2
# Lists.
months = [6, 2, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

# Functions for algorithm.
def yearcode(y):
    """generate year-code using algorithm"""
    y = y % 100
    y = y + (y / 4) % 7
    return round(y)

def monthcode(m):
    """get month number from month-list"""
    return months[monthin - 1]

def daycode(d):
    """simplify day number for efficiency"""
    return d % 7

# Inputs.
dayayin = int(input("What Day in the Month?"))
monthin = int(input("What Month? E.g.- January is 1"))
yearin = int(input("What Year?"))

# Define variables for functions.
yearout = yearcode(yearin)
monthout = monthcode(monthin)
dayout = daycode(dayin)

# Final Add-Up and Output.
result = (dayout + monthout + yearout) % 7
print(weekdays[result])

错误是:“ParseError: bad input on line 17” 这个程序的目的是给出任何日期的星期几。正如你所看到的,它对我如何为我的利益给出函数的目的并不满意。我真的觉得我在这里错过了一些东西。

这是改进和工作版本(感谢您的帮助!)

# Lists.
months = [6, 2, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",  "Saturday"]

# Fruitful Functions for Algorithm.
def yearcode(y):
    """Year Code Generator Algorithm"""
    y = y % 100
    y = y + (y / 4) % 7
    return int(round(y))

def monthcode(m):
    """Retrieve Month Number from Month List"""
    return months[m - 1]

def daycode(d):
    """Simplify Day Input for Efficiency"""
    return d % 7

# Inputs.
dayin = int(input("What Day in the Month?"))
monthin = int(input("What Month? E.g.- January is 1"))
yearin = int(input("What Year?"))

# Define Variables for Functions.
yearout = yearcode(yearin)
monthout = monthcode(monthin)
dayout = daycode(dayin)

# Final Add-Up and Output.
result = int((dayout + monthout + yearout) % 7)
print(weekdays[result])
4

6 回答 6

4

由于混合空格和制表符的问题,您可能会遇到错误。尝试运行你的脚本

python -t yourscript.py

看看它是否告诉你什么。

也许,只使用calendar模块中的内置函数会更容易。

>>> import calendar
>>> calendar.weekday(2013,2,18)
0
>>> calendar.day_name[calendar.weekday(2013,2,18)]
'Monday'

作为旁注,运行您的代码,我没有收到 ParseError ——我收到了NameError因为dayin未定义。也许你不是故意要命名的dayayin

于 2013-02-18T17:17:45.633 回答
1

您应该在monthcode函数的主体中使用“m”而不是“monthin”

于 2013-02-18T17:22:58.697 回答
1

我已经看到了一些简单的错误:

可能是使用变量dayayin而不是 拼写错误dayin

dayayin = int(input("What Day in the Month?"))
...
dayout = daycode(dayin)

函数monthcode中,doesmothin从何而来?

def monthcode(m):
    """get month number from month-list"""
    return months[monthin - 1]

编辑: 修复这些后,并制作result一个整数

result = int((dayout + monthout + yearout) % 7)

脚本运行,但您的代码中仍然存在一些错误。当我输入我的出生日期 (19/05/1978) 时,它会在星期四返回,但我是在星期五出生的。

于 2013-02-18T17:25:29.413 回答
1

我同意 BioGeek

脚本运行,但您的代码中仍然存在一些错误。当我输入我的出生日期 (19/05/1978) 时,它会在星期四返回,但我是在星期五出生的。

与几个在线计算器相比,您的工作版本似乎要休息一天。例如

What Day in the Month?19
What Month? E.g.- January is 15
What Year?1942
Monday

但其他计算器显示为Tuesday.

于 2013-02-18T19:40:08.767 回答
0

您是否尝试过删除该行并手动重新输入?我经常看到人们,尤其是 Mac 用户,输入不可见的 Unicode 字符(如果我没记错的话,alt+空格)。这可能是您的问题的根源。

于 2013-02-18T17:21:32.787 回答
0

正如我在另一个答案中指出的那样,当我输入我的出生日期时,它给出了错误的答案。

更具体地说,当您尝试 2013 年的日期时,您的代码会给出正确答案,但一旦您尝试将其用于更早或将来的日期,它返回错误答案的概率为 81.76%。其中,它没有考虑闰年,也没有补偿不是 21 世纪的日期。

试图找出你哪里出错了,我需要知道你使用的是哪种算法。谷歌搜索列表[6, 2, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]让我进入了这个页面(pdf),它有非常详细的描述,但还有几个额外的步骤,然后你现在在你的算法中。

所以这是我对该算法的实现。从公历开始到 2300 年,我根据mgilsoncalendar提供的解决方案检查了它。

import datetime
import calendar

months = [6, 2, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday", "Sunday"]
centuries = {17: 5,
             18: 3,
             19: 1,
             20: 0,
             21: -2,
             22: -4}

def day_of_week_biogeek(day, month, year):
    # This algorithm is only valid for the Gregorian calendar
    # which began on September 14, 1752.
    if year <= 1752 and month <= 9 and day < 14:
        raise RuntimeError("This algorithm is only valid for the Gregorian " + \  
                           "calendar which began on September 14, 1752.")
    if year >= 2300:
        raise RuntimeError("This algorithm is only valid for the Gregorian " + \
                           "calendar up till December 31, 2299.")


    # Take multiples of 28 from the the last 2 digits of the year
    y = divmod(year, 100)[1] % 28

    # Add a quarter of the nearest multiple of 4 below the number,
    y += divmod(y, 4)[0]

    # Take away 7 or multiples of 7. This leaves us the year code
    y = y % 7

    # The code for the month from the table above
    m = months[month - 1]

    # If it is a leap year AND the month is January or February, subtract 1
    if is_leap_year(year) and month in [1,2]:
        m -= 1

    # Take away 7 or multiples of 7 from the day
    d = day % 7

    # Add the codes for the year, the month and the day
    result = y + m + d

    # Add 1 if the date is in the 1900s
    result += centuries[divmod(year, 100)[0]]

    # Take away 7 or multiples of 7
    result = result % 7

    # The final number indicates day of the week
    return weekdays[result]

def is_leap_year(year):
    # Leap years are the years evenly divisible by 4
    # unless it ends in 00 and is a multiple of 400
    if not year % 400:
        return True
    elif not year % 100:
        return False
    elif not year % 4:
        return True
    return False

# original code by user2080262
def yearcode(y):
    """Year Code Generator Algorithm"""
    y = y % 100
    y = y + (y / 4) % 7
    return int(round(y))

def monthcode(m):
    """Retrieve Month Number from Month List"""
    return months[m - 1]

def daycode(d):
    """Simplify Day Input for Efficiency"""
    return d % 7


def day_of_week_user2080262(dayin, monthin, yearin):
    yearout = yearcode(yearin)
    monthout = monthcode(monthin)
    dayout = daycode(dayin)
    result = int((dayout + monthout + yearout) % 7)
    return weekdays[result]

# alternate solution using builtin functions
def day_of_week_mgilson(day, month, year):
    """ See https://stackoverflow.com/a/14941764/50065"""
    c = calendar.weekday(year, month, day)
    return calendar.day_name[c]

def date_generator(day, month, year):
    """Convience function to return the next day"""
    d = datetime.date(year, month, day)
    while True:
        d += datetime.timedelta(days=1)
        yield d.day, d.month, d.year


if __name__ == '__main__':
    # checking all days from the beginning of the Gregorian
    # calender till 2300
    methods = {'user2080262': day_of_week_user2080262,
               'BioGeek': day_of_week_biogeek}
    for user, func in methods.items():
        checked = 0
        wrong = 0
        d = date_generator(14, 9, 1752)
        for day, month, year in d:
            checked += 1
            if year == 2300:
                break
            if func(day, month, year) != day_of_week_mgilson(day, month, year):
                wrong += 1
        print("The code by {0} gives a wrong answer ".format(user) + \ 
              "{0:.2f}% of the time.".format((float(wrong)/checked)*100))
于 2013-02-18T18:55:19.943 回答