代码功能说明
-
条件类:
Condition
类用于定义每个条件的范围,并提供一个方法is_satisfied
来检查输入值是否满足该条件。 -
算法选择器类:
AlgorithmSelector
类负责应用条件并记录不满足的条件。它提供方法apply_condition
用于更新可用算法,get_selected_algorithm
用于返回选中的算法,以及log_failed_conditions
方法用于输出失败的条件信息。 -
规则定义:
rules
字典中定义了每个条件的范围以及对应的适用算法。通过这种方式,您可以轻松扩展或修改条件和算法的对应关系。 -
选择算法:
select_algorithm
函数根据输入值和启用的开关选择合适的算法。它将输入值传递给AlgorithmSelector
进行处理,并最终返回符合条件的算法编号。
可扩展性
- 添加新条件:要添加新条件,只需在
rules
字典中添加新的条件范围和适用算法。 - 修改条件:可以直接修改
rules
中的条件范围或对应的算法集合。 - 启用/禁用条件:可以通过开关参数灵活地启用或禁用某些条件。
class Condition:
def __init__(self, min_value, max_value, name):
self.min_value = min_value
self.max_value = max_value
self.name = name
def is_satisfied(self, input_value):
return self.min_value <= input_value < self.max_value
class AlgorithmSelector:
def __init__(self):
self.algorithms = set(range(8)) # 假设有8个算法
self.failed_conditions = []
def apply_condition(self, condition, input_value, applicable_algorithms):
if condition.is_satisfied(input_value):
self.algorithms.intersection_update(applicable_algorithms)
else:
self.failed_conditions.append(f"Condition '{condition.name}' failed. "
f"Input value: {input_value}, "
f"expected range: [{condition.min_value}, {condition.max_value})")
def get_selected_algorithm(self):
return next(iter(self.algorithms), -1) # 返回第一个符合条件的算法,若无则返回-1
def log_failed_conditions(self):
if not self.failed_conditions:
print("All conditions passed.")
else:
print("Failed conditions:")
for condition in self.failed_conditions:
print(f" - {condition}")
# 定义每个条件的范围和适用的算法
rules = {
"ISO": [
(Condition(0, 200, "ISO 0-200"), {0}),
(Condition(200, 800, "ISO 200-800"), {1, 2}),
(Condition(800, float('inf'), "ISO 800+"), {2}),
],
"Facelv": [
(Condition(0, 2, "Facelv 0-2"), {0, 3}),
(Condition(2, 5, "Facelv 2-5"), {3}),
],
"Zoom": [
(Condition(0, 2.0, "Zoom 0-2.0"), {1}),
(Condition(2.0, 3.0, "Zoom 2.0-3.0"), {4}),
(Condition(3.0, float('inf'), "Zoom 3.0+"), {4, 5}),
],
"Face Count": [
(Condition(0, 2, "Face Count 0-2"), {2}),
(Condition(3, 5, "Face Count 3-5"), {2, 4}),
(Condition(6, float('inf'), "Face Count 6+"), {4, 6}),
],
"Face Size": [
(Condition(0, 50, "Face Size 0-50"), {3}),
(Condition(50, 100, "Face Size 50-100"), {5}),
(Condition(100, float('inf'), "Face Size 100+"), {3, 7}),
],
}
def select_algorithm(iso, facelv, zoom, face_count, face_size,
use_iso=True, use_facelv=True, use_zoom=True, use_face_count=True, use_face_size=False):
selector = AlgorithmSelector()
# 输入值列表和条件启用的开关
inputs = [iso, facelv, zoom, face_count, face_size]
switches = [use_iso, use_facelv, use_zoom, use_face_count, use_face_size]
# 遍历每个条件
for i, (condition_name, conditions) in enumerate(rules.items()):
if switches[i]: # 如果该条件启用
for condition, applicable_algorithms in conditions:
selector.apply_condition(condition, inputs[i], applicable_algorithms)
# 输出不满足的条件
selector.log_failed_conditions()
# 返回选择的算法
return selector.get_selected_algorithm()
# 示例输入
iso = 300
facelv = 3
zoom = 2.5
face_count = 4
face_size = 75
# 启用/禁用各条件的开关
selected_algorithm = select_algorithm(iso, facelv, zoom, face_count, face_size,
use_iso=True,
use_facelv=True,
use_zoom=True,
use_face_count=True,
use_face_size=False)
if selected_algorithm != -1:
print(f"根据条件,选择的算法是: {selected_algorithm}")
else:
print("未找到符合条件的算法。")
C++实现:
#include <iostream>
#include <vector>
#include <set>
#include <limits>
#include <string>
class Condition {
public:
Condition(double min_value, double max_value, const std::string& name)
: min_value(min_value), max_value(max_value), name(name) {}
bool isSatisfied(double input_value) const {
return min_value <= input_value && input_value < max_value;
}
const std::string& getName() const {
return name;
}
private:
double min_value;
double max_value;
std::string name;
};
class AlgorithmSelector {
public:
AlgorithmSelector() : algorithms({0, 1, 2, 3, 4, 5, 6, 7}) {}
void applyCondition(const Condition& condition, double input_value, const std::set<int>& applicable_algorithms) {
if (condition.isSatisfied(input_value)) {
intersectAlgorithms(applicable_algorithms);
} else {
failed_conditions.push_back("Condition '" + condition.getName() + "' failed. "
"Input value: " + std::to_string(input_value) +
", expected range: [" + std::to_string(condition.getMin()) + ", " + std::to_string(condition.getMax()) + ")");
}
}
int getSelectedAlgorithm() const {
return algorithms.empty() ? -1 : *algorithms.begin(); // 返回第一个符合条件的算法,若无则返回-1
}
void logFailedConditions() const {
if (failed_conditions.empty()) {
std::cout << "All conditions passed." << std::endl;
} else {
std::cout << "Failed conditions:" << std::endl;
for (const auto& condition : failed_conditions) {
std::cout << " - " << condition << std::endl;
}
}
}
private:
std::set<int> algorithms;
std::vector<std::string> failed_conditions;
void intersectAlgorithms(const std::set<int>& applicable_algorithms) {
std::set<int> intersection;
for (const auto& algo : algorithms) {
if (applicable_algorithms.count(algo) > 0) {
intersection.insert(algo);
}
}
algorithms = intersection; // 更新可用算法
}
};
// 定义每个条件的范围和适用的算法
const std::vector<std::pair<Condition, std::set<int>>> rules[] = {
{
{0, 200, "ISO 0-200"}, {0}
},
{
{200, 800, "ISO 200-800"}, {1, 2}
},
{
{800, std::numeric_limits<double>::infinity(), "ISO 800+"}, {2}
},
{
{0, 2, "Facelv 0-2"}, {0, 3}
},
{
{2, 5, "Facelv 2-5"}, {3}
},
{
{0, 2.0, "Zoom 0-2.0"}, {1}
},
{
{2.0, 3.0, "Zoom 2.0-3.0"}, {4}
},
{
{3.0, std::numeric_limits<double>::infinity(), "Zoom 3.0+"}, {4, 5}
},
{
{0, 2, "Face Count 0-2"}, {2}
},
{
{3, 5, "Face Count 3-5"}, {2, 4}
},
{
{6, std::numeric_limits<double>::infinity(), "Face Count 6+"}, {4, 6}
},
{
{0, 50, "Face Size 0-50"}, {3}
},
{
{50, 100, "Face Size 50-100"}, {5}
},
{
{100, std::numeric_limits<double>::infinity(), "Face Size 100+"}, {3, 7}
}
};
int selectAlgorithm(double iso, double facelv, double zoom, double face_count, double face_size,
bool use_iso = true, bool use_facelv = true, bool use_zoom = true, bool use_face_count = true, bool use_face_size = true) {
AlgorithmSelector selector;
// 输入值和启用的开关
std::vector<double> inputs = {iso, facelv, zoom, face_count, face_size};
std::vector<bool> switches = {use_iso, use_facelv, use_zoom, use_face_count, use_face_size};
// 遍历每个条件
for (size_t i = 0; i < switches.size(); ++i) {
if (switches[i]) { // 如果该条件启用
for (const auto& rule : rules[i]) {
selector.applyCondition(rule.first, inputs[i], rule.second);
}
}
}
// 输出不满足的条件
selector.logFailedConditions();
// 返回选择的算法
return selector.getSelectedAlgorithm();
}
int main() {
// 示例输入
double iso = 300;
double facelv = 3;
double zoom = 2.5;
double face_count = 4;
double face_size = 75;
// 启用/禁用各条件的开关
int selected_algorithm = selectAlgorithm(iso, facelv, zoom, face_count, face_size,
true, true, true, true, false);
if (selected_algorithm != -1) {
std::cout << "根据条件,选择的算法是: " << selected_algorithm << std::endl;
} else {
std::cout << "未找到符合条件的算法。" << std::endl;
}
return 0;
}
比较有意思的实现:
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <iterator>
// 定义规则结构
struct Rule {
std::vector<std::pair<double, double>> ranges; // 条件范围
std::vector<std::set<int>> actions; // 对应算法的集合
};
// 定义规则表,适应同一条件多个范围对应多个算法的情况
std::vector<Rule> rules = {
{ {{0, 200}, {200, 800}, {800, 1e9}}, {{0}, {1, 2}, {2}} }, // iso规则
{ {{0, 2}, {2, 5}}, {{0, 3}, {3}} }, // facelv规则
{ {{0, 2.0}, {2.0, 3.0}, {3.0, 1e9}}, {{1}, {4}, {4, 5}} }, // zoom规则
{ {{0, 2}, {3, 5}, {6, 1e9}}, {{2}, {2, 4}, {4, 6}} }, // face_count规则
{ {{0, 50}, {50, 100}, {100, 1e9}}, {{3}, {5}, {3, 7}} } // face_size规则
};
// 根据输入条件和开关选择最优算法
int select_algorithm(double iso, double facelv, double zoom, double face_count, double face_size,
bool use_iso, bool use_facelv, bool use_zoom, bool use_face_count, bool use_face_size) {
std::set<int> selected_actions = {0, 1, 2, 3, 4, 5, 6, 7}; // 初始假设有8种算法
// 输入条件值
std::vector<double> inputs = {iso, facelv, zoom, face_count, face_size};
// 各条件是否启用的开关
std::vector<bool> switches = {use_iso, use_facelv, use_zoom, use_face_count, use_face_size};
// 遍历每个条件
for (int i = 0; i < rules.size(); ++i) {
if (!switches[i]) continue; // 如果该条件未启用,跳过
const Rule& rule = rules[i];
std::set<int> current_matching_actions; // 用于存储该条件下匹配的算法
// 遍历每个范围,找到满足当前条件的所有算法集合
for (int j = 0; j < rule.ranges.size(); ++j) {
if (inputs[i] >= rule.ranges[j].first && inputs[i] < rule.ranges[j].second) {
current_matching_actions.insert(rule.actions[j].begin(), rule.actions[j].end());
}
}
// 如果当前条件有匹配的算法,取交集
if (!current_matching_actions.empty()) {
std::set<int> intersection;
std::set_intersection(selected_actions.begin(), selected_actions.end(),
current_matching_actions.begin(), current_matching_actions.end(),
std::inserter(intersection, intersection.begin()));
selected_actions = intersection;
}
}
// 返回第一个符合条件的算法
return selected_actions.empty() ? -1 : *selected_actions.begin();
}
int main() {
// 示例输入
double iso = 300;
double facelv = 3;
double zoom = 2.5;
double face_count = 4;
double face_size = 75;
// 启用/禁用各条件的开关
bool use_iso = true;
bool use_facelv = true;
bool use_zoom = true;
bool use_face_count = true;
bool use_face_size = false; // 例如不使用face_size条件
// 调用选择函数
int selected_algorithm = select_algorithm(iso, facelv, zoom, face_count, face_size,
use_iso, use_facelv, use_zoom, use_face_count, use_face_size);
if (selected_algorithm != -1) {
std::cout << "根据条件,选择的算法是: " << selected_algorithm << std::endl;
} else {
std::cout << "未找到符合条件的算法。" << std::endl;
}
return 0;
}