简体   繁体   中英

How do I compare sequential characters in two strings with loops?

I have two strings 'hello' and 'leetcode' inside an array words.

I am struggling to compare each of the characters in the string, one by one - so for example, I want to compare

  • 'h' with 'l'
  • 'e' with 'e'
  • 'l' with 'e'
  • and so on.

I have written the following for loops below, but they don't seem to do the job, as it prints the wrong result.

words = ["hello","leetcode"]

for j in range(len(words)):
    for k in range(len(words[j])):
        if words[j][k] < words[j + 1][k]:

Any idea how to amend the above, or suggest another way to do this?

Fix

You need one for loop that generates indices for both words

words = ["hello", "leetcode"]
for j in range(min(len(words[0]), len(words[1]))):
    if words[0][j] < words[1][j]:
        print("LO")
    elif words[0][j] > words[1][j]:
        print("UP")
    elif words[0][j] == words[1][j]:
        print("EQ")

Improve

You can iterate on pair using zip , that directly yields chars of each words

words = ["hello", "leetcode"]
for c1, c2 in zip(*words):
    if c1 < c2:
        print("LO")
    elif c1 > c2:
        print("UP")
    elif c1 == c2:
        print("EQ")

I would let Python split out the characters for me:

for a, b in zip(*words):
    if a==b:
        print(f"{a}=={b}")
    else:
        print(f"{a}!={b}")

h!=l
e==e
l!=e
l!=t
o!=c

If there are more than two words, the technique is the same:

>>> words = ["hello","leetcode","hellooo"]
>>> list(zip(words))
>>> [('h', 'l', 'h'), ('e', 'e', 'e'), ('l', 'e', 'l'), ('l', 't', 'l'), ('o', 'c', 'o')]

As you can see, this will work for any number of words. But it is unclear what you would then mean by match . If you are looking for a match at the same position in all the words, you could do it this way:

words = ["hello","leetcode","hellooo"]
for index, mytuple in enumerate(zip(*words)):
    if len(set(mytuple)) == 1:
        print(f"Match on {mytuple[0]} at position {index}")

    
Match on e at position 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM