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
Related
I'm trying to understand this example:
solve([y == x + 1, ForAll([y], Implies(y <= 0, x < y))])
but after reading the explanation I still don't understand it.
How do you read this?
what is the meaning of []?
My wrong interpretation of this is.
"Given the theorem y == x + 1. Does it hold for all y such that Implies(y <= 0, x < y)?"
With this interpretation if I use y = 0 and x = -1 every constraint (Implies(y <= 0, x < y) is true since y <= 0 and x < y) is respected, but If I run this I find out that it's not solvable.
Do you have any hits to how to understand this topic?
Looks like there're a couple of confusions here. Let's first sort out binding: In a quantifier context, the variable is independent, i.e., it can be renamed with no change to the semantics. So, your original:
from z3 import *
x, y = Ints('x y')
solve([y == x + 1, ForAll([y], Implies(y <= 0, x < y))])
is exactly equivalent to:
from z3 import *
x, y, z = Ints('x y z')
solve([y == x + 1, ForAll([z], Implies(z <= 0, x < z))])
Note that we replaced the y in the "scope" of ForAll to z, but left the one in the first conjunct untouched. You can only rename within the scope of ForAll (or Exist), not outside of it.
And both of these equivalent expressions are unsatisfiable. Why? The first conjunct is easy to satisfy; just pick an arbitrary x, and set y to be x+1 and you're done. It's the second conjunct that's unsatisfiable. Because, no matter which x you choose to satisfy the first, you can always find a z that's less than that x (just pick min(0, x-1)), and the quantified formula becomes False for that assignment. And hence there are no solutions.
Now, let's consider the variant you had in your comments, with x > z:
from z3 import *
x, y, z = Ints('x y z')
solve([y == x + 1, ForAll([z], Implies(z <= 0, x > z))])
Again, the first conjunct is easy to satisfy. And this time, so is the second, because you can pick a positive x, and that will be greater than all z's so long as z <= 0, and thus the implication is always true. And that's exactly what z3 is telling you, when it gives you the satisfying assignment:
[x = 2, y = 3]
Note that there's nothing in this assignment regarding the variable z. You cannot really give a model for a universally quantified formula; by definition it is true for all values of z.
Hope this clears things up.
[] is a Python list; the outer one is a list of constraints (representing a conjunction) and the one in the ForAll is a list of constants to bind.
Note that the same constant name can be re-used. In this case, y in y == x + 1 is a global existential and the y in the ForAll is a universally bound variable which also has the name y.
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 a beginner at Python and I'm trying to use a while loop to sum up all of the squared n values in a given n value range.
Code:
def problem2(n):
x = 0
y = 0
while x < n:
y = (n**2)+y
x+=1
return y
For some reason, this equation returns the input number cubed.
Can someone explain why this happens and how to fix it?
You need to perform the ** on x, the value that is being incremented:
def problem2(n):
x = 0
count = 0
while x < n:
count += pow(x, 2)
x += 1
return count
You keep squaring the same number n, instead of the one being incremented x.
def sum_of_squares(n):
sum = 0
for x in range(0, n):
sum += x*x
return sum
You also don't really need the while loop, avoiding having to manually keep track of which variable is the counting variable and which one is the result variable (which is what you are confusing, as explained e.g. by #Ajax1234 in their answer).
It is a lot more Pythonic to use the built-in function sum, a generator expression and range:
def problem2(n):
return sum(x**2 for x in range(n))
This would be a lot more readable and better (unless of course you are being forced to use while).
Looks good. You're almost there.
It makes it the cube root because you add y to (n**2) everytime. Because you code runs until x !< n it runs n times. That means that you add n**2 to n**2*n.
That means that it gives 1(n**2)*(n-1)(n**2) which equals n(n**2) = n**3
Hope this was clear enough.
f(x) represents the function of a triangular waveform. In which you input the value x and it returns you the associated y value. However my function returns x every time instead of y. For example f(1) should give 2/pi instead of 1.
def f(x):
y=x
if x in arange(-math.pi,-math.pi/2):
y=(-2/math.pi)*x-2
elif x in arange(-math.pi/2,math.pi/2):
y=(2/math.pi)*x
elif x in arange(math.pi/2,math.pi):
y=(-2/math.pi)*x+2
return y
numpy.arange returns an array of non-consecutive numbers. in operation against it will return True only if the left-hand operand belong to those numbers.
You'd better to use <= / < pair to avoid such problem. In addition to be correct, it also save cost of creating arrays.
def f(x):
y = x
if -math.pi <= x < -math.pi/2:
y = (-2/math.pi)*x-2
elif -math.pi/2 <= x < math.pi/2:
y = (2/math.pi)*x
elif math.pi/2 <= x < math.pi:
y = (-2/math.pi)*x+2
return y
The 'in' keyword only checks if the searched element lies in the list. Here, your list contains only values in the step of 1. Perhaps the value of x is not an integral step. Hence, the corrected function would be:
def f(x):
y=x
if x>-math.pi and x<-math.pi/2:
y=(-2/math.pi)*x-2
elif x>-math.pi/2 and x<math.pi/2:
y=(2/math.pi)*x
elif x>math.pi/2 and x<math.pi:
y=(-2/math.pi)*x+2
return y
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)