2021-04-07

该程序实现了对化学方程式的解析,将方程式左侧和右侧的化学物质分离,并计算各元素的系数。通过输入多个方程式,检查左右两侧元素是否平衡,从而判断方程式是否正确。该算法适用于化学方程式的自动化处理和验证。

201912-3 化学方程式

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <map>
#include <stack>
#include <string>
using namespace std;

void analyse(string s, vector<string>& left, vector<string>& right) {
	int l = s.length();
	int start = 0, end = 0, flag = 0;
	while (end <= l) {
		if (s[end] == '+') {
			if (flag == 0) {
				left.push_back(s.substr(start, end - start));
				start = end + 1;
			}
			else if (flag == 1) {
				right.push_back(s.substr(start, end - start));
				start = end + 1;
			}
		}
		else if (s[end] == '=') {
			left.push_back(s.substr(start, end - start));
			start = end + 1;
			flag = 1;

		}
		else if (end == l) {
			right.push_back(s.substr(start, end - start));
		}
		end++;
	}
}



void solve(string s, vector<pair<string, int> >& va) {
	map<string, int> m;
	stack<pair <string, int> > st;
	int coef = 1;  //总系数
	int start = 0, end = 0, l = s.length();
	if (s[0] >= '0' && s[0] <= '9') {
		while (s[end] >= '0' && s[end] <= '9') {
			end++;
		}
		coef = stoi(s.substr(start, end - start));
	}
	start = end;
	while (end < l) {
		if (s[end] >= 'a' && s[end] <= 'z') {
			end++;
			if (end == l) {
				st.push(pair<string, int>(s.substr(start, end - start), 1));
			}
		}
		else if (s[end] >= '0' && s[end] <= '9') {
			string temp = s.substr(start, end - start);
			start = end;
			while (s[end] >= '0' && s[end] <= '9') {
				end++;
				if (end == l) break;
			}
			int subcoef = stoi(s.substr(start, end - start)); //Ba2   元素系数
			st.push(pair<string, int>(temp, subcoef));
			start = end;
		}
		else if (s[end] >= 'A' && s[end] <= 'Z' && end > start) {
			st.push(pair<string, int>(s.substr(start, end - start), 1));
			start = end;
		}
		else if (s[end] == '(') {
			if (end > 0 && (s[end - 1] > '9' || s[end - 1] < '0') && s[end - 1] != '(' && s[end - 1] != ')') {
				st.push(pair<string, int>(s.substr(start, end - start), 1));
			}
			st.push(pair<string, int>("(", 1));
			end++;
			start = end;
		}
		else if (s[end] == ')') {
			if (end > 0 && (s[end - 1] > '9' || s[end - 1] < '0') && s[end - 1] != '(' && s[end - 1] != ')') {
				st.push(pair<string, int>(s.substr(start, end - start), 1));
			}
			end++;
			start = end;
			int subcoef = 1;
			if (end != l && s[end] >= '0' && s[end] <= '9') {
				while (end != l && s[end] >= '0' && s[end] <= '9') {
					end++;
				}
				subcoef = stoi(s.substr(start, end - start));
				start = end;
			}
			vector<pair<string, int> > v;
			while (st.top().first != "(") {
				pair<string, int> temp = st.top();
				st.pop();
				temp.second *= subcoef;
				v.push_back(temp);
			}
			st.pop();
			for (int i = 0; i < v.size(); i++) {
				st.push(v[i]);
			}
		}
		else {
			end++;
			if (end == l) {
				st.push(pair<string, int>(s.substr(start, end - start), 1));
			}
		}
	}
	
	//vector<pair<string, int> > va;
	while (!st.empty()) {
		pair<string, int> temp = st.top();
		st.pop();
		temp.second *= coef;
		va.push_back(temp);
	}
	
	cout << s << ":" << endl;
	for (int i = 0; i < va.size(); i++) {
		cout << va[i].first << " " << va[i].second << endl;
	}
	
}


int main() {
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		vector<string> left, right;
		map<string, int> l, r;
		string s;
		cin >> s;
		analyse(s, left, right);
		cout << "leftside:" << endl;
		for (int i = 0; i < left.size(); i++) {
			vector<pair<string, int> > va;
			solve(left[i], va);
			for (int j = 0; j < va.size(); j++) {
				if (l.count(va[j].first)) l[va[j].first] += va[j].second;
				else l.insert(va[j]);
			}
		}
		cout << endl << endl << endl << "rightside:" << endl;
		for (int i = 0; i < right.size(); i++) {
			vector<pair<string, int> > va;
			solve(right[i], va);
			for (int j = 0; j < va.size(); j++) {
				if (r.count(va[j].first)) r[va[j].first] += va[j].second;
				else r.insert(va[j]);
			}
		} 

		bool isEqual = true;
		for (map<string, int>::iterator p = l.begin(); p != l.end(); p++) {
			if (!r.count(p->first)) {
				//不存在
				isEqual = false;
				break;
			}
			else {
				if (r[p->first] != p->second) {
					isEqual = false;
					break;
				}
			}
			if (isEqual == false) break;
		}

		if (isEqual) {
			for (map<string, int>::iterator p = r.begin(); p != r.end(); p++) {
				if (!l.count(p->first)) {
					//不存在
					isEqual = false;
					break;
				}
				else {
					if (l[p->first] != p->second) {
						isEqual = false;
						break;
					}
				}
				if (isEqual == false) break;
			}
		}
		if (isEqual) cout << 'Y' << endl;
		else cout << 'N' << endl;
	}
}
你已经成功将 `Date` 列转换为 `datetime64[ns]` 类型,并且输出如下: ``` 0 2021-01-04 1 2021-01-05 2 2021-01-06 3 2021-01-07 4 2021-01-08 Name: Date, dtype: datetime64[ns] ``` ✅ **这说明日期解析完全正确!** 接下来你应该执行: ```python df.set_index('Date', inplace=True) df.sort_index(inplace=True) # 确保时间顺序正确 ``` 然后进入主逻辑,使用我们之前修复过的区间筛选函数(作用于索引)即可正常运行。 --- ### ✅ 当前状态确认清单 | 检查项 | 是否完成 | 说明 | |--------|----------|------| | ✔️ `Date` 列是否为 `datetime64[ns]`? | ✅ 是 | 输出已验证 | | ✔️ 是否设置为索引? | ⚠️ 需手动执行 | 必须调用 `set_index` | | ✔️ 时间是否升序排列? | ⚠️ 建议排序 | 使用 `sort_index()` 更安全 | | ✔️ 区间过滤函数是否作用于 `index`? | ✅ 是 | 否则会出错 | --- ### ✅ 推荐后续代码(确保流程完整) ```python # 设置索引并排序 df.set_index('Date', inplace=True) df.sort_index(inplace=True) # 查看数据类型和前几行 print("Index dtype:", df.index.dtype) print("Data head:") print(df.head()) ``` 此时你的 `df.index` 是一个有序的 `DatetimeIndex`,可以安全用于以下操作: ```python intervals = { 'YTD': lambda idx: idx >= pd.Timestamp(year=idx[-1].year, month=1, day=1), '1Y': lambda idx: idx >= idx[-1] - pd.DateOffset(years=1), '6M': lambda idx: idx >= idx[-1] - pd.DateOffset(months=6), '3M': lambda idx: idx >= idx[-1] - pd.DateOffset(months=3), '1M': lambda idx: idx >= idx[-1] - pd.DateOffset(months=1), } ``` 因为 `idx[-1]` 就是最后一个交易日,比如 `2024-03-28`,它是一个 `pd.Timestamp`,支持 `.year`、`.month` 等属性,不会再报错! --- ### ✅ 示例:查看当前 YTD 起始日 你可以加一段调试代码来验证逻辑是否正确: ```python # 调试:打印各个区间的起始时间(以最后一个日期为基准) last_date = df.index[-1] print(f"最新交易日: {last_date}") print("各区间起始日:") print("YTD:", pd.Timestamp(year=last_date.year, month=1, day=1)) print("1Y: ", last_date - pd.DateOffset(years=1)) print("6M: ", last_date - pd.DateOffset(months=6)) print("3M: ", last_date - pd.DateOffset(months=3)) print("1M: ", last_date - pd.DateOffset(months=1)) ``` 输出示例: ``` 最新交易日: 2024-03-28 各区间起始日: YTD: 2024-01-01 1Y: 2023-03-28 6M: 2023-09-28 3M: 2024-01-28 1M: 2024-02-28 ``` 这些日期就是每个区间的“开始日”,之后用它们做布尔索引就能提取对应时间段的数据。 --- ### ✅ 总结:你现在可以继续了! 只要你完成了以下几步: 1. ✅ 成功将 `Date` 转为 `datetime64[ns]` 2. ✅ 执行了 `df.set_index('Date')` 和 `sort_index()` 3. ✅ 使用基于 `idx`(即 DatetimeIndex)的过滤函数 那么之前的两个错误(`float64 has no attribute year` 和 `>= not supported`)都已彻底解决,现在可以放心运行完整的绩效分析代码。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值