Python string_scramble函数实现需求:提取两字符串共有小写无重复字符
Got it, let's tackle this problem step by step to build the string_scramble function that meets your requirements!
Solution for the
string_scramble Function First, let's recap what we need this function to do clearly:
- Accept two input strings
- Find all characters that appear in both strings
- Convert all matching characters to lowercase
- Return them as a list with no duplicate entries
Final Working Implementation
Here's a clean, efficient version of the function that checks all the boxes:
def string_scramble(string_one, string_two): # Convert both inputs to lowercase to handle case insensitivity lower_str1 = string_one.lower() lower_str2 = string_two.lower() # Use set intersection to find shared characters (sets auto-remove duplicates) common_chars = set(lower_str1) & set(lower_str2) # Convert the set to a sorted list (matches the ordered example output) # Skip sorted() if you don't need alphabetical order return sorted(list(common_chars))
Test It With Your Example
If we run the sample input:
print(string_scramble('GraSS', 'grilled cheese'))
We get the expected result:
['g', 'r', 's']
Breakdown of Key Choices
- Lowercasing first: Using
.lower()ensures characters like 'G' and 'g' are treated as identical, which is essential for case-insensitive matching. - Set intersection: Sets are perfect here because they automatically eliminate duplicates, and the
&operator gives us an easy way to find common elements between the two strings. - Sorted output: The
sorted()function aligns the result with the sample's ordered list. If the problem didn't specify order, you could just returnlist(common_chars)instead.
Fixing the Original Snippet's Issues
The reference code you shared had two main flaws:
- It hardcoded input strings instead of using the function's parameters
- It printed characters instead of returning them as a list
The implementation above fixes both of these while adding the necessary case handling.
内容的提问来源于stack exchange,提问作者Colby Fugate
相关产品推荐
相关产品推荐

