Different syntax, different result - python-3.x

I'm trying an ultra simple novice exercise.
The objective of the exercise was to create a fibonacci pattern, I tried two methods that I thought were going to give the same result. But fires some reason they don't, I can't understand why.
Any ideas?
CODE 1
a = 0
b = 1
while b < 100:
print(b)
a = b
b = a + b
CODE 2:
a, b = 0, 1
while b < 100:
print(b)
a, b = b, a + b

In "CODE 1", a = b makes the next line equivalent to b = b + b, which is not correct.
In "CODE 2", a,b=b,a+b is essentially new_a = old_b; new_b = old_a + old_b. The new values are computed from the old values, then the new values are assigned to the variables. This computes the fibonacci series correctly.
To do it correctly in "CODE 1" a temporary variable is needed:
t = a
a = b
b = t + b # use original a saved in t to compute b
a,b=b,a+b eliminates the need for the temporary variable.

Related

Get corresponding element from maximum of element wise 2d array

I have four 2d arrays.
A = [[1,6], [3,5]]
A' = [[11,22], [33,44]] //each index value is related to corresponding index at A
similarly
B = [[5,2],[2,3]]
B' = [[55,66],[77,88]]
output
o/p = [[5,6], [3,5]]
o/p' = [[55,22],[33,44]] // how to get this output
I want to get element wise maximum from A and B, but I want to get the corresponding element
from A' and B'.
Doing a n^2 iteration is taking a lot of time.
numpy.maximum(A,B,A) can get me maximum value but how can I get corresponding elements from A' and B'.
You could do this:
# Defining the arrays
A = np.array([[1,6], [3,5]])
A2 = np.array([[11,22], [33,44]])
B = np.array([[5,2],[2,3]])
B2 = np.array([[55,66],[77,88]])
# Get maximum of A and B. Do not do np.maximum(A, B, A), as this overwrites A.
C = np.maximum(A, B)
# Get indices where C = A and C = B.
A_indices = np.where(C == A)
B_indices = np.where(C == B)
# Get corresponding A2 and B2 values.
C2 = np.copy(C)
C2[A_indices] = A2[A_indices]
C2[B_indices] = B2[B_indices]
C2 now has the values you want. Let me know if you have any questions.

python finding the greatest common divisor of two numbers program

I am a new Python learner. I am trying to finding the greatest common divisor of two numbers (a =1071 and b = 462 for example). I have written two programs for this. the first one is working but the second one gives the wrong answer. what is the problem with my program??
# first program (works)
a, b = 1071, 462
while b:
a, b = b, a % b
print(a)
# second program (doesn't work truly)
a = 1071
b = 462
while b:
a = b
b = a % b
print(a)
Explanation:
Yes, HSK is right. In the 2nd loop:
while b:
a = b
b = a % b
print(a)
First a is changed to b and then what you do is b = b% b. But here:
a, b = b, a % b
it is executed as one-line so a is still a.
Solution:
So just add a third variable:
a = 1071
b = 462
while b:
c = a
a = b
b = c % b
print(c)
One thing that distinguishes Python from other programming languages is that it is interpreted rather than compiled. This means that it is executed line by line.
The second doesn't work because, for the calculation of b, you need to use the old a, not the new a that got generated on the line before (this is actually set to b so you will get b % b, which will generally be zero). The equivalent to the first loop would be:
while b:
oldA = a
a = b
b = oldA % b
print(a)
The tuple assignment in Python can be considered an atomic operation where all the values on the right side are loaded up, then assigned to all the variables on the left side.
def divisor(n):
if n ==1 or n ==2 or n ==3:
return []
else:
result=[]
aux=2
while aux <= n:
if n % aux == 0:
result.append(aux)
aux=aux+1
return result
def func (m,n):
div1=divisor(m)
div2=divisor(n)
result =[]
for x in div1:
for y in div2:
if x == y:
result.append(x)
return result
print(func (x,y))

Alternative to conditionals (if)

I'm having difficulties with this task in python 3.7:
"Define a function that given two integers, a and b, returns the value of their sum. However, if the difference of a and b is an even number, the value of the sum is doubled, on the other hand, if the difference is an odd number, the value of the product of a and b gets added to the value of the sum.
For now, do not use conditionals (if)."
I don't know how to do it without using if statements. I would be thankful if anyone could help me.
If a=2 and b=2, the output should be 8.
If a=1 and b=4, the output should be 9.
To determine if the sum of the two integers is even, we use the modulo operator. The following will only evaluate to 0 or 1: (a - b) % 2. 0 = even, 1 = odd.
Knowing this, we can use this value to index into a list which contains 2 functions.
At index 0 we have the double function, which will be called when the value is even, and at index 1 we have the add_product function, called when it's odd.
def process_numbers(a, b):
def double(c):
c *= 2
return c
def add_product(c):
c += a * b
return c
functions = [double, add_product]
c = a + b
c = functions[(a - b) % 2](c)
print(c)
return c
Here is another solution using anonymous (lambda) functions, and taking advantage of the fact that c & 1 will always evaluate to 0 if the difference between a and b is even, and 1 if it's odd.
def process_numbers(a, b):
functions = (lambda: c*2, lambda: c + a*b)
c = a + b
return functions[c & 1]()
And a one-line monstrosity (avert your eyes!):
>>> (lambda a, b: (lambda: (a + b) * 2, lambda: a + b + a * b)[a + b & 1]())(1, 4)
9
>>> (lambda a, b: (lambda: (a + b) * 2, lambda: a + b + a * b)[a + b & 1]())(2, 2)
8
It's a nice little puzzle. Where did you come across it?
Another solution, based off Demi-Lune's functionless solution.
>>> a, b = 2, 2
>>> (a + b & 1)*(a + b + a*b) + (1 - a + b & 1)*(a + b)*2
8
>>> a, b = 1, 4
>>> (a + b & 1)*(a + b + a*b) + (1 - a + b & 1)*(a + b)*2
9
If the sum of a and b is even, the left half evaluates to 0, and the right half evaluates to the sum being doubled.
If the sum of a and b is odd, the right half evaluates to 0, and the left half evaluates to the sum plus the product.

How to code this pattern using the while loop and for loop?

I am supposed to code this pattern:
[1]
[0][0]
[1][1][1]
[0][0][0][0]
[1][1][1][1][1]
[0][0][0][0][0][0]
[1][1][1][1][1][1][1]
[0][0][0][0][0][0][0][0]
[1][1][1][1][1][1][1][1][1]
However, i am only able to give a output like this:
[1]
[0][0]
[1][1][1]
[0][0][0][0]
[1][1][1][1][1]
[0][0][0][0][0][0]
[1][1][1][1][1][1][1]
[0][0][0][0][0][0][0][0]
[1][1][1][1][1][1][1][1][1]
[0][0][0][0][0][0][0][0][0][0]
this is my current code:
a = '[1]'
b = '[0][0]'
for c in range(1,10,2):
print(a)
a = a + '[1][1]'
print(b)
b = b + '[0][0]'
Please help! I am supposed to the pattern with a while loop and for loop. Thanks in advance!
You're printing both a and b in every iteration, so naturally you can't get odd number of lines in your output.
Instead, use a normal range iterator of 9 and alternate between printing and appending to a and b depending on the counter's remainder of 2.
a = '[1]'
b = '[0][0]'
for c in range(9):
if c % 2 == 0:
print(a)
a = a + '[1][1]'
else:
print(b)
b = b + '[0][0]'
This outputs:
[1]
[0][0]
[1][1][1]
[0][0][0][0]
[1][1][1][1][1]
[0][0][0][0][0][0]
[1][1][1][1][1][1][1]
[0][0][0][0][0][0][0][0]
[1][1][1][1][1][1][1][1][1]

How to append float to list?

I want to append float to list, but I got an error like this:
<ipython-input-47-08d9c3f8f180> in maxEs()
12 Es = lists[0]*0.3862 + lists[1]*0.3091 + lists[2]*0.4884
13 aaa = []
---> 14 Es.append(aaa)
15
AttributeError: 'float' object has no attribute 'append'
I guess I can't append float to list. Can I add floats to list another way?
This is my code:
import math
def maxEs():
for a in range(1, 101):
for b in range(1,101):
for c in range(1,101):
if a+b+c == 100 :
lists = []
lists.append(a*0.01)
lists.append(b*0.01)
lists.append(c*0.01)
Es = lists[0]*0.3862 + lists[1]*0.3091 + lists[2]*0.4884
aaa = []
Es.append(aaa)
I don't know what you want, but you are trying to append a list to a float not the other way round.
Should be
aaa.append(Es)
The other answer already explained the main problem with your code, but there is more:
as already said, it has to be aaa.append(Es) (you did it right for the other list)
speaking of the other list: you don't need it at all; just use the values directly in the formula
aaa is re-initialized and overwritten in each iteration of the loop; you should probably move it to the top
you do not need the inner loop to find c; once you know a and b, you can calculate c so that it satisfies the condition
you can also restrict the loop for b, so the result does not exceed 100
finally, you should probably return some result (the max of aaa maybe?)
We do not know what exactly the code is trying to achieve, but maybe try this:
def maxEs():
aaa = []
for a in range(1, 98 + 1):
for b in range(1, 99-a + 1):
c = 100 - a - b
Es = 0.01 * (a * 0.3862 + b * 0.3091 + c * 0.4884)
aaa.append(Es)
return max(aaa)

Resources