简体   繁体   中英

How to find and remove pairs of strings with a given total letters count from a list

I've got a list, with each element being a word. In this list, I want to find pairs of words whose added letter count is 20, print them and remove them from the list.

When there aren't any more words in the list matching the criteria, the program should stop.

Here is the code I came up with, but as you will see, it has a lot of errors, with indexes going out of range and I can't figure out how to fix it, nor how to make the program to stop when there aren't any more words matching the criteria.

f = open('input.txt', 'r')

words = f.read().split()

c = 0
for word in words:
    c += 1

for i in range(c):
    letterCount = 0
    for letter in words[i]:
        letterCount += 1
    for j in range(i+1, c):
        letterCount2 = 0
        for letter in words[j]:
            letterCount2 += 1
        if letterCount + letterCount2 == 20:
            print(words[i], words[j])
            words.pop(i)
            words.pop(j)

Here is my suggestion. You must use len(list) or len(word) in order to get the length of a list of a word, it will make your life much easier. In the following code, we create a function that checks for such pairs of words and removes them. We run this function until there is no other pair and the loop stops:

f = open('input.txt', 'r')

words = f.read().split()

def find_pair(l):
    for i in range(len(l)-1):
        for k in range(i, len(l)):
            if len(l[i]+l[k])==20:
                return (i, k)
    return (0,0)

while True:
    x=find_pair(words)
    if x!=(0,0):
        words.pop(x[1])
        words.pop(x[0])
    else:
        break

print(words)

Use break; statement to exit from loop once you condition is satisfied

A simple solution without altering your word list:

pairs=[]
for w1 in words:
    for w2 in words:
        if w1 in pairs or w2 in pairs:
            continue
        if w1 != w2 and len(w1) + len(w2) == 20:
            print(w1, w2)
            pairs.append(w1)
            pairs.append(w2)
            break

print(pairs)
print(list(filter(lambda x: x not in pairs, words)))

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