Resolve CODE 2 to print output as CODE 1 and give the reason why both of the codes have different outputs.
Fibonacci Series
CODE 1
x = 0
y = 1
while x < 10:
print(x)
x, y = y, x + y
output
0
1
1
2
3
5
8
CODE 2
x = 0
y = 1
while x < 10:
print(x)
x = y
y = x + y
Output
0
1
2
4
8
Those are simply not identical.
In the first code block y becomes x+y and in the second code block y becomes 2*y.
Just a quick note the output of the second code block is 0 1 2 4 8 and not what you wrote (this was fixed).
Related
From this pandas df
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
samples_indices = df.sample(frac=0.5, replace=False).index
df.loc[samples_indices] = 'X'
will assign 'X' to all columns in randomly selected rows corresponding to 50% of df, like so:
X X X X
1 1 1 1
X X X X
1 1 1 1
But how do I assign 'X' to 50% randomly selected cells in the df?
For example like this:
X X X 1
1 X 1 1
X X X 1
1 1 1 X
Use numpy and boolean indexing, for an efficient solution:
import numpy as np
df[np.random.choice([True, False], size=df.shape)] = 'X'
# with a custom probability:
N = 0.5
df[np.random.choice([True, False], size=df.shape, p=[N, 1-N])] = 'X'
Example output:
0 1 2 3
0 X 1 X X
1 X X 1 X
2 X X X 1
3 X X 1 X
If you need an exact proportion, you can use:
frac = 0.5
df[np.random.permutation(df.size).reshape(df.shape)>=df.size*frac] = 'X'
Example:
0 1 2 3
0 X 1 X 1
1 X 1 X 1
2 1 1 X 1
3 X X 1 X
In #mozway's answer you can set to 'X' cells with a certain probability. But let's say you want to have exactly 50% of your data being marked as 'X'. This is how you can do it:
import numpy as np
df[np.random.permutation(np.hstack([np.ones(df.size // 2), np.zeros(df.size // 2)])).astype(bool).reshape(df.shape)] = 'X'
Example output:
X X X 1
1 X 1 1
X X X 1
1 1 1 X
Create MultiIndex Series by DataFrame.stack, then use Series.sample and last replace removed values by X in Series.unstack:
N = 0.5
df = (df.stack().sample(frac=1-N).unstack(fill_value='X')
.reindex(index=df.index, columns=df.columns, fill_value='X'))
print (df)
0 1 2 3
0 X X 1 1
1 X 1 X 1
2 1 X X X
3 1 1 1 X
I have a list with 4 elements. Each element is a correct score that I am pulling from a form. For example:
scoreFixed_1 = 1
scoreFixed_2 = 2
scoreFixed_3 = 3
scoreFixed_4 = 4
scoreFixed = [scoreFixed_1, scoreFixed_2, scoreFixed_3, scoreFixed_4]
Then, I need to add:
scoreFixed_1 to fixture[0][0]
scoreFixed_2 to fixture[0][1]
scoreFixed_3 to fixture[1][0]
scoreFixed_4 to fixture[1][1]
Hence, I need to create a triple for loop that outputs the following sequence so I can index to achieve the result above:
0 0 0
1 0 1
2 1 0
3 1 1
I have tried to use this to create this matrix, however I am only able to get the first column correct. Can anyone help?
for x in range(1):
for y in range(1):
for z in range(4):
print(z, x, y)
which outputs:
0 0 0
1 0 0
2 0 0
3 0 0
Your logic does not generate the table, you want something like:
rownum = 0
for x in range(2):
for y in range(2):
print (rownum, x, y)
rownum += 1
(Edit: The question has been changed, to accomplish the new desire, you want something like this:)
scoreIndex = 0
for x in range(2):
for y in range(2):
fixture[x][y] += scoreFixed[scoreIndex]
scoreIndex += 1
After your edit, it seems like we can split the 'sequence' into:
First column, regular ascending variable ( n += 1)
Second and third column, binary counter (00, 01, 10, 11)
0 0 0
1 0 1
2 1 0
3 1 1
^ ^------- These seem like a binary counter
(00, 01, 10, 11)
^------ A regular ascending variable
( n += 1 )
Using that 'logic' we can create a code that looks like
import itertools
scoreFixed = 0
for i in itertools.product([0,1],repeat=2):
print(scoreFixed, ' '.join(map(str,i)))
scoreFixed += 1
And wil output:
0 0 0
1 0 1
2 1 0
3 1 1
As you can test in this online demo
for x in range(4):
z = int(bin(x)[-1])
y = bin(x)[-2]
y = int(y) if y.isdigit() else 0
print(x, y, z)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
m = 0
x = 1
while x < 4:
y = 1
while y < 3:
m = m + x + y
y = y + 1
x = x + 1
print(m)
The output is supposed to be 21 but i dont get it , what am i missing? a little help please
m = 0 and x = 1
Since x < 4 it goes inside the while loop where y is set to 1
Since y < 3 it goes inside the nested while
m becomes m + x + y = 0 + 1 + 1 = 2 and y becomes y + 1 = 1 + 1 = 2
Back to the loop condition: y < 3? Yes! Because y = 2. So it goes again inside the while
m becomes m + x + y = 2 + 1 + 2 = 5 and y becomes 3
Back again to the loop condition: y < 3? No! 3 is not less than 3, so the while is now skipped
x becomes x + 1 = 1 + 1 = 2
Back to first while condition: x < 4? Yes! Because x = 2. So it goes inside the loop again
Back to step 2.
When x finally becomes 4, the while loop will terminate and m will be printed.
Let's have a "graphical" representation.
Consider:
x values starting with 1 and growing from left to right (we don't care what's after 3: while x < 4)
y values (!!! for each x !!!) starting with 1 and growing from top to bottom (we don't care what's after 2: while y < 3)
x values are displayed using the "normal" font style, while y ones are displayed in "italic"
Everything that we care about is displayed in "bold" (actually what is not in "bold" won't even be computed by the program, I'm placing those values here, just for clarity's sake):
x values (x ∈ {1, 2, 3})
y values (y ∈ {1, 2})
x row is displayed twice, since for each y, x is added to the sum
The sum:
Is under the separation line and starts from 0
Each number is the sum (consider it a partial sum) of the numbers (in bold) on that column (above it) - they correspond to one x iteration and they contain all y iterations for that x
At the end, we add those values - for all x iterations - and get the final value
x (→): 1 2 3 4 5 6 ...
y (↓): 1 1 1 1 ...
x (→): 1 2 3 4 5 6 ...
y (↓): 2 2 2 2 ...
y (↓): 3 3 3 3 ...
y (↓): ... ... ... ... ...
sum: 0 + 5 + 7 + 9 = 21
A very simplified example:
n=1
a=n
x=1
y=a+1
while (y-x) <10:
n+=1
print(x,y)
print(n,a)
This would go into an endless loop of :
x= 1 y= 2
n= 2 a= 1
x= 1 y= 2
n= 3 a= 1
x= 1 y= 2
n= 4 a= 1
x= 1 y= 2
n= 5 a= 1
x= 1 y= 2
n= 6 a= 1
x= 1 y= 2
n= 7 a= 1
As you can see, n is being updated by the loop and can be called however a is not being updated to the updated n value. I was wondering why this was. Such is the case if y is just n+1.
Operations on int objects (+= here) always create a new integer object, it doesn't mutate the previous value. Therefore, the changes to n won't be reflected in a despite the a = n assignment.
You need to rebind a to n each time you change the value for n:
while (y-x) <10:
n += 1
a = n
I have a data frame that looks like this, but with several hundred thousand rows:
df
D x y
0 y 5.887672 6.284714
1 y 9.038657 10.972742
2 n 2.820448 6.954992
3 y 5.319575 15.475197
4 n 1.647302 7.941926
5 n 5.825357 13.747091
6 n 5.937630 6.435687
7 y 7.789661 11.868023
8 n 2.669362 11.300062
9 y 1.153347 17.625158
I want to know what proportion of values ("D") in each x:y grid space is "n".
I can do it by brute force, by stepping through x and y and calculating the percentage:
zonexy = {}
for x in np.arange(0,10,2.5):
dfx = df[(df['x'] >= x) & (df['x'] < x+2.5)]
zonexy[x] = {}
for y in np.arange(0,24,6):
dfy = dfx[(dfx['y'] >= y) & (dfx['y'] < y+6)]
try:
pctn = len(dfy[dfy['Descr']=='n'])/len(dfy) * 100.0
except ZeroDivisionError:
pctn = 0
zonexy[x][y] = pctn
Output:
pd.DataFrame(zonexy)
0.0 2.5 5.0 7.5
0 0 0 0 0
6 100 100 50 0
12 0 0 50 0
18 0 0 0 0
But this, and all the variations on this theme that I've tried, is very slow. It seems like there should be a much more efficient way (probably via numpy), but I'm blanking on it.
One way would be to use the 2D histogram function of numpy:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram2d.html
Then,
Run it once on the data where the criteria is matched (here, "D" is "n")
Run it again on all of the data.
Divide the first result, element-by-element, with the second result.