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

The Error is: "ParseError: bad input on line 17" The purpose of this program is to give the day of the week for any date. As you can see it is not happy with how I have given the purpose of the function for my benefit. I really feel like I am missing something here.

Here is the Improved and Working Version (Thanks for the help!)

# 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

私はBioGeekに同意します

スクリプトは実行されますが、コードにはまだ 1 つずれているエラーがあります。生年月日 (1978 年 5 月 19 日) を入力すると、木曜日に返されますが、金曜日に生まれます。

あなたの作業バージョンは、いくつかのオンライン計算機と比較して 1 日ずれているようです。例えば

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

しかし、他の電卓では と表示されTuesdayます。

于 2013-02-18T19:40:08.767 に答える
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)

スクリプトは実行されますが、コードにはまだ 1 つずれているエラーがあります。生年月日 (1978 年 5 月 19 日) を入力すると、木曜日に返されますが、金曜日に生まれます。

于 2013-02-18T17:25:29.413 に答える
1

monthcode 関数の本文では、「monthin」ではなく「m」を使用する必要があります。

于 2013-02-18T17:22:58.697 に答える
0

他の回答で述べたように、生年月日を入力すると、間違った回答が返されました。

具体的には、2013年の日付を試してみると、コードは正しい答えを返しますが、それより前または将来の日付にコードを使用しようとすると、81.76%の確率で間違った答えが返されます。とりわけ、うるう年は考慮されておらず、21世紀以外の日付も補正されていません。

どこが間違っているのかを突き止めようとして、どのアルゴリズムを使用しているかを知る必要がありました。リストをグーゲル化すると、このページ(pdf)にたどり着きました。このページには、非常に詳細な説明がありますが、現在アルゴリズムにあるいくつかの追加の手順もあります[6, 2, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]

これがそのアルゴリズムの私の実装です。グレゴリオ暦の開始から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 に答える
0

その行を削除して、手動で再入力してみましたか? 特に Mac ユーザーが目に見えない Unicode 文字 (私の記憶が正しければ、alt + スペース) を入力するのをよく見てきました。これが問題の原因である可能性があります。

于 2013-02-18T17:21:32.787 に答える