[英]Python code doesn't return expected results
我的代码遇到了问题:
def zeroOrOne(x):
i = 0
zc = 0
oc = 0
while i < len(x):
if x[i] == "1":
oc = oc + 1
elif x[i] == "0":
zc = zc + 1
i = i + 1
if zc > oc:
return True
elif oc > zc:
return False
elif oc == zc:
return False
f = open("D:\matura\Dane_PR2\liczby.txt", "r")
for x in f.readlines():
print(zeroOrOne(x))
f.close()
而打开的文件包含以下保存为字符串的数字:
11010100111
11110111111011101
1010100111010100
1101111111111111111111010100101010101001
1010110011001101010011110101010101010111
我的目标是计算这些行中的每个零和一个,然后决定是否有更多的 1 或零。 如果有更多零,我希望 function 返回TRUE不幸的是它不起作用。 它说所有行都等于FALSE ,这是不正确的,因为其中 3 行应该返回 True。
它说所有行都等于 FALSE,这是不正确的,因为其中 3 行应该返回 True。
你真的检查过吗? 在您提供的数据中,所有行的 1 多于 0。 您可以使用str.count
轻松确定这一点:
with open("test.txt", "r") as f:
for x in f:
print(x.count('0'), x.count('1'))
=>
4 7
3 14
8 8
11 29
17 23
除此之外,您的代码将受益于各种改进(除了您可以在上面的简短片段中看到的那些):
<=
和>=
是有效的运算符,您不需要分别检查<
和==
(也可以使用反向操作: not a >= b
是a < b
)def moreZeroes(s):
zeroes, ones = 0, 0
for c in s:
if c == '0':
zeroes += 1
if c == '1':
ones += 1
return zeroes > ones
或者使用标准工具的短版本,尽管遍历字符串两次,但由于完全在 C 中执行,这可能更快:
def moreZeroes(s):
return s.count('0') > s.count('1')
或者,仅在两个方面可能并不便宜,特别是如果您的输入不是巨大的:
def moreZeroes(s):
c = collections.Counter(s)
return c['0'] > c['1']
lines = """11010100111
11110111111011101
1010100111010100
1101111111111111111111010100101010101001
1010110011001101010011110101010101010111"""
for line_number, line in enumerate(lines.splitlines()):
ones = line.count('1')
zeros = line.count('0')
print('Line %d has %d zeros and %d ones, it should return %s' % (line_number, zeros, ones, str(True if zeros > ones else False)))
->
Line 0 has 4 zeros and 7 ones, it should return False
Line 1 has 3 zeros and 14 ones, it should return False
Line 2 has 8 zeros and 8 ones, it should return False
Line 3 has 11 zeros and 29 ones, it should return False
Line 4 has 17 zeros and 23 ones, it should return False
所以你的方法zeroOrOne()
将是L
def zeroOrOne(line):
ones = line.count('1')
zeros = line.count('0')
return True if zeros > ones else False
最短的解决方案,只是为了它:
with open("test.txt", "r") as f:
[print(l.count("0") > l.count("1")) for l in f]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.