Loop not functioning correctly - python

Working with data frames and this is the code I have for it.
numbers = 3
count=0
A = 0
B = 0
C = 0
for x in range(numbers):
if str(data.iloc[count])== 'A':
A += 1
elif str(data.iloc[count])== 'B':
B += 1
elif str(data.iloc[count])== 'C':
C += 1
count +=1
#this is to return the count to check if it works
print A
print B
print C
but for some reason when I run this code only the count for A increases.
i.e. if the data in the index had a 'A', 'B', 'B' its still returning A = 3 and B = 0 where it should be returning A = 1, B = 2, and C = 0
what am I doing wrong? thanks again.

Since your count += 1 is not within the for loop, count += 1 only runs once, after the for loop is complete. It needs to be indented. Alternatively, you do not need to use a count variable since x is already going through the range 0 to 3:
numbers = 3
A = 0
B = 0
C = 0
for x in range(numbers):
if str(data.iloc[x])== 'A':
A += 1
elif str(data.iloc[x])== 'B':
B += 1
elif str(data.iloc[x])== 'C':
C += 1
#this is to return the count to check if it works
print A
print B
print C

This also worked
count=0
numbers = 3
A = 0
B = 0
C = 0
for x in range(numbers):
count +=1
if str(data.iloc[x])== 'A':
A += 1
elif str(data.iloc[x])== 'B':
B += 1
elif str(data.iloc[x])== 'C':
C += 1
#this is to return the count to check if it works
print A
print B
print C

Related

what is the precedence of a ternary operator in this example?

>>> count = 0
>>> for c in "##.#.":
... count = count + 1 if c == '.' else 0
...
>>> print(count)
1
>>> count = 0
>>> for c in "##.#.":
... count = count + (1 if c == '.' else 0)
...
>>> print(count)
2
Why doesn't the first example print out a counter of 2?
Conditional expressions have a very low precedence.
So the first expression is actually parsed as:
count = (count + 1) if c == '.' else 0
That will set count to 0 every time c != '.'.
In the first case, count value gets replaced
>>> for c in "##.#.":
... count = count + 1 if c == '.' else 0
... print (count)
...
0
0
1
0
1
Here count gets append
>>> count=0
>>> for c in "##.#.":
... count = count + (1 if c == '.' else 0)
... print (count)
...
0
0
1
1
2
>>>
Because this corresponds to the True state of if.
(True) if (Condition) else (Else)
count = count + 1 if c == '.' else 0 True status for this (count + 1)
count + (1 if c == '.' else 0) True status for this (1)
Did I tell you a little bit complicated?

Counter set or rows with the same numbering based on condition

I have dataset. For a certain condition there is a column has True or False values. If there is a sequence of rows has the same value, then let the counter of these rows be the same.
To make it clear, below is my code:
c1 = [True,True,False,False,False,True,False,True,True,False,True]
counter = 1
switch = 0 #increase the counter when the vector has switched twice
c2 = np.repeat(None, len(c1))
c2[i]=counter
for i in range(1,len(c1)):
p = c1[i-1]
x = c1[i]
if p==x:
counter=counter
c2[i]=counter
if p!=x :
switch = switch + 1
c2[i]=switch
elif switch == 2:
counter = counter + 1
switch = 0 #reset the counter
print(c2)
The actual output is
[None 1 1 1 1 2 3 4 1 5 6]
while the expected one should be
[None, 1,1,1,1,2,2,3,3,3,4]
c1 = [True,True,False,False,False,True,False,True,True,False,True]
res = []
var = 1
cur=c1[0]
flag = 0
res.append(None)
for val in c1[1:]:
if val==cur and flag == 0:
res.append(var)
elif val == cur and flag == 1:
var+=1
flag = 0
res.append(var)
elif val != cur and flag == 0:
flag = 1
res.append(var)
elif val != cur and flag == 1:
res.append(var)
else:
pass
print(res)
Output:[None, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4]

Python dice outcome count

Write a function collect_sims(nsim,N,D,p=0.5,nmax=10000) that runs your run_sim function nsim times (with parameters N, D, p) and returns a numpy array of length nmax giving the number of times that the simulation took a specified number of steps to stop. For example, suppose nsim was 8 and successive runs of run_sim gave you 3,4,4,3,6,5,4,4. You would tabulate this as “two 3s, four 4s, one 5, one 6, zero 7s, zero 8s …”
def collect_sims(nsim, N, D, p=0.5, nmax=10000):
run_sim(N=20, D=6, p=0.5, itmax=5000)
onecount = 0
twocount = 0
threecount = 0
fourcount = 0
fivecount = 0
sixcount = 0
for k in range (n):
if D == 1:
onecount += 1
if D == 2:
twocount += 1
if D == 3:
threecount += 1
if D == 4:
fourcount += 1
if D == 5:
fivecount += 1
if D == 6:
sixcount += 1
return(k)
print(onecount, "1",twocount,"2",threecount,"3",fourcount,"4",fivecount,"5",sixcount,"6")
It says my 6 variables onecount, twocount, etc are not defined, how can I define them? Also, what can I do to fix my code?
I don't know why are you returning k.
Anyway, the problem is that oncount, twocount, ... etc is in different scope that print. You can put the print() inside the function or you can return an tuple with the counts
Some like that:
def collect_sims(nsim, N, D, p=0.5, nmax=10000):
run_sim(N=20, D=6, p=0.5, itmax=5000)
onecount = 0
twocount = 0
threecount = 0
fourcount = 0
fivecount = 0
sixcount = 0
for k in range (n):
if D == 1:
onecount += 1
if D == 2:
twocount += 1
if D == 3:
threecount += 1
if D == 4:
fourcount += 1
if D == 5:
fivecount += 1
if D == 6:
sixcount += 1
return(onecount, twocount, threecount, fourcount,fivecount,sixcount)
onecount, twocount, threecount, fourcount,fivecount,sixcount = collect_sims (...)
print(onecount, "1",twocount,"2",threecount,"3",fourcount,"4",fivecount,"5",sixcount,"6")
Different Solution
Maybe this other solution can help you:
https://stackoverflow.com/a/9744274/6237334
Indent your for loop: in the code you posted, it's back at the original indentation level (none, for the for statement). This ends your function, and the loop is in the main program. Your variables aren't defined yet (since they're not the same as the ones in the function), and your return is illegal.
Try this, perhaps?
def collect_sims(nsim, N, D, p=0.5, nmax=10000):
run_sim(N=20, D=6, p=0.5, itmax=5000)
onecount = 0
twocount = 0
threecount = 0
fourcount = 0
fivecount = 0
sixcount = 0
for k in range (n):
if D == 1:
onecount += 1
if D == 2:
twocount += 1
if D == 3:
threecount += 1
if D == 4:
fourcount += 1
if D == 5:
fivecount += 1
if D == 6:
sixcount += 1
print(onecount, "1",twocount,"2",threecount,"3",fourcount,"4",fivecount,"5",sixcount,"6")
collect_sims()
I can't test, since you didn't supply enough code. Also, note that I simply left the print statement in place as a debugging trace. You have to return an array, and you've made no attempt to do that yet. Your original code returned k, which had to be n+1. This is not useful to the calling program.
FURTHER HELP
Learn to use a list of 6 elements for the counts, rather than six separate variables. Even better, put all of the die rolls into a list, and simply use the count function to determine how many of each you have.

not getting output for euler challenge 3

I am attempting to solve Project Euler: Problem 3, and I am using the following function to test for primality,
def check_prime(x):
i = 1
b = 0
while b == 0 :
i += 1
if i >= x :
return True
b += 1
elif x%i == 0 :
return False
b += 1
Which I call from the rest of my program
a = 3
z = []
number_used = 600851475143
while a < number_used/2 :
if check_prime(a) and number_used%a == 0 :
z.append(a);
a += 2
else :
a += 2
print z
But, the code is not printing the prime factors needed for the third Euler problem. Is my code too inefficient to manage it?

How do you read loops?

What is the thought process when evaluating a loop? I really have no idea how the shell gets these answers (A: 12, B: 2, C: 4, D: 6).
A, B, C, D = 0, 0, 0, 0
while A <= 10:
A += 2
if A%3 == 0:
B += 1
else:
C += 1
D += 1
Perhaps you can read it more easily if you break it down:
A = 0
while A <= 10:
A += 2
Can you read this? Do you understand how it gets to 12?
A, D = 0, 0
while A <= 10:
A += 2
D += 1
Also including D should not make it any harder.
Can you read and understand the if-statement by itself?
if A%3 == 0:
B += 1
else:
C += 1
How about when it is inside the loop?
A, B, C, D = 0, 0, 0, 0
while A <= 10:
A += 2
if A%3 == 0:
B += 1
else:
C += 1
D += 1
B and C are related; exactly one of them are incremented in each iteration, so they should add up to the same as D, which they do.
Do you have any specific problems reading and understanding this now? :)
The other answers are good. I would highly recommend going through things with a pen and paper to make sure you understand what's going on.
Using print inside the loop is also useful to see what is going on while your program runs.
A,B,C,D = 0,0,0,0
while A <= 10:
A += 2
if A%3 == 0:
B += 1
else:
C += 1
D += 1
print "A =", A, " B =", B, " C =", C, " D =", D
The output shows you the values of A, B, C, D at the end of every loop iteration.
A = 2 B = 0 C = 1 D = 1
A = 4 B = 0 C = 2 D = 2
A = 6 B = 1 C = 2 D = 3
A = 8 B = 1 C = 3 D = 4
A = 10 B = 1 C = 4 D = 5
A = 12 B = 2 C = 4 D = 6
You can see that:
A gets incremented by 2 every loop iteration
B gets incremented by 1 IF A is divisible by 3, that is A%3 == 0
C gets incremented by 1 IF A is NOT divisible by 3
D gets incremented by 1 every loop iteration
When it comes to loops, you can think of the collection of indented code as a single "chunk" of code that gets executed once for every repetition of the loop. The formal term for this code chunk is a block. It also applies to if/else statements.
The body of the while loop will execute 6 times (for A=0,2,4,6,8,10).
At each iteration, A is incremented by 2, so after the first statement
within the loop it has values 2,4,6,8,10,12.
B is incremented by one twice (when A=6 and A=12);
C is incremented by one for the remaining values of A.
D is incremented every time round the loop.
Hence, after the loop, A=12, B=2, C=4 and D=6.

Categories