gpt4 book ai didi

python - 使用 numpy 计算给定 dd/mm 的星期几(给定 1 月 1 日)

转载 作者:行者123 更新时间:2023-11-30 22:03:08 25 4
gpt4 key购买 nike

我正在做一篇过去的考试复习论文,并陷入了这个问题:

编写一个 python 脚本,从用户那里接受特定年份中 1 月 1 日是星期几,然后打印用户指定的任何其他月份的星期几和该月中的某一天。您可以假设该年份不是闰年,用户将输入键入为任何单词的前三个字母,并且之前已定义以下代码:

import numpy as np
months = np.array(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'])
ndays = np.array([31,28,31,30,31,30,31,31,30,31,30,31])
days=np.array(['Mon','Tue','Wed','Thu','Fri','Sat','Sun'])

所以我知道如何使用输入命令来获取用户的输入,这样我就可以创建 3 个变量:

user_Jan_1_day = input('Input the day of the week for Jan 1st: ')
user_month = input('Input the month: ')
user_day = input('Input the day of the month required: ')

假设用户说 1 月 1 日是“星期六”,他们想要“Mar”是一周中的某一天,即“1”,即 3 月 1 日。

我知道我需要取 31 + 28 + 1。求和 = 60。取模数:60%7 = 4,然后在“周六”上添加四个工作日,得到“周三”作为我的答案,但我如何在 Python 中做到这一点?

我认为我可以通过使用数组的索引来做到这一点,所以我使用了

a=np.where(months==user_month)
no_of_days = 0
for i in range (a):
no_of_days =+ ndays[i]

但我收到错误:“‘tuple’对象无法解释为整数”

有人可以告诉我该怎么做吗?

谢谢!

最佳答案

按照您的确切逻辑,您可以这样做,无需迭代(确保获得int(input(...)) for user_day 而不是默认的字符串输入):

user_Jan_1_day = input('Input the day of the week for Jan 1st: ')
user_month = input('Input the month: ')
user_day = int(input('Input the day of the month required: '))

m = np.where(months == user_month)[0][0]
d = np.where(days == user_Jan_1_day)[0][0]
# or, maybe more straightforward, since there is only one correct value:
# m = list(months).index(user_month)
# d = list(days).index(user_Jan_1_day)

result = days[(np.sum(ndays[:m]) + user_day + d) % 7]

例如:

>>> user_Jan_1_day = input('Input the day of the week for Jan 1st: ')
Input the day of the week for Jan 1st: Sat
>>> user_month = input('Input the month: ')
Input the month: Mar
>>> user_day = int(input('Input the day of the month required: '))
Input the day of the month required: 1

>>> m = np.where(months == user_month)[0][0]
>>> d = np.where(days == user_Jan_1_day)[0][0]
>>> result = days[(np.sum(ndays[:m]) + user_day + d) % 7]

>>> result
'Wed'

关于python - 使用 numpy 计算给定 dd/mm 的星期几(给定 1 月 1 日),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53623522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com