0

What different between these pieces of code?

Hi, guys! I can't figure out why this code give the result a4b2c1a2 dna = 'aaaabbcaa' cnt = 1 x=1 dna2 = dna[x:x+1] for g in dna: if g in dna2: cnt+=1 else: print (g, end='') print (cnt, end='') cnt=1 x+=1 dna2 = dna[x:x+1] And this one doesn't dna = 'aaaabbcaa' cnt = 0 x= 0 dna2 = dna[x:x+1] for g in dna: if g in dna2: cnt+=1 else: print (g, end='') print (cnt, end='') cnt= 0 x+=1 dna2 = dna[x:x+1] The difference is 2, 3 and 11 string. For 1 code - cnt = 0, x = 0 For 2 code - cnt = 1, x = 1

12th May 2020, 5:19 PM
Zlata Zukovich
Zlata Zukovich - avatar
1 Answer
+ 1
1st code- for g in dna: if g in dna2: Your if statement is one step ahead of your 'g' in for loop. So when x is 4, your 'g' in for loop is at index 3. In this case dna2 has 'b' but dna at index 3 has 'a'. This causes the if statement to fail and your else is executed. This happens for successive cases. It will print the count of each character. 'aaaabbcaa' a4b2c1a2 ------------------------------------------------------------------ 2nd code- for g in dna: if g in dna2: Both the 'g' here match at all times. So your if statement never fails and else is always ignored. This has caused the 'cnt' to increment every time and now it just holds the number of characters in the string. print(cnt) -> you will get 9
12th May 2020, 6:25 PM
Avinesh
Avinesh - avatar