python - 在 Python 3.3 中解方程

标签 python python-3.x python-3.3

因此,要计算出自 10 月 15 日以来的任何日期是星期几,您可以使用一个简单的算术运算,我的问题是我已从文件中读取了日期(例如 2009-06-12)并且我将等式代入:

w = (d + [2.6 * m - 0.2] + Y + [Y / 4] + 5 * C + [C / 4] ) % 7

日期的格式为 yyyy-mm-dd,我的代码如下所示:

count = 5
f = open('/Users/student/Desktop/Harry.txt').readlines()[count]
Y = f[2:4]
C = f[:2]
m = f[5:7]
d = f[8:10]
w = (d + [2.6 * m - 0.2] + Y + [Y / 4] + 5 * C + [C / 4] ) % 7
if w == 0:
    print (f, "is a Sunday")
elif w == 1:
    print (f, "is a Monday")
elif w == 2:
    print (f, "is a Tuesday")
elif w == 3:
    print (f, "is a Wednesday")
elif w == 4:
    print (f, "is a Thursday")
elif w == 5:
    print (f, "is a Friday")
elif w == 6:
    print (f, "is a Saturday")

澄清一下:

w = day of the week counting from Sunday = 0 Monday = 1
d = the day of the month (for e.g. 28th 13th)
m = month number where March = 1 etc.
Y = last 2 digits of year
C = first 2 digits of year

但是我收到这个错误

Traceback (most recent call last):
  File "/Users/student/Documents/workspace/Tutorial Challenges/src/Day_Of_The_Week.py", line 7, in <module>
    w = (d + [2.6 * m - 0.2] + Y + [Y / 4] + 5 * C + [C / 4] ) % 7
TypeError: can't multiply sequence by non-int of type 'float'

非常感谢您的帮助。

最佳答案

YCmd 都是字符串。您想先将它们转换为整数:

Y = int(f[2:4])
C = int(f[:2])
...

不过,你确定这个方程有效吗?看起来它会产生很多非整数工作日。你可能抄错了。另外,方括号不是 Python 中的分组运算符;而是一个分组运算符。它们是列表构造语法。您需要将这些方括号替换为 w 表达式中的圆括号。 (或者这些括号应该是下限运算符吗?如果是这样,您需要来自 math 模块的 math.floor,或者只是 int 如果截断没问题。)

关于python - 在 Python 3.3 中解方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646931/

相关文章:

python-3.x - 使用python脚本下载YouTube视频

python - 移位运算符和二进制按位运算符适用于 bool 参数

python - 学习如何使用延迟库

python - Paypal API : Get balance of other users?

python - Python 是否有更简洁的方式来表达 "if x contains a|b|c|d..."?

python - 为什么 sorted() 和 reversed() 是内置函数而不是序列方法?

python - python 3.4 向后兼容 python 3.3 吗?

python - 将参数从函数传递到类方法

python - 如何使用 __init__.py 在 python 中导入包

python-3.x - 如何在python中从服务器接收文件?