如何关联函数实现从排列结果中匹配并输出指定目标数字
Solution to Connect
find_key and bool_check Functions Here's how to link your two functions to capture the target number and output the required result:
Step 1: Adjust find_key to Generate String Permutations
Your current find_key returns tuples of characters (e.g., ('4','3','2','1')), but bool_check expects a string. Modify the function to join each tuple into a string:
from itertools import product def bool_check(x): # Simplified to direct comparison return x == "4321" def find_key(different_dig, quantity_dig): chars = list(different_dig) perms = [] for c in product(chars, repeat=quantity_dig): # Combine tuple elements into a single string perms.append(''.join(c)) return perms
Step 2: Iterate Through Permutations and Check for Match
Loop through the generated permutations, use bool_check to test each one, and print the result when a match is found:
# Generate all permutations all_permutations = find_key("1234", 4) # Check each candidate for candidate in all_permutations: if bool_check(candidate): print(True) print(candidate) break # Stop searching once target is found
Optional: Use itertools.permutations for Unique Orderings
If you only want permutations with no repeated digits (which fits "4321"), replace product with permutations—this is more efficient as it avoids duplicate combinations:
from itertools import permutations def find_key(different_dig, quantity_dig): perms = [] # permutations generates unique orderings without repetition for c in permutations(different_dig, quantity_dig): perms.append(''.join(c)) return perms
Running the code will output:
True 4321
内容的提问来源于stack exchange,提问作者The Vinchi
相关产品推荐
相关产品推荐

