如何生成单词中低位和高位字符的所有组合? e.g:
let sleepHoursSurveyActivity = OCKCarePlanActivity.assessment(
withIdentifier: ActivityIdentifier.sleepHours.rawValue,
groupIdentifier: nil,
title: "Sleep Hours",
text: nil,
tintColor: .darkGreen,
resultResettable: true,
schedule: dailyScheduleRepeating(occurencesPerDay: 1),
userInfo: ["ORKTask" : AssessmentTaskFactory.sleepHoursSurveyAssessmentTask()])
static func sleepHoursSurveyAssessmentTask() -> ORKTask {
var steps = [ORKQuestionStep]()
let question = NSLocalizedString("How many hours did you sleep?", comment: "")
let textChoices = [
ORKTextChoice(text: "1-3", value: "1-3" as NSString),
ORKTextChoice(text: "4-5", value: "4-5" as NSString),
ORKTextChoice(text: "6-7", value: "6-7" as NSString),
ORKTextChoice(text: "8", value: "8" as NSString),
ORKTextChoice(text: "more than 8", value: "more than 8" as NSString)
]
let questAnswerFormat: ORKTextChoiceAnswerFormat = ORKAnswerFormat.choiceAnswerFormat(with: .singleChoice, textChoices: textChoices)
let sleepHoursSurvaySteps = ORKQuestionStep(identifier: "sleepHours", title: question, answer: questAnswerFormat)
sleepHoursSurvaySteps.isOptional = false
steps += [sleepHoursSurvaySteps]
return ORKOrderedTask(identifier: "sleepHoursSurveyTask", steps: [sleepHoursSurvaySteps])
}
→'abc'
['abc', 'ABC', 'Abc', 'ABc', 'aBC', 'aBc', 'abC', 'Abc']
→'ab'
答案 0 :(得分:6)
您可以通过zipping大写和小写字母以及他们的笛卡尔product来实现此目的:
import itertools
chars = "abc"
results = list(map(''.join, itertools.product(*zip(chars.upper(), chars.lower()))))
print(results)
>>>['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']
为了想象这是如何运作的,zip
正在创造我们的3轴'对我们来说,每个都有2个点,大写和小写字母:[('A', 'a'), ('B', 'b'), ('C', 'c')]
product
取这些轴的笛卡尔积,即与其创建的单位立方体的角相对应的8个可能的离散点:
答案 1 :(得分:2)
使用递归
def foo(word):
if len(word) == 1:
return [word.lower(), word.upper()]
return [f"{j}{i}" for j in foo(word[0]) for i in foo(word[1:])]
s = "abc"
print(foo(s))
['abc', 'abC', 'aBc', 'aBC', 'Abc', 'AbC', 'ABc', 'ABC']