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()
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.
x.__mul__(y)
operator.mul(x, y)
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
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)
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)
Related
Edit: Sorry guys, I meant to use the power function, not squaring, i hope this clears it up
I'm a new to python, and I'm trying to create a function that lets the user input x and y and will give the output of the powers of those numbers in a loop, so create_list(2,8) returns the list [1,2,4,8,16,32,64,128,256].
I have this code so far, but I feel like it's way off as it only allows for 1 input, whereas I'm looking for 2
import math
a=int(input())
while a<=10000:
print (a)
a=a*2
An example output of this is if a=4, output:
4
8
16
32
64
128
256
512
1024
2048
4096
8192
The previous answers already explain how to solve your question, here I explain how to create a function. Notice that for simple operation like power, you don't need import math. With the following code you define a function create_list(x, y) that takes as input 2 numbers x and y and gives your output, regardless of how they are passed to the function:
def create_list(x, y):
my_list = []
for i in range(y+1):
my_list.append(x**i)
return my_list
After that, you can call the create_list function by giving the numbers programmatically (maybe they are the results of previous operations), but if you want to give them explicitly by keyboard, use this code:
x = int(input())
y = int(input())
my_list = create_list(x,y)
print(my_list)
First, use the input() function twice to let the user input two numbers.
Use the formula square = x * x (instead of x*2) to calculate the square.
Iterate over all numbers between a and b by using the range(a, b) function.
Collect all square numbers in a list and print the list afterwards.
a = int(input())
b = int(input())
squares = []
for i in range(a, b):
square = i * i
squares.append(square)
print(squares)
The more pythonic way in one line:
squares = [i*i for i in range (a,b)]
print(squares)
a=int(input())
b=int(input())
def create_list(a,b):
return [a**i for i in range(b+1)]
print(create_list(a,b))
output for create_list(2,8)
[1, 2, 4, 8, 16, 32, 64, 128, 256]
You can use python pow function
import math
def get_powers(power, length):
return [int(math.pow(power, x)) for x in range(1, length + 1)]
power_input = int(input('power:'))
length_input = int(input('length:'))
print(get_powers(power_input, length_input))
run
power:3
length:5
[3, 9, 27, 81, 243]
[ x * x for x in range (int(input("lower bound")), int(input("upper bound")))]
The above is a list comprehension. It takes every element in range and accesses it through the variable x. The expression on the left is what will actually end up in the list. For example, putting x + 1 would result in storing a value 1 greater than x being stored.
Inputs are evaluated from left to right so you can directly put them in as the parameters to the range function.
The evaluation order is:
Call 'lower bound' input
Convert to int
As above for right input
Evaluate range
Run list comprehension
I am trying to write code which gives you numbers which are less than given or entered number , and their GCD equal to 1 . I wrote this code but I don't know if works or why not . For example I chose number 6. array will be like [1,2,3,4,5]. And my point is to filter numbers that GCD equals to 1. So it will be [1,5]. And their amount is two.
a is input number and b is list numbers that are less than entered one and not equal to zero . And then print it .
a = int(input("enter number \n"))
b = list(range(1,a))
print (b)
Then I convert list to array
for i in range(1, len(b)):
b[i] = int(b[i])
and then this
r = a % b[i]
q = int ( a / b[i])
while(r!=0):
a = b[i]
b[i] = r
q = int ( a / b[i])
r = a - (b[i] * q)
print ( a , b[i], r )
break
I am beginner .
A few comments about your code:
You should always encapsulate code like this in a function; write a function find_coprimes which takes an argument n and returns the list you want;
In order to test the correctness of your function, write a reference function find_coprimes_ref which does the same thing, but uses library functions to make sure there is no error; this will teach you to look for relevant library functions, and you can compare the results of the two functions;
The initial loop for i in range(1, len(b)): b[i] = int(b[i]) is wrong for two reasons; 1) It has no effect, as b is already a list of integers. 2) Lists are 0-indexed, so a correct iterations on every element of b would be for i in range(0, len(b)): or simply for i in range(len(b)):;
Your code has two nested loops: a while-loop executing repeatedly inside a for-loop; whenever there are nested loops like this, you must make sure that variables are reinitialised the way you intend them to at the beginning of the outer loop; in your case, variable a is modified inside the while-loop, and as a result, its value is wrong at the beginning of the next iteration of the for-loop.
The break statement at the end of the while-loop makes no sense; in general, break statements only make sense if they are encapsulated in an if conditional, and they act as a substitute for the loop condition; but it's always possible to write loops without using break at all and I recommend you forget about break entirely.
After performing the gcd calculation using q and r, your code is missing something to tell it whether or not to keep b[i] or not in the final result;
For integer division in python, it is better to use // rather than int(... / ...).
Code
import math
def find_coprimes_ref(n):
return [x for x in range(1,n) if math.gcd(x,n) == 1]
def find_coprimes(n):
result = []
for x in range(1, n):
a = n
b = x
r = a % b
q = a // b
while (r > 1):
a = b
b = r
q = a // b
r = a - b * q
if (r == 1):
result.append(x)
return result
# TESTING
for n in range(1, 31):
coprimes_ref = find_coprimes_ref(n)
coprimes = find_coprimes(n)
if coprimes_ref != coprimes:
print(n, coprimes_ref, coprimes)
Note how my code never modifies n or x in the loop; instead, I make copies called a and b and modify the copies.
Encapsulating even further
Note how function find_coprimes_ref is so much easier to read than function find_coprimes? This is not just because we used library function math.gcd. It's because library function math.gcd is a cleanly-encapsulated function with a name that explains clearly what it does. Your code contains a while loop inside a for loop and it's a bit hard to keep track of every variable and everything that is going on and not lost track of our sub-objective and overall objective.
To make your function both easier to read, easier to code and easier to debug, You should encapsulate the gcd calculation inside a function called gcd:
def gcd(a, b):
r = a % b
q = a // b
while (r > 1):
a = b
b = r
q = a // b
r = a - b * q
return r
def find_coprimes(n):
result = []
for x in range(1, n):
if gcd(a, b) == 1:
result.append(x)
return result
# TESTING GCD
for b in range(1, 31):
for a in range(b, 31):
r1 = math.gcd(a, b)
r2 = gcd(a, b)
if r1 != r2:
print(a, b, r1, r2)
# TESTING FIND_COPRIMES
for n in range(1, 31):
coprimes_ref = find_coprimes_ref(n)
coprimes = find_coprimes(n)
if coprimes_ref != coprimes:
print(n, coprimes_ref, coprimes)
There are two reasons why the code is easier to debug now:
The logic for gcd and for find_coprimes is cleanly separated, which means you can reason about gcd clearly without any risk of messing up the list and the other variables used in find_coprimes;
You can test separately your function gcd and your function find_coprimes; and if something doesn't work correctly, you'll know more precisely where to look for the issue rather than just thinking "well, something is wrong somewhere in the code but I have no idea where".
There are a few errors in your code like, break inside while loop. I have refactored your code and also added inbuilt math.gcd function to compare results.
import math
def math_inbuilt_gcd(a, b):
gcd_one = []
for x in b:
if math.gcd(x, a) == 1:
gcd_one.append(x)
print("gcd_one_math_fun:", gcd_one)
def gcd_my_fun(a, b):
gcd_arr = []
for i in range(len(b)):
x, y = a, b[i] # taking x, y just to make things clear
r = x % y # remainder
q = int(x / y) # quotient
while(r != 0):
x = y
y = r
q = int(x/y)
r = x % y
if y == 1:
gcd_arr.append(b[i])
print("gcd_one_my_fun:", gcd_arr)
a = int(input("Enter number: "))
b = list(range(1, a))
print("b:", b)
math_inbuilt_gcd(a, b)
gcd_my_fun(a, b)
Output:
Enter number: 10
b: [1, 2, 3, 4, 5, 6, 7, 8, 9]
gcd_one_math_fun: [1, 3, 7, 9]
gcd_one_my_fun: [1, 3, 7, 9]
As a new python programmer, I'm working on a Leetcode question and don't know why my code does not work, so I really appreciate your advice:
Question:
Implement pow(x, n), which calculates x raised to the power n.
Example:
Input: 2.00000, 10
Output: 1024.00000
Here is my python code (I tried to use divide and conquer concept):
class Solution:
def myPow(self, x, n):
if n == 0:
return 0
if n == 1:
return x
return self.power(x,n)
def power(self,x,n):
if n == 1:
return x
self.power(x,n//2)
self.multiply(x,x)
return x
def multiply(self,x,y):
x = x*y
return x
test3=Solution()
test3.myPow(2,4)
But the results give 2 instead of 16. I expect the above code to work as follows:
power(2,4)->power(2,2)->power(2,1), which reaches the base case since n==1, and then we proceed with power(2,2),due to function multiply(x,x) or multiply(2,2) in this case, I expect x to become 4 (x = 2*2), and then we proceed with power(2,4), due to function multiply(x,x), x = 4*4 = 16
I don't know why I am wrong, could any expert give me some advice?
x^0 always equals 1, so your first "if" in myPow() is not accurate.
Also, your power() function always returns x, because the lines:
self.power(x,n//2)
self.multiply(x,x)
don't assign the value they return to anything.
class Solution:
def myPow(self, x, n):
if n == 0:
return 1
if n == 1:
return x
return self.power(x,n)
def power(self,x,n):
if n == 1:
return x
x = self.power(x,n//2)
return self.multiply(x,x)
def multiply(self,x,y):
x = x*y
return x
test3=Solution()
test3.myPow(2,4)
This code only fixes some minor problems in your code, but still you should consider cases when the power n is an odd number.
You aren't storing the return values from your self.power() and self.multiply() within power().
This is due to function scope. When you change x within multiply(), it is only changed within that function. You are correctly returning the changed value but you don't store it in the calling function.
Changing power() to the following works for your example (2^4).
def power(self,x,n):
if n == 1:
return x
x = self.power(x,n//2)
x = self.multiply(x,x)
return x
However, your algorithm is flawed as 2^3 returns 4 rather than 8.
First, I would note that x ^ 0 = 1, but your code states that it should equal zero within your first if statement within myPow. Second, your big problem is that you are not storing any of your intermediate results. Within the power function, you have:
def power(self,x,n):
if n == 1:
return x
self.power(x,n//2)
self.multiply(x,x)
return x
This function is taking in x and n, then computing subproblems using these variables, and then returning the original x. Therefore, in your example, calling test3.power(x, y) will always return the original x value. Instead, do the following.
def power(self,x,n):
if n == 1:
return x
# Account for when n is not even.
n1 = n // 2
n2 = n - n1
# Calculate powers.
x1 = self.power(x, n1)
x2 = self.power(x, n2)
# Combine divide-and-conquer answers and return.
x = self.multiply(x,x)
return x
Also notice that I changed the function to break the problem into powers of n1 and n2. This is because your function would not correctly handle something like power(2, 3). In this case, the original function would compute power(2, 3 // 2) = power(2, 1) which is not what you want. I hope this helps.
I am trying to create a function in Python. This function should be able to create a list of whole numbers less than or equal to the number provided. I've created an empty list, a variable called y and a while loop. In this while loop, as long as y <= x, the results of the subsequent equations are appended to the empty list, and y increments by 1. However, when I call this function, I get a list with only one element. How can I fix this?
def fff(x):
numbers = []
y = 2
while(y <= x):
x = x - (x - y)
numbers.append(x)
y += 1
return numbers
>>> fff(10)
[2]
That function already exists, more or less.
Python 2
def fff(x):
return range(1,x+1)
Python 3
def fff(x):
return list(range(1,x+1))
If you look at this line x = x - (x - y) and think of your inputs, you will see the problem. if x initially equals 10, then x - (x - y) equals 2, and y will equal 3, therefore breaking out of your loop.
If you are trying to mimic the range function then this is how you would do it:
def fff(x):
numbers = []
y = 1
while(y <= x):
numbers.append(y)
y += 1
return numbers
Everytime I try to solve some math problem such as finding a specific product of certain number of factors I do this in Python
for x in xrange(1,10):
for y in xrange(1,10):
for z in xrange(1,10):
product = x * y * z
if product == 36:
print "factors : {0},{1},{2}".format(x,y,z)
It is very straightforward and gets the job done fast in this example, but I was wondering if you guys know an easier or simpler way to write this. Any ideas on how to do this without using that many for iterations or repeating almost the same code over and over. These is obviously for 3 factors, but the more factors I add the longer and more repetitive the code keeps getting. Any ideas on how to simplify code for this simple type of problem?
thanks
Itertool's cartesian product simulates the effect of multiple nested for loops.
import itertools
for x, y, z in itertools.product(range(1,10), range(1,10), range(1,10)):
product = x * y * z
if product == 36:
print "factors : {0},{1},{2}".format(x,y,z)
Result:
factors : 1,4,9
factors : 1,6,6
factors : 1,9,4
(...etc)
If the range is always the same for each of x,y, and z, you can specify it just once:
for x, y, z in itertools.product(range(1,10), repeat=3):
If you're sick of typing a zillion asterisks for the product = line, you can use reduce to multiply together an arbitrary number of arguments:
for factors in itertools.product(range(1,3), repeat=10):
product = reduce(lambda x, y: x*y, factors)
Once your format string becomes unwieldy, you can depend on join to string together factors:
if product == 512:
#use `map` to turn the factors into strings, first
print "factors: " + ",".join(map(str, factors))
Avoid duplicates by having y start at x. Calculate z instead of running another loop.
for x in xrange(1,10):
for y in xrange(x,10):
z, r = divmod(36, x*y)
if r == 0:
print "factors : {0},{1},{2}".format(x,y,z)
For more factors, I would use a recursive function.