working with negative numbers in python


working with negative numbers in python



I am a student in a concepts of programming 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.




Python: Inheritance of a class attribute (list)

1:



How to increment variable names/Is this a bad idea
Perhaps you would accomplish this with something to the effect of.
pyopengl: Could it replace c++?
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. 


Read more numbers in a line in Python
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.


How to format contour lines from Matplotlib
Using a while loop at all is rare.


Where can I find a high quality music library for python that plays OGG, ACC and/or MP3 which isn't pygame?
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.


python, wrapping class returning the average of the wrapped members
total = -total print total
or maybe.
My method is being recognized within my own program. Newbie mistake probably
a * b 


2:


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..


3:


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 


4:


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 


5:


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


6:


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..


7:


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 ()   



72 out of 100 based on 72 user ratings 222 reviews

@