работа с отрицательными числами в Python - PullRequest
11 голосов
/ 16 марта 2010

Я учусь на занятиях по программированию. Лаборатория управляется ТА, и сегодня в лаборатории он дал нам очень простую небольшую программу для сборки. Это был один, где это будет умножаться на сложение. Во всяком случае, он заставил нас использовать абсолют, чтобы не ломать прогу с негативами. Я быстро взбил его, а потом 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

Я хочу сделать это без абсолютов, но каждый раз, когда я ввожу отрицательные числа, я получаю большой толстый мурашек. Я знаю, что есть какой-то простой способ сделать это, но я просто не могу его найти.

Ответы [ 7 ]

5 голосов
/ 16 марта 2010

Возможно, вы бы достигли этого с эффектом

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
4 голосов
/ 16 марта 2010

Слишком сложно? Твоя ТА ... ну, эта фраза, вероятно, сделает меня баном. В любом случае, проверьте, является ли numb отрицательным. Если это так, умножьте numa на -1 и сделайте numb = abs(numb). Затем выполните цикл.

3 голосов
/ 16 марта 2010

Функция abs () в условии while необходима, так как она контролирует количество итераций (как бы вы определили отрицательное число итераций?). Вы можете исправить это, инвертировав знак результата, если numb отрицательно.

Так что это модифицированная версия вашего кода. Обратите внимание, что я заменил цикл 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
1 голос
/ 16 марта 2010

Попробуйте это на своем TA:

# 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
0 голосов
/ 10 ноября 2014
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 ()  
0 голосов
/ 17 марта 2010

Спасибо всем, вы все помогли мне многому научиться. Это то, что я придумал, используя некоторые ваши предложения

#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

Спасибо всем за помощь.

0 голосов
/ 16 марта 2010

Как насчет чего-то подобного? (Не использует abs () и многовариантность)
Примечания:

  • функция abs () используется только для оптимизации. Этот фрагмент можно удалить или перекодировать.
  • логика менее эффективна, так как мы тестируем знак 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
...