Python - writing print - python

I'm trying to learn Python and going through some exercises, it’s all going good and I’ve learned some new stuff.
But I came across this code over the internet and it wants me to write out what the new Max and Min is supposed to become also B will be after the run.
I have tried to look for the correct answer but no one has printed it. I’ve tried to run it in my IDE but actually I never get an output. I’ve also tried writing “print(b)” but I get no result.
min = 5
max = 10
b = 0
a = -2
if a < min:
min = a
elif a > max:
max = a
else:
b += 1
What I’ve thought the answer should be is Min will be -2 since a is declared as -2 and the first statement “if a < min:” says if -2 is less than 5, 5 will become -2.
Other statement “a > max:” asks if -2 is higher than 10, 10 will be –2 but since -2 is not higher we go to the else which says that we should plus 1 to 0 and that will give b = 1. So my answer is min = -2 , max = 10 , and b = 1.
Is my answer correct and if not what have I done wrong? Also, is there any way I can run it in python and get the answer through print(b, max, min) I’ve tried that but it’s not working.

I guess the second condition should be if not elif. An if-elif-else block exits as soon as any of them satisfies the condition. So, as in your code the first condition if a < min is True, the next conditions are not going to be checked.
min = 5
max = 10
b = 0
a = -2
if a < min:
min = a
if a > max:
max = a
else: <-- this is executed only if: `a > max`: is `False`
b += 1
print b, max, min
#1 10 -2

Related

Why does AND exit my while loop but OR leaves it running? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
I was able to make this program (python 3.9) for my assignment work, but I am having trouble understanding the logic behind it.
I needed to find the root of the polynomial function f(x) = 𝑥^3 − 4𝑥^2 + 3𝑥 − 4. The variables were provided, so I only was required to write the function, a while loop to find the root, and format the output. Part of the required framework was to "execute until the absolute value of val1 and val2 are both less than 0.000001"
My first attempt was
x1 = 0
x2 = 5
val1 = x1**3 - (4*x1**2) + 3*x1 - 4
val2 = x2**3 - (4*x2**2) + 3*x2 - 4
n = 0
while abs(val1) or abs(val2) >= .000001:
n += 1
new_x = (x1+x2)/2
new_val = (new_x**3) - (4 * new_x**2) + (3 * new_x) - 4
if new_val < 0:
x1 = new_x
val1 = new_val
else:
x2 = new_x
val2 = new_val
solution = (x1+x2)/2
print(f"{'The approximate solution is x = '}{solution:.7f}{'.'}")
print(f"{'The algorithm took '}{n}{' iterations to converge.'}")
My reasoning for choosing OR was: both abs(val1) and abs(val2) must be <.000001, so as long as one of the values is greater than or equal to .000001, then the loop will continue to execute. However this caused the loop to run indefinitely. I was able to fix this and complete the assignment by changing the line to:
while abs(val1) and abs(val2) >= .000001:
My confusion stems from my belief that this exits the loop when only one of these statements becomes false, as opposed to both.
Thank you in advance for any guidance you may be able to provide.
In python, like many programming languages, a number (e.g. an integer, float) used as the predicate will resolve to true unless that number is 0. For example,
if 2:
print('2')
if 0.1:
print('0.1')
if 0:
print('0')
In the above code, only 2 and 0.1 will be printed. In your scenario
while abs(val1) or abs(val2) >= .000001:
the first predicate (abs(val1)) was always resolving to true so the while loop was never exiting
it will run if you change your code to following:
while abs(val1) >= .000001 or abs(val2) >= .000001:

Moves to make all the elements in a array equal in Python

I came across a problem in which the input is as follows:
5
1 1 1 1 6
And the expected output is 4
Basically what we are trying to do is print the minimum number of moves it will require to make all the 5 values equal to each other. One move means reducing a location and incrementing another location. If it is not possible to make them all equal, we print -1.
I tried the below approach:
def solution(N, W):
counter=0
W.sort()
k=W[int(N/2)]
for i in range(0,N):
counter=counter+abs(W[i]-k)
if N%2==0:
tempC=0
k=W[int(N/2)-1]
for i in range(0,N):
tempC=tempC+abs(A[i]-k)
counter=min(counter,tempC)
return counter
and am getting 5 as the answer. Kindly share what your function to achieve this would be.
Lets see how logic works with your input.
5 1 1 1 1 6
1. If 1 2 1 3 3 this case possible then finally it show look like this 2 2 2 2 2. What are the things we get from this result Sum(INITAL_LIST) is equal to SUM(FINAL_LIST), this is 1st condition, if this hold pattern is possible.
2. Among all index-value some of them is going to leave some value some will take. Decrement of one-index and Increment of another-index is taken as one step, so we will consider only decrement case. Those who are leaving and finally become equal to 2. So total-step is equal to some of decremented index value.
Here I use vectorization properties of numpy for easy operation.
CODE :
import numpy as np
def solution(N, W):
if sum(W)%N !=0:
return -1
eq = sum(W)//N
step = np.array(W)-eq
step_sum = np.sum(step[step>0])
return step_sum
if __name__ == '__main__':
var_, list_ = input().split(maxsplit=1)
print(solution(int(var_), list(int(i) for i in list_.split())))
WITHOUT NUMPY :
Update :
step = np.array(W)-eq
step_sum = np.sum(step[step>0])
To :
step = [i-eq for i in W]
step_sum = sum(i for i in step if i>0)
OUTPUT :
5 1 1 1 1 6
4

While loop gives values equal to, even though it explicitly states 'less than' not 'less than or equal to' [duplicate]

This question already has answers here:
Why does my while loop output an out-of-bounds value?
(6 answers)
Closed 6 months ago.
I have a while loop question that is stumping me. Below is a simple illustration of what is happening in my code - I ask the while loop to stop when the condition is less than, but it gives the values as if it stated less than or equal to. Does anyone know what i have done wrong?
A = 10.0
B = 20.0
x = 1.0
while ((A < 13.0) and (B < 23.0)):
A += x
B += x
print(A, B)
if x > 100.0:
break
x += 1.0
print(x)
A and B equal 13 and 23 after the second loop iteration, which returns a FALSE in your while condition, thus the loop stops.
You add 1 to A and B after it checks the condition. The loop isn’t some eternal contract within itself; it just checks at the top whether to execute all the instructions inside it, then go to the top and check again.
You could move those instructions after the printing, but then you’d be printing 10 and 20, which you aren’t so far. Otherwise, put another check inside the loop before printing.
The while is correct, but notice that you will sum the "x" value after the last loop.
A = 10.0
B = 20.0
x = 1.0
while ((A < 13.0) and (B < 23.0)):
print('Here they are less then',A,B)
A += x
B += x
print(A, B,x)
if x > 100.0:
break
x += 1.0
To explain that, we have to break down the code:
First, It initializes A, B and x. then it goes into the loop. since both the conditions are correct, it passes through.
Now notice you have added 1.0 to x. That makes x = 2.0.
Now we go back to the loop and it checks the conditions. 11.0 and 21.0 pass.
However, x is now 2.0. So we add 2.0 to A and B. Thus making them 13.0 and 23.0. It then prints it.
So the loop is working perfectly, its the way you have positioned the code that messes it up.

Program not showing all values in for loop

i have started learning python and i have problem.
I learn for loops and i am a little bit confused.
I tried this:
for i in range(0,12,3):
print(i)
Why program is not showing 12 value?
In other languages e.g java it works.
Anyone help?
The upper bound of range is non-inclusive. From the documentation:
For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.
Read more here.
Java's equivalent:
IntStream.range(0, 12 / 3).map(x -> x * 3).forEach(System.out::print);
Also does not include the upper bound. This will also print 0 3 6 9, not 12.
The upper bound of a range is not included. The main advantage is that range(len()) "just works" without having to subtract 1. For example:
>>> x = 'abcd'
>>> for i in range(len(x)):
... print(i, x[i])
...
0 a
1 b
2 c
3 d

lmfit: constraining parameters with respect to other ones

I am having troubles setting the min and max values of a parameter to be fitted in lmfit. Basically, I have two parameters, a and b which need to obey the following constraints:
0 < b < 1
0 < a+b < 1
-b < a < 1
While the first two are rather easy to implement as:
fit_params.add('b', min = 0, max = 1)
fit_params.add('a_plus_b', min = 0, max = 1)
fit_params.add('a', expr = 'a_plus_b-b')
I am missing now an idea on how to include in the system my third condition. Can you suggest a further expression?
Thank you very much,
Leo
The solution is pretty simple, and I should only have read better the lmfit manual here: https://lmfit.github.io/lmfit-py/constraints.html
Trying anyway to be helpful, the solution is given by implementing an if sentence in the parameter expression.
fit_params.add('b', min = 0, max = 1)
fit_params.add('a_plus_b', min = 0, max = 1)
fit_params.add('a', expr = 'a_plus_b-b if a_plus_b-b > 0 else 0.')
I think that you don't actually need your third condition here, as
-b < a < 1
can be re-written as
0 < a+b < 1+b
but since b>0, this condition will always be met with 0 < a+b < 1.
But, to answer the question more generally, you would probably need to introduce another "difference-or-sum variable" as you did with a_plus_b and use that.

Categories