不知道这里出了什么问题。我确信这是正确的语法,我已检查过拼写错误

时间:2013-02-18 17:15:14

标签: python

# 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:第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])

6 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

你应该在月份代码功能的主体中使用“m”而不是“monthin”

答案 2 :(得分:1)

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

可能是使用变量dayayin而不是dayin

的拼写错误
dayayin = int(input("What Day in the Month?"))
...
dayout = daycode(dayin)

在函数monthcode中,mothin来自何处?

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

修改 修复这些后,并使result为整数

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

脚本运行,但代码中仍有一些错误。当我输入我的出生日期(1978年5月19日)时,它将在周四返回,但我出生在星期五。

答案 3 :(得分:1)

我同意BioGeek

  

脚本运行,但你的内容仍有一些错误   码。当我输入我的出生日期(1978年5月19日)时,它将在周四返回,   但我出生在星期五。

与多个在线计算器相比,您的工作版似乎有一天休息。 e.g。

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

但其他计算器将其显示为Tuesday

答案 4 :(得分:0)

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

答案 5 :(得分:0)

正如我在其他答案中所说,当我进入出生日期时,它给出了错误的答案。

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

试图找出出错的地方我需要知道你使用的是哪种算法。列表[6, 2, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]的Googeling让我找到了this page(pdf),其中有一个非常详细的描述,但是您的算法中还有一些额外的步骤。

所以这是我对该算法的实现。我根据mgilson提供的calendar解决方案检查了自公历开始至2300年的每个日期。

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))