string comparison in a while loop - python

I've written a small piece of code that should detect if there are any matching characters in the same place in the 2 strings. If there is , the score in incremented by 1, if there is 2 or more consecutive matching characters , the score is incremented by 3, if there is no matching character, the score is decremented by 1.
The problem is though , when i try to run the code, it gives me a error: string index out of range.
What might be wrong ? thank you very much.
def pairwiseScore(seqA, seqB):
count = 0
score = 0
while count < len(seqA):
if seqA[count] == seqB[count]:
score = score + 1
count = count + 1
while seqA[count] == seqB[count]: # This is the line the error occurs
score = score + 3
count = count + 1
elif seqA[count] != seqB[count]:
score = score - 1
count = count + 1
return score

Do both strings have the same lenght? otherwise you should consider using something like:
while count < min(len(seqA), len(seqB)):

Also, the zip function might come in handy here to pair off the letters in each word. It is a python builtin. e.g.
def letter_score(s1, s2):
score = 0
previous_match = False
z = zip(s1, s2)
for pair in z:
if pair[0] == pair[1]:
if previous_match:
score += 3
else:
score += 1
previous_match = True
else:
score -= 1
previous_match = False
return score

Indexes are numberd 0 to n.
len(someString)
will give you n + 1.
Let's say that your string is length 10, and the indexes are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Your while loop checks the condition that count is < 10. So far so good.
Ok now let's say that count is equal to 9. Immediately within the first while loop, you increment count.
So now count = 10.
Now attempting to access someString[count] will give you an IndexError because the indices only go up to 9.

The error message says it: You're trying to access a character beyond the boundaries of your string. Consider this:
>>> s = "hello"
>>> len(s)
5
>>> s[4]
'o'
Now when (at the start of the first while loop) count is 1 below len(seqA), then you're incrementing count and then you're doing seqA[count] which will throw this exception.
Let's assume you're calling pairwisescore("a", "a"):
score = 0
count = 0
while count < len(seqA): # 0 < 1 --> OK
if seqA[count] == seqB[count]: # "a" == "a" --> OK
score = score + 1 # score = 1
count = count + 1 # count = 1
while seqA[count] == seqB[count]: # seqA[1] doesn't exist!

In the second while loop you must test that count is less than len(seqA):
while count < len(seqA) and seqA[count] == seqB[count]:
...
and, also there's possibly other bug: If the length of seqB is less than length of seqA, you'll again see runtime exception. so, you should change every occurence of count < len(seqA) with count < min(len(seqA), len(seqB)).

def pairwiseScore(seqA, seqB):
count = 0
score = 0
isOne = False
isTwoOrMore = False
while count < min(len(seqA), len(seqB)):
if seqA[count] == seqB[count]:
if isTwoOrMore:
score = score + 3
count = count + 1
else:
if isOne:
isTwoOrMore = True
score = score + 1
count = count + 1
isOne = True
elif seqA[count] != seqB[count]:
score = score - 1
count = count + 1
isOne = False
isTwoOrMore = False
return score
a = 'apple'
b = 'aplle'
print(pairwiseScore(a, b))
I think this one solve the problem, I added a "counting" bool variable. And to respond to the question, your program didn't compare the length of the second string.
while count < min(len(seqA), len(seqB)):

The problem is that you do this:
count = count + 1
Both before the inner while loop and at the end of it. But you then continue using seqA[count] before checking it against len(seqA) again - so, once it goes too high, Python will try to read past the end of seqA, and you'll get that error (when, if the condition had been checked again after incrementing, the loop would have ended).
Using a Python for loop will get around bugs like this, since Python will manage count for you:
for a,b in zip(seqA, seqB):
if a == b:
score += 1
You can implement the extra-points bit easily in this by keeping track of whether the previous character is a match, rather than trying to work out how many after this one are. A boolean variable last_matched that you keep updated would help with this.

Related

how to use while loop to determine the amount of numbers in a list that are greater the average

Hi I need to do this task in two ways: one way with for loop which I did and other with while loop but I don't secceed....The code I wrote is:
A = [5,8,9,1,2,4]
AV = sum(A) / float(len(A))
count = 0
for i in A :
if i > AV :
count = count + 1
print ("The number of elements bigger than the average is: " + str(count))
count = 0
while float in A > AV:
count += 1
print ("The number of elements bigger than the average is: " + str(count))
The problem is that you are using while float in A > AV: in your code. The while works until the condition is true. So as soon as it encounters some some number in list which is smaller than average, the loop exits. So, your code should be:
A = [5,8,9,1,2,4]
AV = sum(A) / float(len(A))
count = 0
for i in A : if i > AV :
count = count + 1
print ("The number of elements bigger than the average is: " + str(count))
count = 0
i = 0
while i < len(A):
if A[i] > AV: count += 1
i += 1
print ("The number of elements bigger than the average is: " + str(count))
i hope it helped :) and i believe you know why i added another variable i.
Your code is indeed unformatted. Generally:
for x in some_list:
... # Do stuff
is equivalent to:
i = 0
while i < len(some_list):
... # Do stuff with some_list[i]
i += 1
A = [5,8,9,1,2,4]
AV = sum(A) / float(len(A))
count = 0
for i in A:
if i > AV:
count = count + 1
print ("The number of elements bigger than the average is: " + str(count))
count = 0
i = 0
while i < len(A):
if A[i] > AV:
count += 1
i += 1
print ("The number of elements bigger than the average is: " + str(count))
You can use something like the code below. I have commented on each part, explaining the important parts. Note that your while float in A > AV is not valid in python. In your case, you should access elements of a list by indexing or using a for loop with the in keyword.
# In python, it is common to use lowercase variable names
# unless you are using global variables
a = [5, 8, 4, 1, 2, 9]
avg = sum(a)/len(a)
print(avg)
gt_avg = sum([1 for i in a if i > avg])
print(gt_avg)
# Start at index 0 and set initial number of elements > average to 0
idx = 0
count = 0
# Go through each element in the list and if
# the value is greater than the average, add 1 to the count
while idx < len(a):
if a[idx] > avg:
count += 1
idx += 1
print(count)
The code above will output the following:
4.833333333333333
3
3
Note: There are alternatives to the list comprehension that I've provided. You could also use this piece of code.
gt_avg = 0
for val in a:
if val > avg:
gt_avg += 1

In Python, how do I print only the final answer in a while loop when adding values between 1 and 20

So this is what I've got. The output is every answer leading up to the final outcome of Odd = 100 and Even = 110. I was hoping someone could maybe suggest what I could do to only print the final answers rather than the whole list of iterations.
Thanks a million x
#inputs
odd = 0
even = 0
counter = 0
# calculations for even numbers
while counter <= 20 and counter % 2 == 0:
even = even + counter
print("The sum of the EVEN numbers between 1 and 20 is", even)
counter += 1
# calculations for odd numbers
if counter <= 20 and counter % 2 != 0:
odd = odd + counter
print("The sum of the ODD numbers between 1 and 20 is", odd)
counter += 1
use the print statement after incrementing the counter, outside the while loop
#inputs
odd = 0
even = 0
counter = 0
# calculations for even numbers
while counter <= 20 and counter % 2 == 0:
even = even + counter
counter += 1
# calculations for odd numbers
if counter <= 20 and counter % 2 != 0:
odd = odd + counter
counter += 1
print("The sum of the ODD numbers between 1 and 20 is", odd)
print("The sum of the EVEN numbers between 1 and 20 is", even)
Something like this should work; note the print statement is outside the while loop and the arithmetic is being done on odd and even using the if statement to determine which is to be added. Hope this makes sense
odd = 0
even = 0
counter = 0
while counter <= 20:
if counter % 2 == 0:
even += counter
elif counter % 2 != 0:
odd += counter
counter += 1
print("Sum of odd numbers is: {}, sum of even numbers is: {}".format(odd, even))

Can't assign to literal with "for" loop

I am creating a Yahtzee program in Python. This function is meant to carry out the action that the user chooses (the user inputs a number, and it chooses the appropriate list item). I just got to the section about adding the total of one number set (the top part of a Yahtzee card with the ones, twos, etc.). I made a loop that adds one to the score for every 1 found in list dicevalues (a random list of "rolled dice" numbers; declared earlier in program).
I am getting the error on the for 1 in dicevalues: line. It says SyntaxError: cannot assign to literal. I looked up this error, but I'm not making sense of it. What I interpret here is that the program would run the code in the for block for every value 1 in dicevalues, but I'm not quite sure if you can use the for loop in that way.
def choiceAction():
if options[choice] == "Chance (score total of dice).":
global score
score += (a + b + c + d + e)
if options[choice] == "YAHTZEE!":
score += 50
if options[choice] == "Large straight":
score += 40
if options[choice] == "Small straight.":
score += 30
if options[choice] == "Four of a kind (total dice score).":
score += (a + b + c + d + e)
if options[choice] == "Three of a kind (total dice score).":
score += (a + b + c + d + e)
if options[choice] == "Full house.":
score += 25
if options[choice] == "Add all ones.":
for 1 in dicevalues: # <-- SyntaxError: can't assign to literal
score += 1
Is it possible that for some reason 1 cannot be in the for declaration?
If you don't want to use the items in dicevalues you can use a placeholder
for _ in dicevalues:
The error
When you write for x in dicevalues: you iterate over dicevalues and put each element in the variable x, so x can not be replaced with 1. This is why you get the error SyntaxError: can't assign to literal.
The solution(s)
Here are several solutions to perform what you want:
dicevalues = [2, 1, 3, 6, 4 ,1, 2, 1, 6]
# 1. Classic 'for' loop to iterate over dicevalues and check if element is equal to 1
score = 0
for i in dicevalues:
if i == 1:
score += 1
print(score) # 3
# 2. Comprehension to get only the elements equal to 1 in dicevalues, and sum them
score = 0
score += sum(i for i in dicevalues if i == 1)
print(score) # 3
# 3. The 'count()' method to count the number of elements equal to 1 in dicevalues
score = 0
score += dicevalues.count(1)
print(score) # 3

Palindrome chain length in Python coming up incorrect

I feel like this should work correctly but I get an error with the count being 1 less than it should be.
def palindrome_chain_length(n):
count = 0
while str(n) != str(n)[::-1] :
n = n+n
count += 1
else:
return count
If you just get count 1 less than you want, start with count = 1.
And it seems to me that it should be:
n += int(str(n)[::-1])
instead of:
n = n + n
(see comment #alfasin).

How do I exit this while loop?

I’m having trouble with exiting the following while loop. This is a simple program that prints hello if random value is greater than 5. The program runs fine once but when I try to run it again it goes into an infinite loop.
from random import *
seed()
a = randint(0,10)
b = randint(0,10)
c = randint(0,10)
count = 0
while True:
if a > 5 :
print ("aHello")
count = count + 1
else :
a = randint(0,10)
if b > 5 :
print ("bHello")
count = count + 1
else :
b = randint(0,10)
if c > 5 :
print ("cHello")
count = count + 1
else :
c = randint(0,10)
if count == 20 :
count = 0
break
count = 0
Your while loop might increment the variable count by 0, 1, 2 or 3. This might result in count going from a value below 20 to a value over 20.
For example, if count's value is 18 and the following happens:
a > 5, count += 1
b > 5, count += 1
c > 5, count += 1
After these operations, count's value would be 18 + 3 = 21, which is not 20. Therefore, the condition value == 20 will never be met.
To fix the error, you can either replace the line
if count == 20
with
if count >= 20
or just change your program logic inside the while loop.
Does the following code help?
while True:
if a > 5 :
print ("aHello")
count = count + 1
if count == 20 :
break
else :
a = randint(0,10)
if b > 5 :
print ("bHello")
count = count + 1
if count == 20 :
break
else :
b = randint(0,10)
if c > 5 :
print ("cHello")
count = count + 1
if count == 20 :
break
else :
c = randint(0,10)
You have to check the value of count after incrementing it every time.
The "break" condition might fail if two or more values of the variables a, b, and c are greater than 5. In that case the count will be incremented more than once and count will end up > 20, and the loop can never terminate. You should change:
if count == 20 :
to
if count >= 20:
At the end of iteration, count might be greater than 20 due to multiple increments. So I would update the last if statement to:
if count >= 20:
to feel safe.
If your goal is to stop counting when count is >= 20, then you should use that condition for your while loop and you won't need to break at all, as you only break at the end of the loop anyways.
The new while statement would look like
while count < 20:
# increment count
and then outside of the while loop you can reset count to 0 if you want to use it again for something else.
since you increment count 2 or 3 times in one iteration, it may skip past your count == 20 check
Here's one way to get exactly 20 lines.
from random import seed, randint
seed()
a = randint(0,10)
b = randint(0,10)
c = randint(0,10)
count = iter(range(20))
while True:
try:
if a > 5:
next(count)
print ("aHello")
else:
a = randint(0,10)
if b > 5:
next(count)
print ("bHello")
else:
b = randint(0,10)
if c > 5:
next(count)
print ("cHello")
else:
c = randint(0,10)
except StopIteration:
break
Note there is still a lot of repetition in this code. Storing your a,b,c variables in a list instead of as separate variables would allow the code to be simplified further

Categories