2009-05-30 55 views
0

在回答this code golf question时,我在答案中遇到了一个问题。不可重复的字符串比较,强制elsif失败

我一直在测试这个,我甚至无法让这两个比较在代码中工作,尽管IRB具有正确的行为。我真的这里需要一些帮助。

下面是代码,下面将会解释这个问题。

def solve_expression(expr) 
    chars = expr.split '' # characters of the expression 
    parts = [] # resulting parts 
    s,n = '','' # current characters 

    while(n = chars.shift) 
    if (s + n).match(/^(-?)[.\d]+$/) || (!chars[0].nil? && chars[0] != ' ' && n == '-') # only concatenate when it is part of a valid number 
     s += n 
    elsif (chars[0] == '(' && n[0] == '-') || n == '(' # begin a sub-expression 
     p n # to see what it breaks on, (or - 
     negate = n[0] == '-' 
     open = 1 
     subExpr = '' 
     while(n = chars.shift) 
     open += 1 if n == '(' 
     open -= 1 if n == ')' 
     # if the number of open parenthesis equals 0, we've run to the end of the 
     # expression. Make a new expression with the new string, and add it to the 
     # stack. 
     subExpr += n unless n == ')' && open == 0 
     break if open == 0 
     end 
     parts.push(negate ? -solve_expression(subExpr) : solve_expression(subExpr)) 
     s = '' 
    elsif n.match(/[+\-\/*]/) 
     parts.push(n) and s = '' 
    else 
     parts.push(s) if !s.empty? 
     s = '' 
    end 
    end 
    parts.push(s) unless s.empty? # expression exits 1 character too soon. 

    # now for some solutions! 
    i = 1 
    a = parts[0].to_f # left-most value is will become the result 
    while i < parts.count 
    b,c = parts[i..i+1] 
    c = c.to_f 
    case b 
     when '+': a = a + c 
     when '-': a = a - c 
     when '*': a = a * c 
     when '/': a = a/c 
    end 
    i += 2 
    end 
    a 
end 

问题发生在negate的赋值中。

当表达式之前的字符是短划线时,我需要否定,但条件不起作用。 n == '-'n[0] == '-',引用的形式都没有关系,每次发送FALSE。然而,我一直在使用这个确切的比较,并且n == '('每次都能正确工作!

这是怎么回事?为什么n == '-'不工作,当n == '('呢?这是用UTF-8编码,不带BOM,UNIX linebreaks。

我的代码有什么问题?

回答

3

您有:

if (s + n).match(/^(-?)[.\d]+$/) || (!chars[0].nil? && chars[0] != ' ' && n == '-') 
     s += n 
elsif (chars[0] == '(' && n[0] == '-') || n == '(' 

由于n始终是一个字符的字符串,如果(chars[0] == '(' && n[0] == '-'))是真实的,那么以前的状态,(!chars[0].nil? && chars[0] != ' ' && n == '-'),也将是如此。如果n[0]=='-'您的代码将永远不会输入if的第二部分。

如果您的p n行输出短划线,请确保它与您正在查找的字符完全相同,而不是看起来像短划线的某些字符。 Unicode有许多破折号,也许你的代码或输入中有一个奇怪的unicode破折号字符。

+0

非常感谢你,我没有想到前面的声明已经引起了我的代码。谢谢你的新鲜眼睛。 – 2009-05-30 15:10:12