Include upper bound in range() - python

How can I include the upper bound in range() function? I can't add by 1 because my for-loop looks like:
for x in range(1,math.floor(math.sqrt(x))):
y = math.sqrt(n - x * x)
But as I understand it will actually be 1 < x < M where I need 1 < x <= M Adding 1 will completely change the result.
I am trying to rewrite my old program from C# to Python. That's how it looked in C#:
for (int x = 1; x <= Math.Floor(Math.Sqrt(n)); x++)
double y = Math.Sqrt(n - x * x);

Just add one to the second argument of your range function:
range(1,math.floor(math.sqrt(x))+1)
You could also use this:
range(math.floor(math.sqrt(x)))
and then add one inside your loop. The former will be faster, however.
As an additional note, unless you're working with Python 3, you should be using xrange instead of range, for idiom/efficiency. More idiomatically, you could also call int instead of math.floor.

Why exactly can't you simply add one to the upper bound of your range call?
Also, it seems like you want to refer to n in your first line, i.e.:
for x in range(1,math.floor(math.sqrt(n)) + 1):
...assuming you want to have the same behavior as your C# snippet.

Related

Convert c++ code to python,with operators?

how would i convert the following code to python?
for (int i = 1; i <= 50; i++)
im not sure the ++ operator exists in python so im having a little bit of a hard time with it.
i = 1
while i <= 50:
# your code here
i += 1
Or
for i in range(1, 51):
pass
range()'s upper bound is exclusive.
that i++ is only a way of displaying i = i + 1.. dont hang around it too much if there is other way..
i = 1
while i <= 50:
print(i)
i += 1 # or i = i + 1 or what ever display that produce the same result
First off, what are you trying to accomplish? Are you trying to write a converter? Or do you need help with Python? In any case, to answer your question, in order to do a for loop in Python, all you have to do is this:
for i in range(6):
print(i)
As per w3schools documentation, the parameters for the range() function are as follows:
range(start, stop, step)
With start being the start number, stop being the number to end at, and step being the number increase/decrease every iteration.
I'm not too experienced with Python. I'm sure that there is a built-in iterator function that allows you to do some enhanced-for-loop trickery.
This loop begins with i = 1 and the last iteration is when i = 50, so you can reproduce this in Python using:
for i in range(1, 51):
print(i)
(if for some reason, you are stuck using Python 2, consider using xrange instead of range)

Python: "If" function

This is probably really simple but I can't figure it out.
I have a bunch of lists and I want to call certain lists if they are in the range equal to a value x and any number between x-5 and x +5. i.e. x-5,x-4,x-3,x-2,x-1,x,x+1,x+2,x+3,x+4 and x+5.
At the moment I have
if sum(listname[i])==x:
if sum(listname[i])==x-1:
if sum(listname[i])==x-2:
etc
How can I do it so that it is combined in one "if" function.
I've been thinking on the lines of something like:
if sum(listname[i])==x-5>=x>=x+5:
or
if sum(listname[i])==x or x-1 or x-2 ".. etc":
but neither work.
Can anybody shine some light on this?
A scenario like if sum(listname[i])==x or x-1 or x-2 ".. etc": (which is not valid python) is usually solved with if value in range(start, stop, step):
So you would write:
if sum(listname[i) in range(x-2, x):
# Code for this case here...
Do you simply mean
if x-5 <= sum(listname[i]) <= x+5:
...
...
It looks like you want to check if the sum of the list is between x - 5 and x + 5. To put it in one if statement is simply:
s = sum(listname[i])
if s >= x - 5 and s <= x + 5:
# do stuff
From what I understand from your question. You what to check that whether sum(listname[i]) is between (x-5, x+5)
You can do this in a single if assuming x is a possitive value:
if (sum(listname[i]) >= (x - 5)) and (sum(listname[i]) <= (x+5))

Python While Loop Square

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.

How to use map lambda of python to make a element to a certain number?

I have a numpy.array called p2De. The first row has multiple elements may larger than 1. I want to set the elements which smaller than 1 to 1. Following is my code, but shows error... why? How to fix it?
bounde=1
p2De[:0]=map(lambda x:bounde if (x < bounde),p2Di[:0])
File "C:\Users\wange\workspace\cathode\src\diffusion.py", line 86
p2De[:0]=map(lambda x:bounde if (x < bounde),p2Di[:0])
^
SyntaxError: invalid syntax
You need to specify an else for your lambda function :
lambda x:bounde if (x < bounde) else #stuff
It should be
lambda x:bounde if (x < bounde) else x
You can also use list comprehension, which is more readable. Also, I would use the max builtin function instead of your lambda:
p2De[:0] = [max(x, bounde) for x in p2Di[:0]]
As others have noted, the syntax problem is in the lambda.
I don't think you want p2De[:0] - that's an empty array. p2De[0] is the 1st row. p2De[0,:] is the same, and makes it clear to the human readers that you have selected the 1st row of a 2d array.
The use of a map or comprehension works, but they don't offer much of an advantage, if any, over a simple loop (since you don't need to replace all of the values):
for i,v in enumerate(p2De[0,:]):
if v<1:
p2De[0,i] = 1
But none of these iterations is good numpy practice. You should try to think in terms of vector operations. A common practice is to use a boolean mask (or indexing) to select the values that should be changed:
I = p2De[0,:]<1 # boolean vector
p2De[0, I] = 1
p2De[0,p2De[0,:]<1]=1 # or one line form
There is also a numpy function that applies limits like this, np.maximum:
p2De[0,:] = np.maximum(p2De[0,:], 1)
np.clip applies both minimum and maximum bounds:
p2De[0,:] = np.clip(p2De[0,:], minbd, maxbd)
np.clip(p2De[0,:], minbd, maxbd, p2De[0,:]) # alt calling method
The Python(3) bosses encourage us to use functions and comprehensions over maps and lambdas. For example if plist was a list like your p2De[0,:] row:
def clip(x):
return 1 if x<1 else x
plist = [clip(x) for x in plist]
plist = [min(x, 1) for x in plist] # using a builtin for this simple case
say if you have a list a, you can do something like this:
a=[2,3,1,7,0,0,8]
bounde=1
b = map(lambda n: n if n > bounde else bounde,a)
print b

Cycle "for" in python like in C [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python decimal range() step value
I have a cycle in C:
for (float i = 0; i < 2 * CONST; i += 0.01) {
// ... do something
}
I need the same cycle in python, but:
for x in xxx
not the same.
How can i make it in python?
You are almost on the line. This is how you do it on a list: -
your_list = [1, 2, 3]
for eachItem in your_list:
print eachItem
If you want to iterate over a certain range: -
for i in xrange(10):
print i
To give a step value you can use a third parameter, so in your case it would be: -
for i in xrange(2 * CONST, 1):
print i
But you can only give an integer value as step value.
If you want to use float increment, you would have to modify your range a little bit:-
for i in xrange(200 * CONST):
print i / 100.0
for i in xrange(200*CONST):
i = i/100.0
Write your own range generator. This helps you deal with non-integer step values with ease, all across your program, solving multiple issues of the same kind. It also is more readable.
def my_range(start, end, step):
while start <= end:
yield start
start += step
for x in my_range(1, 2 * CONST, 0.01):
#do something
For-loop reference
numpy has a method that can be used to create a range of floats.
from numpy import arange
for x in arange(0, 2*CONST, 0.01):
do_something(x)

Categories

Resources