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
Related
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).
I have started to implement backwards Dijkstra's algorithm in python:
def backwardsDijkstra(g: DoubleDictGraph, s, t):
q = PriorityQueue()
dist = {}
next = {}
q.add(t, 0)
dist[t] = 0
found = False
while not q.isEmpty() and not found:
x = q.pop()
for y in g.parseNin(x):
if y not in dist.keys() or dist[x] + g.Cost(x, y) < dist[y]:
dist[y] = dist[x] + g.Cost(x, y)
q.add(y, dist[y])
next[y] = x
if x == t:
found = True
return dist[s], next
And I can't figure out why it stops at the second iteration for the next graph for example:
5 7
0 1 5
0 2 20
1 2 10
1 3 30
2 3 5
2 4 20
3 4 10
(number of vertices, number of edges, (start,end,cost)
The bug in you code is at this line:
if x == t:
found = True
Since you are starting from t (target), you should be looking for s (source). Currently you are breaking out of the loop for the first candidate (which is t).
For some reason, when I try to set a while function, it doesn't do what I want.
For example:
import random
x = 0
while x <= 10:
print random.randint(1, 100)
x += x + 1
This only runs four times. But if I change it to while x <= 1000: it runs ten times. Any idea why?
EDIT
I am sorry, But think this is a legitimate question. Please stop downvoting me! Next time I will do more research into the syntax for problems as simple as this. Sorry.
To increment x by 1 you should use
x += 1
or
x = x + 1
You have combined them into x += x + 1, which adds x+1 to x each time.
Your problem is x += x + 1 is essentially adding x + (x + 1). Simply remove the initial +.
You are adding x + 1 to x. It should be x+=1, that makes you finish sooner:
Start: x = 0
After first iteration: x + x + 1 = 0 + 0 + 1 = 1
After second iteration: x + x + 1 = 1 + 1 + 1 = 3
After third iteration: x + x + 1 = 3 + 3 + 1 = 7
After fourth iteration: x + x + 1 = 7 + 7 + 1 = 15, which is greater that 10 and stops.
You are multiplying x by 2 and adding 1, so it's not an error just is the answer to another question.
I need to make a quick algorithm(I already made a slow one) which will find the number of all possible values from two ranges of integer numbers (ranges can intersect or not) which sum will be the given number
I can represent it like an equation: z = x + y
where z is a known number and equals x plus y
z can be any number between 0 and 10^18
x belongs to a range of integer numbers [a..b], where 0 <= a <= b <= 10^18 and
the difference between the consecutive numbers is 1
y belongs to a range of integer numbers [c..d], where 0 <= c <= d <= 10^18 and
the difference between the consecutive numbers is 1
so I need to find the number(not their exact values) of all the possible variations of x and y from two sets of numbers which sum will be z
Example:
z = 5
first set: a = 1, b = 5(it means the set consists of 1,2,3,4,5)
second set: c = 1, b = 5
then the answer is 4, because all possible combinations are:
x = 4, y = 1
x = 3, y = 2
x = 2, y = 3
x = 1, y = 4
because theirs sums are 5's
The compulsory condition for an algrorithm is to work faster than 1 second
The following code works fine but only with numbers lesser than 1000000. It starts to work much slower with big numbers
with open(r"input.txt") as f:
n = int(f.readline()) # the given number
a = int(f.readline()) # the start position of the first set
b = int(f.readline()) # the end position of the first set
c = int(f.readline()) # the start position of the second set
d = int(f.readline()) # the end position of the second set
# print "n:",n,"a:",a,"b:",b,"c:",c,"d:",d
t = b - a + 1 # all posible variants of the first set
k = d - c + 1 # all posible variants of the second set
number_of_vars = 0
if t >= k:
while b >= a:
if (n - b <= d) \
and (n - b>= c):
number_of_vars += 1
b -= 1
else:
b -= 1
if t < k:
while d >= c:
if (n-d <= b) and (n-d >= a):
number_of_vars += 1
d -= 1
else:
d -= 1
print number_of_vars
No algorithm required -- just algebra:
It suffices to count the number of x in [a,b] for which z - x is in [c,d]
You need both a <= x <= b and c <= z - x <= d. The second inequality is equivalent to z - d <= x <= z - c hence you need
max(a, z - d) <= x <= min(b,z - c)
The number of such x is 0 if min(b,z - c) < max(a, z - d) otherwise it is
min(b,z - c) - max(a, z - d) + 1
In either case the number of solutions is
max(0, min(b,z - c) - max(a, z - d) + 1)
In your example a = c = 1 and b = d = z = 5 and
min(b, z - c) - max(a, z - d) + 1 = min(5,4) - max(1,0) + 1 = 4 - 1 + 1 = 4
One thing that you can use to reduce the checks in your algorithm is,
If the range for the 2 sets are overlapping, then you can cancel out some checks. Like in your example,
range for 1st set is 1 to 5
range for 2nd set is 1 to 5
So, if
x = 4, y = 1
is working, then
x = 1, y = 4
will also work. So you have to go only till half the number (i.e till 3 only in this case)
If only a part of the range is overlapping, then you can use the above method for that part, and the remaining part can be checked using normal method.
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.