我是个新程序员。正如标题所述,这是我试图完成的:
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个字母。
发布于 2022-01-26 16:08:04
你可以用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)的复杂性,这将大大提高性能。
发布于 2022-03-21 15:28:51
好的,这就是我想出的答案:
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))https://stackoverflow.com/questions/70866353
复制相似问题