Why i = 1, and i = i + 1 would become 2? - python-3.x

i = 1
i = i + 1
print(i)
I am pretty confused about the code's logic. Why would i eventually become 2?

Lets begin with the first assignment:
i = 1
This creates the variable i and initialize it to the integer value 1.
Then we get to what you seem to have problem understanding:
i = i + 1
This statement can be split into two parts:
The addition
The assignment
The addition i + 1 will take the current values of the variable i, which is 1, and add the value 1 to that. In essence the expression i + 1 is the same as 1 + 1.
The result of the addition will be 2. And this result is then assigned to the variable i, making the value of i be equal to 2.
You then print the (new) current value of i:
print(i)
This will of course print the value 2.

The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1.
Just for completeness:
x += y is not always doing an in-place operation, there are (at least) three exceptions:
If x doesn't implement an __iadd__ method then the x += y statement is just a shorthand for x = x + y. This would be the case if x was something like an int
If __iadd__ returns NotImplemented, Python falls back to x = x + y.
The __iadd__ method could theoretically be implemented to not work in place. It'd be really weird to do that, though.
As it happens your bs are numpy.ndarrays which implements __iadd__ and return itself so your second loop modifies the original array in-place.
You can read more on this in the Python documentation of "Emulating Numeric Types".

'i' is a variable which stored 1 if We add 1 again in 'i' that means
i=1;
i+1 means 1+1=2
i=1
i=i+1// i has already 1 and here we are adding 1 again so result will be 2.
hope you understood.

Let's start from i = 1. So you are assigning i to 1. Now your situation is:
i = i + 1
So if i is 1, then the abovementioned code would be "translated" to:
i = 1 + 1
That's why i = i + 1 is equal to 2.

Related

How can I store a variable in a list number?

I have a piece of code which uses a counter to move through a list but the problem is that when I do counter+1 it does not store in the variable counter.
code:
list = [1,2,3,4,5]
counter = 0
b = list[counter]+list[counter+1]
print(counter)
I expect this to return 1 since I added 1 to the counter but instead it returns 0 as if i had not add anything.
As joshmeranda said, counter + 1 does not change the counter variable.
You'd probably have to separately increment the counter variable, like:
list = [1,2,3,4,5]
counter = 0
b = list[counter]+list[counter+1]
counter += 1 #variable += 1 is syntastic sugar for variable = variable + 1
print(counter)

calling functions in python 3 from within a function

Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring).
last2('hixxhi') → 1
last2('xaxxaxaxx') → 1
last2('axxxaaxx') → 2
I found this question in one of the websites (https://codingbat.com/prob/p145834).
The answer to the above question as given on the website is as follows :
def last2(str):
# Screen out too-short string case.
if len(str) < 2:
return 0
# last 2 chars, can be written as str[-2:]
last2 = str[len(str)-2:]
count = 0
# Check each substring length 2 starting at i
for i in range(len(str)-2):
sub = str[i:i+2]
if sub == last2:
count = count + 1
return count
I have a doubt on the below mentioned line of code
last2 = str[len(str)-2:]
Now, I know that this piece of code is extracting the last 2 letters of the string 'str'. What I am confused about is the variable name. As you can see that the variable name is same as the name of the function. So is this line calling the function again and updating the value of the variable 'str' ??
def last2(str):
. . .
This creates a parameter called str that shadows the built-in str class*. Within this function, str refers to the str parameter, not the str built-in class.
This is poor practice though. Don't name your variables the same thing as existing builtins. This causes confusing situations like this, and leads to issues like this.
A better name would be something that describes what purpose the string has, instead of just a generic, non-meaningful str.
* The built-in str is actually a class, not a plain function. str(x) is a call to the constructor of the str class.
def last2(str):
if len(str) == 0:
return 0
last_two = str[-2::]
count = 0
for i in range(len(str)):
if last_two == str[i :i + 2]:
count += 1
return count-1
this is the answer that was correct for me for the first time. The official answer is better, but this one might be less confusing for you.

how to convert decimal to binary by using repeated division in python

how to convert decimal to binary by using repeated division in python?
i know i have to use a while loop, and use modulus sign and others {%} and {//} to do this...but i need some kind of example for me to understand how its done so i can understand completely.
CORRECT ME, if I'm wrong:
number = int(input("Enter a numberto convert into binary: "))
result = ""
while number != 0:
remainder = number % 2 # gives the exact remainder
times = number // 2
result = str(remainder) + result
print("The binary representation is", result)
break
Thank You
Making a "break" without any condition, makes the loop useless, so the code only executes once no matter what.
-
If you don't need to keep the original number, you can change "number" as you go.
If you do need to keep the original number, you can make a different variable like "times".
You seem to have mixed these two scenarios together.
-
If you want to print all the steps, the print will be inside the loop so it prints multiple times.
If you only want to print the final result, then the print goes outside the loop.
while number != 0:
remainder = number % 2 # gives the exact remainder
number = number // 2
result = str(remainder) + result
print("The binary representation is", result)
-
The concatenation line:
Putting the print inside the loop might help you see how it works.
we can make an example:
the value in result might be "11010" (a string, with quotes)
the value in remainder might be 0 (an integer, no quotes)
str(remainder) turns the remainder into a string = "0" instead of 0
So when we look at the assignment statement:
result = str(remainder) + result
The right side of the assignment operator = is evaulated first.
The right side of the = is
str(remainder) + result
which, as we went over above has the values:
"0" + "11010"
This is string concatenation. It just puts one string on the end of the other one. The result is:
"0 11010"
"011010"
That is the value evaluated on the right side of the assignment statement.
result = "011010"
Now that is the value of result.
B_Number = 0
cnt = 0
while (N != 0):
rem = N % 2
c = pow(10, cnt)
B_Number += rem * c
N //= 2
# Count used to store exponent value
cnt += 1
return B_Number

Matlab, order cells of strings according to the first one

I have 2 cell of strings and I would like to order them according to the first one.
A = {'a';'b';'c'}
B = {'b';'a';'c'}
idx = [2,1,3] % TO FIND
B=B(idx);
I would like to find a way to find idx...
Use the second output of ismember. ismember tells you whether or not values in the first set are anywhere in the second set. The second output tells you where these values are located if we find anything. As such:
A = {'a';'b';'c'}
B = {'b';'a';'c'}
[~,idx] = ismember(A, B);
Note that there is a minor typo when you declared your cell arrays. You have a colon in between b and c for A and a and c for B. I placed a semi-colon there for both for correctness.
Therefore, we get:
idx =
2
1
3
Benchmarking
We have three very good algorithms here. As such, let's see how this performs by doing a benchmarking test. What I'm going to do is generate a 10000 x 1 random character array of lower case letters. This will then be encapsulated into a 10000 x 1 cell array, where each cell is a single character array. I construct A this way, and B is a random permutation of the elements in A. This is the code that I wrote to do this for us:
letters = char(97 + (0:25));
rng(123); %// Set seed for reproducibility
ind = randi(26, [10000, 1]);
lettersMat = letters(ind);
A = mat2cell(lettersMat, ones(10000,1), 1);
B = A(randperm(10000));
Now... here comes the testing code:
clear all;
close all;
letters = char(97 + (0:25));
rng(123); %// Set seed for reproducibility
ind = randi(26, [10000, 1]);
lettersMat = letters(ind);
A = mat2cell(lettersMat, 1, ones(10000,1));
B = A(randperm(10000));
tic;
[~,idx] = ismember(A,B);
t = toc;
fprintf('ismember: %f\n', t);
clear idx; %// Make sure test is unbiased
tic;
[~,idx] = max(bsxfun(#eq,char(A),char(B)'));
t = toc;
fprintf('bsxfun: %f\n', t);
clear idx; %// Make sure test is unbiased
tic;
[~, indA] = sort(A);
[~, indB] = sort(B);
idx = indB(indA);
t = toc;
fprintf('sort: %f\n', t);
This is what I get for timing:
ismember: 0.058947
bsxfun: 0.110809
sort: 0.006054
Luis Mendo's approach is the fastest, followed by ismember, and then finally bsxfun. For code compactness, ismember is preferred but for performance, sort is better. Personally, I think bsxfun should win because it's such a nice function to use ;).
This seems to be significantly faster than using ismember (although admittedly less clear than #rayryeng's answer). With thanks to #Divakar for his correction on this answer.
[~, indA] = sort(A);
[~, indB] = sort(B);
idx = indA(indB);
I had to jump in as it seems runtime performance could be a criteria here :)
Assuming that you are dealing with scalar strings(one character in each cell), here's my take that works even when you have not-commmon elements between A and B and uses the very powerful bsxfun and as such I am really hoping this would be runtime-efficient -
[v,idx] = max(bsxfun(#eq,char(A),char(B)'));
idx = v.*idx
Example -
A =
'a' 'b' 'c' 'd'
B =
'b' 'a' 'c' 'e'
idx =
2 1 3 0
For a specific case when you have no not-common elements between A and B, it becomes a one-liner -
[~,idx] = max(bsxfun(#eq,char(A),char(B)'))
Example -
A =
'a' 'b' 'c'
B =
'b' 'a' 'c'
idx =
2 1 3

Fibonacci Sequence logic in Python [duplicate]

This question already has answers here:
How to write the Fibonacci Sequence?
(67 answers)
Closed 9 years ago.
A tutorial I am going through had the following program
# This program calculates the Fibonacci sequence
a = 0
b = 1
count = 0
max_count = 20
while count < max_count:
count = count + 1
old_a = a # we need to keep track of a since we change it
print(old_a,end=" ") # Notice the magic end=" " in the print function arguments that
# keeps it from creating a new line
a = b
b = old_a + b
print() # gets a new (empty) line
The code is perfect. However, I am not able to figure out how the sequence is calculated.
How are the values changed to create the sequence?
It'll make more sense if you remove all of that extraneous code:
while count < max_count:
old_a = a
a = b
b = old_a + b
The old_a is probably confusing you. It's the long way of writing this:
a, b = b, a + b
Which swaps a with b and (at the same time), b with a + b. Note that it isn't the same as writing:
a = b
b = a + b
Because by the time you re-define b, a already holds its new value, which is equal to b.
I'd also run through the code manually by writing it out on paper.
This code works fine:
a, b = 0, 1
for _ in range(20):
print a
a, b = b, a+b

Resources