在回答此代码高尔夫问题,我碰到一个问题,我的答案跑

我一直在测试这一点,我甚至无法获得这两个比较,在代码中,工作尽管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 W / O BOM,UNIX换行符。

这有什么错我的代码?

有帮助吗?

解决方案

您有:

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 == '-'),也将如此。您的代码将不会进入if的第二部分如果n[0]=='-'

如果您p n线路输出一个破折号,以确保它正是你所寻找的,不是一些字符的相同的字符看起来像的破折号。 Unicode有多种破折号,也许你有一个奇怪的Unicode连字符在你的代码或您的输入。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top