2014-02-10 106 views
1

我的函数不能像预期的那样工作。当所有行[0]小于行[2]时,我总是得到'真'。我知道这是很琐碎,但它是一个练习,我已经采取了更好地了解文件和for循环中的比较运算符

def contains_greater_than(filename): 
    """ 
    (str) --> bool 
    The text file of which <filename> is the name contains multiple lines. 
    Each line consists of two integer numbers, separated by a space. 
    This returns True iff in at least one of those lines, the first number 
    is larger than the second one. 

    """ 
    lines = open(filename).readlines() 
    for line in lines: 
     if line[0] > line[2]: 
      return True 
    return False 

我的数据:

3 6 
3 7 
3 8 
2 9 
3 20 
+0

你的代码读取'返回True如果任何线路,线[0]>行[2]'。这是真的,因为'3> 2'。只读取第一个和第三个字符,意思是'3 20''读取'line [0] = 3 line [2] = 2' – njzk2

回答

4

已经在我的超认为以前的答案被彻底接受教育,可能我提供的这个简单得多的解决方案仍然短路如预期

for line in lines: 
    x, y = line.split() 
    if int(x) > int(y): return True 
return False 
+0

发电机很不错,但它们不会帮助比较字符串作为数字;-)并且此外,OP特别*希望*短路(请参阅文档字符串)。 –

+0

当这些数字是一位数字时! OP想知道为什么它总是返回True,短路一旦为True就是原因 – mhlester

+1

*这将返回True iff至少在其中一行中,第一个数字大于第二个* - 这应该是要求,因为我明白。 –

1
line[0] = "3" , line[1] = " " 

的所有情况在您的数据( '3' < ''= FALSE)

你需要做的

split_line = line.split() 

然后

numbers = [int(x) for x in split_line] 

然后看着numbers[0]numbers[1]

0

“3 20”是一个字符串,只是做map(int,LINE.split())之前。 但你如何比较2个数字和2个数字?

1

1)你比较,你需要转换为整数

2)您只抢到第一和第三个字符串(这样,你就不会得到0 20)

相反使用

first, second = line.split() 
if first < second: 
1

这是一个全猪功能重写。希望这是有启发性的;-)

import functools 

def line_iter(fname): 
    with open(fname) as inf: 
     for line in inf: 
      line = line.strip() 
      if line: 
       yield line 

def any_line(fn, fname): 
    return any(fn(line) for line in line_iter(fname)) 

def is_greater_than(line): 
    a,b = [int(i) for i in line] 
    return a > b 

contains_greater_than = functools.partial(any_line, is_greater_than) 
+1

虽然这在技术上是正确的,但我不确定它是否真的有助于SO – njzk2

+0

如果他抛出链接到['str.split()']文档的链接(http://docs.python.org/2/ library/stdtypes.html#str.split),['any()'](http://docs.python.org/2/library/functions.html#any)内建函数和[generator表达式](http:/ /docs.python.org/2/reference/expressions.html#generator-expressions)它可能。 –

0

主要问题是你比较线的字符,而不是每个人的两个数字的值。这可避免第一分割行成空格分隔单词,然后通过将int()函数每一个转动的那些进用于比较的整数值:

def contains_greater_than(filename): 
    with open(filename) as inf: 
     for line in inf: 
      a, b = map(int, line.split()) 
      if a > b: 
       return True 
     return False 

print(contains_greater_than('comparison_data.txt')) 

这些都可以非常简洁地完成使用Python中内置any()功能与一对夫妇的generator expressions

def contains_greater_than(filename): 
    with open(filename) as inf: 
     return any(a > b for a, b in (map(int, line.split()) for line in inf))