2013-02-06 46 views
1

我試圖檢查用戶輸入的字符串是否包含在其他字符串的列表中以及這些字符串的任何排列,用「*」分隔。如何檢查一個字符串是否是其他字符串與python中的每個字符串之間插入的字符的串聯

換句話說,這裏的代碼,我到目前爲止:

user_string=raw_input("Please supply a string") 


viable_entries=['this', 'that', 'something else'] 

if user_string in viable_entries: 
    print "here I'd move on with my script" 

我還想要打印「在這裏我會繼續前進與我的劇本」如果user_string =「別的東西*本」或「this * that」等。

有沒有一種簡單的pythonic方式來做到這一點?

回答

5

您可以分割的輸入,並使用set.issubset

if set(user_string.split('*')).issubset(viable_entries): 
    ... 

請注意,這讓即使是重複的條目True"this*this")。如果要防止用戶反覆提供的條目可以使用len(set)

entries = user_string.split('*') 
if set(entries).issubset(viable_entries) and len(set(entries)) == len(entries): 
    ... 
1

ecatmur的解決方案是更好的,但「蠻力」的方法是產生了動力組viable_entries的時間並基於這一點。從itertools頁面改編:

def powerset(iterable): 
    "powerset([1,2,3]) -->() (1,) (2,) (3,) (1,2) (1,3) (2,3) (2,1) (3,1) (3,2) (1,2,3)..." 
    s = list(iterable) 
    return chain.from_iterable(permutations(s, r) for r in range(len(s)+1)) 

之後,"*".join(X) for X in powerset(viable_entries)會給你你的列表來匹配。

+0

我真的很喜歡powerset的方法,但我從來沒有使用過chain.from_iterable並且不斷收到這個錯誤:「NameError:全局名稱'鏈'未定義」。我試過「導入itertools」,仍然沒有骰子。有什麼建議? – Atticus29

+1

@ Atticus29:如果您只導入itertools,則必須限定各種名稱,因此請使用'itertools.chain.from_iterable'和'itertools.permutations' – jkerian

相關問題