簡體   English   中英

我如何從一個大列表中提取最多 14 個名字,這些名字一起包含字母表中的所有字母?

[英]How do I extract a maximum of 14 names out of a big list that, together, have all the letters of the alphabet?

我是一名新程序員。 正如標題所述,這是我完成此任務的嘗試:

def alphabet_set(countrylist):
    alphabetical_list = []
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
   
    for country in countries:
        for i in country:
            if i in alphabet:
                alphabetical_list.append(country)
            if i == 26:
                break    
    return alphabetical_list

print(alphabet_set(countries))

同樣,我從中提取的這個列表很大。 我需要 14 個國家/地區名稱,這將給我字母表的所有字母。 Alphabetical_list 將是我的 14 個國家/地區列表,其中包含所有 26 個字母表中的字母。

你可以使用set()

def alphabet_set(countrylist:list[str]):
    alphabetical_list = []
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    countriescontains = []
    letters = set()
    for country in countrylist:
        if len(letters)==26 or len(alphabetical_list) == 14:break
        elif set(country.lower()).intersection(alphabet):
            alphabetical_list.append(country)
            print({x.lower() for x in country},letters.union({x.lower() for x in country}))
            letters=letters.union({x.lower() for x in country if x != ' '})
    print(sorted(list(letters)))
    
    return alphabetical_list
print(alphabet_set(countries))

這會將alphabet_set的復雜性從O(n^2)降低到O(n) ,這將是性能方面的巨大改進。

好的,這是我想出的答案:

def alphabet_set(countries):   
    alphabetical_list = []
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    for country in countries:
        for i in country:
            if i.lower() in alphabet and country not in alphabetical_list:
                alphabet = alphabet.replace(i.lower(),'')
                alphabetical_list.append(country)
            if alphabet == '':
                break    
    return alphabetical_list
print(alphabet_set(countries))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM