Multiplying without the multiplication operator in python

Question:

How do I write a python script that multiplies x * y without using the multiplication operator? I know that basically you should have:

def multi():
    x = raw_input('x is: ')
    y = raw_input('y is: ')
    z = #(x + x) y times
    return z

multi()
Asked By: Sydney

||

Answers:

With sum and range or xrange:

z = sum(x for _ in xrange(y))

It can of course work the other way around, and effectively does x+x y times as you requested.

This works essentialy the same as doing:

z = 0
for _ in range(y):
    z += x
Answered By: Korem
x.__mul__(y)
operator.mul(x, y)

You can use reduce which does x*y in the way you describe:

x = raw_input('x is: ')
y = raw_input('y is: ')
reduce(lambda a, b: a+b, [x]*y)

This will calculate ((x+x)+x)… y times.

EDIT to explain what reduce does:

The 1st argument is a function taking exactly 2 arguments, describing what to do at each iteration.

lambda x,y: x+y is just a function taking 2 arguments and adding them together. As if you wrote:

def my_operation(x, y):
    return x + y

The 2nd argument is the input data, for example [1, 4, 2, 8, 9].

reduce will iterate over your input data, starting with 1 and 4. This is passed to your function which will return 5. Then 5 and 2 are passed to your function,…
So the calculation will be ((((1+4)+2)+8)+9)

So if your input list is [x, x, x…, x] of length y (i.e. [x]*y), you will get the result you want, calculated in the way you described.

Answered By: nicolas

For Python 3.x you can use this code to solve the same problem.
Knowing that 5*5 is == 5+5+5+5+5….with that idea in mind…

a = int(input("Intro a number: "))
b = int(input("Intro a second number: "))
for i in range(1,a):
    b = b+a
print(b)
Answered By: DoctorChocolate

How do I write a python script that multiplies x * y without using the multiplication operator? you can use this code to solve the same problem

a = int(input("Intro a number: "))
b = int(input("Intro a second number: "))
c=b
for i in range(1,a):
    b = b+c
    print(b)
Answered By: Gajanan Mirkhale
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.