[英]Writing a program that takes a string as an argument and returns a new string in which all of the letters of the word are in random order
[英]Write a function that takes a string parameter and returns a new string with all the letters of the alphabet that are not in the argument string
編寫一個名為missing_letters的函數,它接受一個字符串參數並返回一個新字符串,其中包含所有不在參數字符串中的字母表字母。 返回字符串中的字母應按字母順序排列。
它還應該使用全局變量字母表。 它應該直接使用這個全局變量,而不是通過參數或本地副本。 它應該遍歷字母表中的字母以確定輸入參數中缺少哪些字母。 函數missing_letters應該將缺失的字母列表組合成一個字符串並返回該字符串。
對列表test_miss 中的字符串編寫一個循環,並使用每個字符串調用missing_letters 。 為每個字符串打印一行,列出缺失的字母。 例如,對於字符串“aaa”,輸出應如下所示。
aaa 缺少字母 bcdefghijklmnopqrstuvwxyz
我盡力解決這個問題。 該程序正在運行,但沒有提供所需的輸出。
test_miss = ["b","zzz"]
def missing_letters(s):
missingAlphabets = ""
global alphabet
for c in s:
i=0
while i < len(alphabet):
if alphabet[i] not in c:
missingAlphabets += alphabet[i]
i += 1
sortedmissingAlphabetslists = sorted(missingAlphabets)
sortedmissingAlphabets = ''.join(sortedmissingAlphabetslists)
return sortedmissingAlphabets
for i in test_miss:
print('{} is missing letters {}'.format(i,missing_letters(i)))
該程序為具有單個字符的任何字符串提供適當的輸出,例如 - "b"
即: b 缺少字母 acdefghijklmnopqrstuvwxyz
但是對於具有多個字符的字符串,例如:“zzz”,輸出為:
zzz 缺少字母 aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyy
但我想要: zzz 缺少字母 abcdefghijklmnopqrstuvwxy
set
類型已經為您處理了大部分工作。
import string
def missing_letters(s):
return ''.join(sorted(set(string.lowercase) - set(s)))
如果x
和y
是一組,則x - y
是集項目中存在的x
,但不y
。 如果你有一組缺失的字符,你可以對它們進行排序並將排序的元素重新連接成一個字符串。
>>> set('abc') - set('a')
set(['c', 'b'])
>>> sorted(_)
['b', 'c']
>>> ''.join(_)
'bc'
與您已經定義的精神保持一致。 問題是您多次測試missing_letters
函數中的每個字母。 所以你只想檢查字符(來自字母表)是否在字符串中。 所以去掉循環參數中字母的額外for loop
- 就像這樣
alphabet = 'abcdefghijklmnopqrstuvwxyz'
test_miss = ["b","zzz"]
def missing_letters(s):
missingAlphabets = ""
global alphabet
i = 0
while i < len(alphabet):
if alphabet[i] not in s:
missingAlphabets += alphabet[i]
i += 1
sortedmissingAlphabetslists = sorted(missingAlphabets)
sortedmissingAlphabets = ''.join(sortedmissingAlphabetslists)
return sortedmissingAlphabets
for i in test_miss:
print('{} is missing letters {}'.format(i,missing_letters(i)))
b is missing letters acdefghijklmnopqrstuvwxyz
zzz is missing letters abcdefghijklmnopqrstuvwxy
def has_duplicates(t):
t= histogram(t)
for i in t:
a=(t[i])
if a > 1:
return True
else:
return False
for i in test_dups:
f = has_duplicates(i)
if f == True:
print(i +' '+ 'has duplicates')
else:
print(i +' '+ 'has no duplicates')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.