working with negative numbers in python
I am a student in a concepts of programm开发者_Go百科ing class. The lab is run by a TA and today in lab he gave us a real simple little program to build. It was one where it would multiply by addition. Anyway, he had us use absolute to avoid breaking the prog with negatives. I whipped it up real quick and then argued with him for 10 minutes that it was bad math. It was, 4 * -5 does not equal 20, it equals -20. He said that he really dosen't care about that and that it would be too hard to make the prog handle the negatives anyway. So my question is how do I go about this.
here is the prog I turned in:
#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
I want to do it without absolutes, but every time I input negative numbers I get a big fat goosegg. I know there is some simple way to do it, I just can't find it.
Perhaps you would accomplish this with something to the effect of
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
or maybe
a * b
Too hard? Your TA is... well, the phrase would probably get me banned. Anyways, check to see if numb
is negative. If it is then multiply numa
by -1
and do numb = abs(numb)
. Then do the loop.
The abs() in the while condition is needed, since, well, it controls the number of iterations (how would you define a negative number of iterations?). You can correct it by inverting the sign of the result if numb
is negative.
So this is the modified version of your code. Note I replaced the while loop with a cleaner for loop.
#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
Try this on your 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
output:
3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129
How about something like that? (Uses no abs() nor mulitiplication)
Notes:
- the abs() function is only used for the optimization trick. This snippet can either be removed or recoded.
- the logic is less efficient since we're testing the sign of a and b with each iteration (price to pay to avoid both abs() and multiplication operator)
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
Thanks everyone, you all helped me learn a lot. This is what I came up with using some of your suggestions
#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
Thanks for all the help everyone.
Try doing this:
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")
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 ()
精彩评论