How to replace the for with a while loop - python

How can I change the for loop into a while loop. What are the significant differences between using for and while loop?
S="I had a cat named amanda when I was little"
count = 0
for i in S:
if i =="a":
count += 1
print (count)

Following is the while loop implementation of same code.
i = 0
count = 0
while i < len(S):
if S[i] == 'a':
count += 1
i += 1
print count

You need a counter which will be incremented each time "while counter < len(S)"
Here's a start:
index = 0
count = 0
while index < len(S):
#do something with index and S ...
index += 1

You could also do it via the boolean nature of an empty string/list/dictionary.
S="I had a cat named amanda when I was little"
count = 0
while S:
# pop the first character off of the string
ch, S = S[0], S[1:]
if ch == "a":
count += 1
print (count)

Related

Python - WHILE loop nested in FOR loop

I was trying to achieve this output:
0;12
1;24
2;36
3;48
4;60
... but I got this:
0;12
1;12
2;12
3;12
4;12
Here is the code:
iter = 0
count = 0
letter = 0
for iter in range(5):
while letter < len("hello, world"):
letter+=1
count+=1
print("Iteration " + str(iter) + "; count is: " + str(count))
I managed to fix this by adding count*(iter+1) instead of count in print statement, but what I'm trying to understand is why count variable resets every time when new for iteration begins.
Thanks in advance.
letter is always 13 since it is not reinitialized. So while loop will be executed only once. To fix this,
count = 0
for iter in range(5):
letter = 0
while letter < len("hello, world"):
letter+=1
count+=1
print("Iteration " + str(iter) + "; count is: " + str(count))
What's happening here is you never set letter to 0 after an interation. So letter always stays at 12.
Printing letter like this:
iter = 0
count = 0
letter = 0
for iter in range(5):
while letter < 12:
letter+=1
count+=1
print(letter)
Outputs:
1
2
3
4
5
6
7
8
9
10
11
12
After the first while iteration letter stays at 12 and therefore while letter < 12: is never run so count never increases.
Make sure to set letter to 0 after each while loop:
iter = 0
count = 0
letter = 0
for iter in range(5):
while letter < 12:
letter+=1
count+=1
letter=0
there! this can be fixed by resetting letter to 0 after each while loop. The while loop will only run the first time because, during the second time, the letter value increases to 13 and is no longer < len("hello, world").
iter = 0
count = 0
letter = 0
for iter in range(5):
while letter < len("hello, world"):
letter+=1
count+=1
print("Iteration " + str(iter) + "; count is: " + str(count))
letter=0

couldn't figure out the string count behaviour in certain input

string = input("Enter the string: ")
sub_string = input("Enter sub string: ")
count = 0
idx = 0
while string.count(sub_string, idx) != 0:
count += string.count(sub_string, idx)
idx = string.index(sub_string, idx)
idx += 1
if string.count(sub_string, idx) == 0:
print(count)
break
when i give this code input as follows:
ininini
ini
It prints output 4. I tried running debugger and found out that it is incrementing count with +2 in the first step instead of +1 and I couldn't figure out that. Any suggestions would be very much helpful.
Use:
count += 1
instead of
count += string.count(sub_string, idx)
string.count(sub_string, idx) is 2 initially, and that's why you end up adding 2 in first iteration (instead of intended 1), thereby getting a 1 more than expected.
What you need is to increment count by 1 in every iteration and if you make this change, you get 3 as output.
I would use a for loop instead:
string = input("Enter the string: ")
sub_string = input("Enter sub string: ")
count = 0
for index in range(len(string) - len(sub_string) + 1):
if string[index: index + len(sub_string)] == sub_string:
count += 1
print(count)
If you are tyring to reach to get the length of the string, just use
len(string)

Where to place counter variable in python loop?

What disallows me from putting the evenCounter or 'oddCounter' variables inside the for loop or if statement? How does the loop know where the counters are if they are out of the loop's scope?
list1 = [1,2,3,4,5,6,7,8]
evenCounter = 0
oddCounter = 0
for i in list1:
if i%2 == 0:
evenCounter += 1
else:
oddCounter += 1
print(evenCounter)
print(oddCounter)
if this question is a duplicate, dont hesitate to flag it as such
If the counter is in the loop, it keeps restarting as you iterate through your sequence. The loopCounter below is getting added in the if-else loop but keeps resetting to zero at every iteration, in this example, you can see it with print
list1 = [1,2,3,4,5,6,7,8]
evenCounter = 0
oddCounter = 0
for i in list1:
loopCounter = 0
print(loopCounter)
if i%2 == 0:
evenCounter += 1
loopCounter += 1
else:
oddCounter += 1
loopCounter += 1
print(evenCounter)
print(oddCounter)

Python - variable not updating in loop

I am trying to solve the 'Love-Letter' mystery problem of HackerRank using Python, but I am stuck at a place where in my loop a variable is not getting updated.
s = input()
first_char = s[0]
last_char = s[-1]
ascii_first_char = ord(first_char)
ascii_last_char = ord(last_char)
count = 0
i = 1
while ascii_first_char < ascii_last_char:
count += abs((ascii_last_char-ascii_first_char))
ascii_first_char = ord(s[i])
ascii_last_char = ord(s[-i])
i += 1
print(count)
If you try to run that, you would see that alc is not changing it's value according to ord(s[i]) where I keeps incrementing. Why is that happening?
You get the first letter with s[0] and the last with s[-1]. In your loop you take the next letters with the same index i.
I don't understand your condition in the while loop. Instead of "ascii_first_char < ascii_last_char" you should test if you have looked at every element of the string. For that we have to loop len(s)/2 times. Something like:
while i < len(s) - i:
or equivalent
while 2*i < len(s):
And this conditions only work for even length. I prefer for-loops when I know how many times I will loop
current_line = input()
# if length is even, we don't care about the letter in the middle
# abcde <-- just need to look for first and last 2 values
# 5 // 2 == 2
half_length = len(current_line) // 2
changes = 0
for i in range(index):
changes += abs(
ord(current_line[i]) - ord(current_line[-(i+1)])
)
print (changes)
s1 = ['abc','abcba','abcd','cba']
for s in s1:
count = 0
i = 0
j = -1
median = len(s)/2
if median == 1:
count += abs(ord(s[0])-ord(s[-1]))
else:
while i < len(s)/2:
count += abs(ord(s[j])-ord(s[i]))
i += 1
j -= 1
print(count)

Counting the distance between values with python

I am new to python and would be grateful for some help.
I have this script that counts every three bases in a sequence until it identifies a stop codon, then breaks and returns the value. This works for each reading frame 0, +1, +2.
I would like it to return a value of 0 it the script runs to the end of the sequence before identifying a stop codon. At the moment the script returns 18 for count0 which should be 0 as the sequence ends before finding either a "TAG" or a "TAA"
Any help would be gratefully appreciated!
seq="TCATTCTaTTTAAAAAAatATAAAaGGGgTTTTGGGgTTTtGGGGTTTtGGGG"
stop_codons = ["TAG", "TAA"]
count0 = 0
n = 0
while n < len(seq):
if seq[n:n+3] in stop_codons:
break
count0 += 1
n += 3
print count0
count1 = 0
n = 1
while n < len(seq):
if seq[n:n+3] in stop_codons:
break
count1 += 1
n += 3
print count1
count2 = 0
n = 2
while n < len(seq):
if seq[n:n+3] in stop_codons:
break
count2 += 1
n += 3
print count2
Result:
18
3
6
A simple fix would be to do something like this. Nevertheless you should consider refactor your code.
stop_codons = ["TAG", "TAA"]
count0 = 0
n = 0
found = False
while n < len(seq):
if seq[n:n+3] in stop_codons:
found = True
break
count0 += 1
n += 3
if not found:
count0 = 0
I recommend pushing the iterating code into a function:
def get_codon_index(seq, start_idx):
count = 0
n = start_idx
while n < len(seq):
if seq[n:n+3] in stop_codons:
return count
count += 1
n += 3
return -1
This way you save the effort of introducing boolean flags and avoid code duplication.
I return -1 instead of 0, because 0 might be an actual index of a codon (if the codon is right at the beginning of your sequence).
seq="TCATTCTaTTTAAAAAAatATAAAaGGGgTTTTGGGgTTTtGGGGTTTtGGGG"
stop_codons = ["TAG", "TAA"]
def printcount(seq, stop_codons, start):
found = False
count = 0
n = start
while n < len(seq):
if seq[n:n+3] in stop_codons:
found = True
break
count += 1
n += 3
print count if found else 0
printcount(seq, stop_codons, 0)
printcount(seq, stop_codons, 1)
printcount(seq, stop_codons, 2)
You search for the stop codon, and if it finds it, it exits the loop prematurely.
But otherwise, it runs the complete loop, exits the loop when n == len(seq) and then still prints the count.
Two solutions:
Print only when you find a stop codon:
count1 = 0
n = 1
while n < len(seq):
if seq[n:n+3] in stop_codons:
print count1
break
count1 += 1
n += 3
or set a stopped flag:
count1 = 0
n = 1
stopped = False
while n < len(seq):
if seq[n:n+3] in stop_codons:
stopped = True
break
count1 += 1
n += 3
if stopped:
print count1
this code will loop through your sequence and stops when it finds a TAA or TAG sequence returning the position of the first character of the stop codon
seq="TCATTCTaTTTAAAAAAatATAAAaGGGgTTTTGGGgTTTtGGGGTTTtGGGG"
list = ["z", "z", "z"] # otherwise the list will not be of 3 characters
i = 0
for letter in seq:
list.pop(0)
list.append(letter)
codon = "".join(list)
i = i + 1
if codon == "TAG" or codon == "TAA":
print i - 2 # to print the position of T
break
Do yourself a favor and don't re-invent the wheel especially when BioPython is freely available and widely used.

Categories

Resources