Python 二进制数除以2和8
我需要检查一些二进制数是否可以被2或8整除,并告诉它们有多少。我现在知道,当最后一个数字为0时,二进制数可以被2整除,当最后3个数字为0时,二进制数可以被8整除,这就是我的工作方式Python 二进制数除以2和8,python,python-3.x,Python,Python 3.x,我需要检查一些二进制数是否可以被2或8整除,并告诉它们有多少。我现在知道,当最后一个数字为0时,二进制数可以被2整除,当最后3个数字为0时,二进制数可以被8整除,这就是我的工作方式 twos = 0 eights = 0 file = 'numbers.txt' with open(file) as fin: for line in fin: if line[-2:] == '0': twos += 1 elif line[-3:]
twos = 0
eights = 0
file = 'numbers.txt'
with open(file) as fin:
for line in fin:
if line[-2:] == '0':
twos += 1
elif line[-3:] == '000':
eights +=1
print(twos)
print(eights)
tbh我现在不知道为什么这不起作用,我打赌这是因为不同的数据类型,但我是python新手,无法确定错误在哪里
numbers.txt的示例
- 最后一个“数字”是
(或行[-1]
行[-1:][/code>),而不是
行[-2:][/code>(根据相同的逻辑,
行[-3:][/code>是最后3个“数字”,而不是最后2个)
- 您的代码根本不尝试处理换行符
- 由于
,您的算法将丢失可被2和8整除的数字elif
应成为:
line = line.strip()
if line[-1] == '0':
twos += 1
else:
continue # a micro optimization.
# If it does not end with '0', obviously it can't end with '000'
if line[-3:] == '000':
eights +=1
正如您所说,当最后一位数字为0时,二进制数字可被2整除,因此:
line = line.strip() // The strip() method returns a copy of the string with both leading and trailing characters removed
if line[-1] == '0':
twos += 1
文件='numbers.txt'
的内容是什么?您可能需要在for
循环中执行line=line.strip()
,因为它们可能是每行末尾的\n
。line.strip()
可能希望是line.rstrip()
。就我个人而言,我更喜欢完整的连环漫画,但为了以防万一,我想我会给OP留下评论。@Error syntacticalreforme OP获得通缉领先空间或换行的机会非常渺茫,但这一点值得注意。
line = line.strip() // The strip() method returns a copy of the string with both leading and trailing characters removed
if line[-1] == '0':
twos += 1