Do both strings have the same lenght? otherwise you should consider using something like:
while count < min(len(seqA), len(seqB)):
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
I'm struggling with what I need to use to get this to equal 4. The outcome down here gets me 6. I've tried a bunch of different ways to get to the problem and I'm just stuck. I'm pretty sure I'm close to the answer. Help is much appreciated user_score = 0 simon_pattern = 'RRGBRYYBGY' user_pattern = 'RRGBBRYBGY'
for c in user_pattern:
for d in simon_pattern:
if c == d:
user_score += 1
if c != d:
break
print('User score:', user_score)i previously had another break statement in the first if statement that got me 3
Python string comparison whilst in loop - Stack Overflow
string - While-loop within a while-loop python - Stack Overflow
loops - Python: how to compare input() string to another string? - Stack Overflow
Python while loop with string - Stack Overflow
OK, let's take this one step at a time. First, I would read file B into a structure that's well suited for fast lookup since we're going to be doing that quite often:
chars = {}
with open("B") as lookupfile:
for number,line in enumerate(lookupfile):
chars[line.strip()] = number
Now we have a dictionary chars that contains letters as keys and their row number as values:
>>> chars
{'t': 1, 'a': 4, 'i': 3, 'h': 0, 's': 2}
Now we can iterate over the first file. The standard Python iterator for files consumes one line per iteration, not one character, so it's probably best to simply read the entire file into a string and then iterate over that (because for strings, iteration is character-by-character):
with open("A") as textfile:
text = textfile.read()
Now we iterate over the string and print matching values:
for char in text:
if char in chars:
print("Character {0} found in row {1}".format(char, chars[char]))
If you don't like accessing the dictionary twice, you can also use
for char in text:
found = chars.get(char): # returns None if char isn't a key in chars
if found:
print("Character {0} found in row {1}".format(char, found))
or, using exceptions:
for char in text:
try:
print("Character {0} found in row {1}".format(char, chars[char]))
except KeyError:
pass
import os
fA = open('C:\\Desktop\\fileA.txt', 'r')
fB = open('C:\\Desktop\\fileB.txt', 'r')
fileb_content = []
for line in fB:
fileb_content.append(fB.read().split('\n'))
rA = fA.readline().split('\n')[0]
for c in list(rA):
if(c.strip()):
if(c.lower() in fileb_content[0]):
print(fileb_content[0].index(c.lower()))
here i test that character is not empty.
You never reset x inside the outer loop. As a result it'll always be equal or greater to len(stringscompare) after the first iteration of the outer loop.
Set it to 0 in the outer loop:
v = 0
while v < len(strings) and stop == False:
x = 0
while x < len(stringscompare) and stop == False:
Other observations:
Don't use stop == False where not stop will do.
You could just use a for loop, then break out twice:
for s in strings:
for sc in stringscompare:
if re.search(s, sc):
same.append(dict)
break
else:
continue
# only reached if the inner loop broke out
break
or use any() with a generator expression to find the first match:
if any(re.search(s, sc) for s in strings for sc in stringscompare):
same.append(dict)
you use twice the same variable stop I think you should set the stop to false after the loop:
strings = <list of 3 word strings> [...,...,...]
stringscompare = <list of 3 word strings to compare>
v=0, x=0
while v < len(strings) and stop == False:
while x < len(stringscompare) and stop == False:
if re.search(strings[v], stringscompare[x]):
same.append(dict)
stop = True
x += 1
stop = False
v +=1
This statement
x != 'Y' or x != 'N'
is always True, because everything in the world is not "Y" or not "N".
Change it to:
x != 'Y' and x != 'N'
Change the or to and, as you want to check it is not equal to either of these fields. If you want to use or you will have to change the code to
def main ():
user_input = input("print data? (Y/N) ")
while (true):
if (user_input.lower() == 'y' or user_input.lower() == 'n'):
break
user_input = input("error: wrong input. Please put Y or N only ")
if user_input.lower() == 'y':
read_serial()
side note: x is a poor variable name, call it something more appropriate.
You should always change case to lower when comparing strings when case doesn't matter. In this case, case does not matter so use lower()
def main ():
user_input = input("print data? (Y/N) ")
while (user_input.lower() != 'y' and user_input.lower() != 'n'):
user_input = input("error: wrong input. Please put Y or N only ")
if user_input.lower() == 'y':
read_serial()
Your while loop compares each character with the last, a, stopping when it finds a character that isn't equal or higher than a. Your code stops at the space because the latter's position in the ASCII table is 32:
>>> ' ' < 'a'
True
>>> ord(' ')
32
>>> ord('a')
97
You probably wanted to create a loop comparing num_index to num_length instead:
while num_index <= num_length:
If you wanted to loop through all characters in a string, just use a for loop:
for character in myString:
print(character)
You can use the enumerate() function to add an index:
for index, character in enumerate(myString):
print(index, character, sep=': ')
print(myString[:index])
because myString[num_index] value is space
check this..
>>> " ">="a"
False
Try and instead of or. Alternatively, you might find the following more readable:
while direction not in ('encode', 'encrypt', 'decrypt', 'decode'):
Try this:
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
method = ["encode", "encrypt", "decrypt", "decode"]
while direction not in method:
print("Please put in a valid direction!\n")
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
You are resetting count to 0 each iteration of the loop. The loop therefore compares the first elements over and over and over and over again. To fix that problem, just move the count = 0 assignment outside of the loop, like this:
# ...
b = input('Please enter the second string to compare: ')
count = 0
while True:
if a[count] != b[count]:
# ...
When you have done that, you will realise that you have a second problem – the program crashes when you have reached the end of one of the strings. You might want to handle this case too.
You can use zip here:
def compare(s1, s2):
if len(s1) != len(s2):
return False
else:
for c1, c2 in zip(s1, s2):
if c1 != c2:
return False
else:
return True
>>> compare('foo', 'foo')
True
>>> compare('foo', 'fof')
False
>>> compare('foo', 'fooo')
False
In your code you're resetting the value of count to 0 in each iteration:
a = input('Please enter the first string to compare:')
b = input('Please enter the second string to compare: ')
if len(a) != len(b): # match the length first
print ('Strings don\'t match')
else:
count = 0 #declare it outside of while loop
while count < len(a): #loop until count < length of strings
if a[count] != b[count]:
print ('Strings don\'t match! ')
break
count = count + 1
else:
print ("string match")
If you have a condition of number != '1' or number != '2', one of those conditions will always be true, so it'll never break out of the loop. Try while number not in ('1', '2', '3') instead.
As mentioned, you used or instead of and. But the in operator may be a better choice:
number=input("Would you like to eat 1. cake 2. chocolate 3. sweets: ")
while number not in ("1", "2","3"):
number=input("Please input a choice [1,2,3]")
You don't need nested loop in this case, thanks to the in operator:
for c in local:
if c in valChar:
performvalidaction(c)
else:
denoteasinvalid(c)
What identifier to use (c, ch, or anything else) is pretty indifferent, I tend to use single-character identifiers for loop variables, but there's no rule saying that you must.
If you did have to use two nested loops, you'd just use different loop variables for the two loops.
In fact you don't even need one loop here (you could instead work e.g with Python's sets, for example) -- much less two -- but I guess using one loop is OK if it's clearer for you.
ch is a variable, you can replace it with any valid identifier:
for local_ch in local:
for valChar_ch in valChar:
if(local_ch == valChar_ch): <----No problem
For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.
Not always. NaN is a counterexample. But usually, identity (is) implies equality (==). The converse is not true: Two distinct objects can have the same value.
Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values?
You use == when comparing values and is when comparing identities.
When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with is, but don't rely on it.
For boolean values, you shouldn't be doing comparisons at all. Instead of:
if x == True:
# do something
write:
if x:
# do something
For comparing against None, is None is preferred over == None.
I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id.
Yes, that's exactly what it's for.
I would like to show a little example on how is and == are involved in immutable types. Try that:
a = 19998989890
b = 19998989889 +1
>>> a is b
False
>>> a == b
True
is compares two objects in memory, == compares their values. For example, you can see that small integers are cached by Python:
c = 1
b = 1
>>> b is c
True
You should use == when comparing values and is when comparing identities. (Also, from an English point of view, "equals" is different from "is".)