【问题标题】:working with negative numbers in python在 python 中处理负数
【发布时间】:2011-01-27 22:47:45
【问题描述】:

我是编程概念课程的学生。该实验室由一名 TA 管理,今天在实验室他给了我们一个非常简单的小程序来构建。这是一个可以通过加法相乘的方法。无论如何,他让我们使用 absolute 来避免用底片破坏前卫。我很快就把它搅了起来,然后和他争论了 10 分钟,说这是一个糟糕的数学。原来,4 * -5 不等于 20,它等于 -20。他说他真的不在乎这个,无论如何让前卫处理负面因素太难了。所以我的问题是我该怎么做。

这是我上交的编:

#get user input of numbers as variables

numa, numb = input("please give 2 numbers to multiply seperated with a comma:")

#standing variables
total = 0
count = 0

#output the total
while (count< abs(numb)):
    total = total + numa
    count = count + 1

#testing statements
if (numa, numb <= 0):
    print abs(total)
else:
    print total

我想在没有绝对值的情况下做到这一点,但每次我输入负数时,我都会得到一个大胖子。我知道有一些简单的方法可以做到这一点,我就是找不到。

【问题讨论】:

  • 总是更喜欢 raw_input 而不是 input,这不应该出现在语言中(并且在 Python 3 中被删除。)
  • 为了混淆,Python 3 中的 input 与 Python 2 中的 raw_input 相同,而 IIRC,Python 3 没有 raw_input。 @_@
  • 没错,raw_input 在 Python 3 中被重命名为 input

标签: python negative-number


【解决方案1】:

也许你会用一些类似的东西来完成这个

text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
a = int(split_text[0])
b = int(split_text[1])
# The last three lines could be written: a, b = map(int, text.split(','))
# but you may find the code I used a bit easier to understand for now.

if b > 0:
    num_times = b
else:
    num_times = -b

total = 0
# While loops with counters basically should not be used, so I replaced the loop 
# with a for loop. Using a while loop at all is rare.
for i in xrange(num_times):
    total += a 
    # We do this a times, giving us total == a * abs(b)

if b < 0:
    # If b is negative, adjust the total to reflect this.
    total = -total

print total

或许

a * b

【讨论】:

  • RTQ:加法乘法
【解决方案2】:

太难了?你的助教是……嗯,这句话可能会让我被禁止。无论如何,检查numb 是否为负数。如果是,则将numa 乘以-1 并执行numb = abs(numb)。然后循环。

【讨论】:

  • 嗯,整个项目都是关于乘法的;他应该通过递归实现乘以-1吗?也许递归和堆栈对 TA 来说太难了 :-)
  • @John:不。只需从 0 中减去它。
【解决方案3】:

while 条件中的 abs() 是必需的,因为它控制迭代次数(如何定义负迭代次数?)。如果numb 为负数,您可以通过反转结果的符号来纠正它。

所以这是您的代码的修改版本。注意我用更干净的 for 循环替换了 while 循环。

#get user input of numbers as variables
numa, numb = input("please give 2 numbers to multiply seperated with a comma:")

#standing variables
total = 0

#output the total
for count in range(abs(numb)):
    total += numa

if numb < 0:
    total = -total

print total

【讨论】:

    【解决方案4】:

    在你的助教身上试试这个:

    # Simulate multiplying two N-bit two's-complement numbers
    # into a 2N-bit accumulator
    # Use shift-add so that it's O(base_2_log(N)) not O(N)
    
    for numa, numb in ((3, 5), (-3, 5), (3, -5), (-3, -5), (-127, -127)):
        print numa, numb,
        accum = 0
        negate = False
        if numa < 0:
            negate = True
            numa = -numa
        while numa:
            if numa & 1:
                accum += numb
            numa >>= 1
            numb <<= 1
        if negate:
            accum = -accum
        print accum
    

    输出:

    3 5 15
    -3 5 -15
    3 -5 -15
    -3 -5 15
    -127 -127 16129
    

    【讨论】:

    • 从技术上讲,符号反转(accum = -accum 等)以及移位操作(numb &lt;&lt;= 1)是乘法,但 +1 仍然是一个好主意,以及可能适合的概念了解 OP 在课堂上已经或即将涵盖的典型内容。
    • @mjv:这叫做否定,而不是符号反转......如果被模拟的盒子没有 NEG 指令,则通过从零减法来完成。使用您的推理,abs() 洒在其他一些答案上也是乘法!如果移位是乘法,那么加法也是如此,例如numa += numa !!!移位是一种非常原始的硬件操作,用于乘法的实现。
    • 你是对的,在所有方面。事实上,一旦你看到 CPU 的水平,这个练习就变得很尴尬了。很高兴我们可以帮助 OP,我讨厌教练似乎不鼓励学生加倍努力......
    【解决方案5】:

    这样的事情怎么样? (不使用 abs() 或乘法)
    备注:

    • abs() 函数仅用于优化技巧。此 sn-p 可以删除或重新编码。
    • 逻辑效率较低,因为我们在每次迭代时都测试 a 和 b 的符号(避免使用 abs() 和乘法运算符的代价)

    def multiply_by_addition(a, b):
    """ School exercise: multiplies integers a and b, by successive additions.
    """
       if abs(a) > abs(b):
          a, b = b, a     # optimize by reducing number of iterations
       total = 0
       while a != 0:
          if a > 0:
             a -= 1
             total += b
          else:
             a += 1
             total -= b
       return total
    
    multiply_by_addition(2,3)
    6
    multiply_by_addition(4,3)
    12
    multiply_by_addition(-4,3)
    -12
    multiply_by_addition(4,-3)
    -12
    multiply_by_addition(-4,-3)
    12
    

    【讨论】:

    • 您应该将while 循环放在if 语句中,因为if 语句每次都计算相同的值。或者在 while 循环之前将变量da 设置为1-1,并将dt 设置为total-total
    • Python 中的函数应该以小写字母开头。如果有人看到FooBar(在具有这种命名约定的外部库之外),他们会认为它是一个类。
    • @Mike,是的!你是对的,这通常是可取的。在这个人为的作业的上下文中,我选择了单一的while方法,因为它反映了原始算法并使数学更加独立。尽管事先进行所有“符号测试”并使用 2 个(或 3 或 4 个)while 循环将是等效的,但单个 while 读起来更像是单个算法(毫无疑问是心理学)。
    • @Mike,感谢您指出这一点。实际上,PEP8 需要一个类似 mul_by_add() 的名称,或者更好的是 multiply_by_addition()。我的错,我一直在切换语言,而且工作中严格而愚蠢的命名约定也无济于事:-(
    【解决方案6】:

    谢谢大家,你们让我学到了很多东西。这是我根据您的一些建议得出的结论

    #this is apparently a better way of getting multiple inputs at the same time than the 
    #way I was doing it
    text = raw_input("please give 2 numbers to multiply separated with a comma:")
    split_text = text.split(',')
    numa = int(split_text[0])
    numb = int(split_text[1])
    
    #standing variables
    total = 0
    
    if numb > 0:
        repeat = numb
    else:
        repeat = -numb
    
    #for loops work better than while loops and are cheaper
    #output the total
    for count in range(repeat):
        total += numa
    
    
    #check to make sure the output is accurate
    if numb < 0:
        total = -total
    
    
    print total
    

    感谢大家的帮助。

    【讨论】:

    • 如果只是一个简单的repeat = abs(numb),那么整个 if-else 子句的意义何在?
    • 另外,如果您的问题得到解决,请接受其中一个答案(甚至是您自己的)。
    • 没有 if else 子句,数字仍然返回绝对值,而不是真实值,所以没有它 prog 仍然返回 4*-5 作为 20 而不是 -20
    • 实际上,如果没有 if-else 子句,4*-5 将返回 0,因为带有负参数的 range() 返回一个空列表。我不是在说这种逻辑是不需要的。我在谈论它重新发明轮子,因为这整 4 行可以替换为读取 repeat = abs(numb) 的单行。这不仅更短,而且更清晰。
    • 哦,我现在明白你在说什么了。好的,对不起,我只是在学习。你是对的,它确实工作得更好,而且更干净、更清晰。
    【解决方案7】:

    尝试这样做:

    num1 = int(input("Enter your first number: "))
    num2 = int(input("Enter your second number: "))
    ans = num1*num2
    
    
    if num1 > 0 or num2 > 0:
        print(ans)
    
    elif num1 > 0 and num2 < 0 or num1 < 0 and num1 > 0:
        print("-"+ans)
    
    elif num1 < 0 and num2 < 0:
        print("Your product is "+ans)
    else:
        print("Invalid entry")
    

    【讨论】:

      【解决方案8】:
      import time
      
      print ('Two Digit Multiplication Calculator')
      print ('===================================')
      print ()
      print ('Give me two numbers.')
      
      x = int ( input (':'))
      
      y = int ( input (':'))
      
      z = 0
      
      print ()
      
      
      while x > 0:
          print (':',z)
          x = x - 1
          z = y + z
          time.sleep (.2)
          if x == 0:
              print ('Final answer: ',z)
      
      while x < 0:
          print (':',-(z))
          x = x + 1
          z = y + z
          time.sleep (.2)
          if x == 0:
              print ('Final answer: ',-(z))
      
      print ()  
      

      【讨论】:

      • 只有代码的答案通常不好,你能解释一下吗?
      猜你喜欢
      • 1970-01-01
      • 2020-08-09
      • 2012-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多