3817: Sum

题目链接

题目大意:给定正整数N,R;求 d=1n(1)d×r×d

题解:膜CA

我的收获:经典套路

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

int T;
ll n,r;
double t;

inline ll calc(ll n,ll a,ll b,ll c){
    if(!n) return 0;
    ll g=__gcd(__gcd(a,b),c);a/=g,b/=g,c/=g;
    ll k=(t*b+c)/a,ret=n*(n+1)/2*k;
    c-=k*a;k=(t*b+c)/a*n;
    return ret+n*k-calc(k,b*b*r-c*c,a*b,-a*c);
}

void work()
{
    scanf("%lld%lld",&n,&r);t=sqrt(r);
    if((ll)t==t) printf("%d\n",(r&1)?((n&1)?-1:0):n);
    else printf("%lld\n",n+(calc(n,2,1,0)<<2)-(calc(n,1,1,0)<<1));
}

int main()
{
    scanf("%d",&T);
    while(T--) work();
    return 0;
}
KeyError Traceback (most recent call last) File D:\pythonpachong\Lib\site-packages\pandas\core\indexes\base.py:3805, in Index.get_loc(self, key) 3804 try: -> 3805 return self._engine.get_loc(casted_key) 3806 except KeyError as err: File index.pyx:167, in pandas._libs.index.IndexEngine.get_loc() File index.pyx:196, in pandas._libs.index.IndexEngine.get_loc() File pandas\\_libs\\hashtable_class_helper.pxi:7081, in pandas._libs.hashtable.PyObjectHashTable.get_item() File pandas\\_libs\\hashtable_class_helper.pxi:7089, in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: &#39;总面积(㎡)&#39; The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) Cell In[22], line 2 1 sum_price=file_data[&#39;价格(元/月)&#39;].groupby(file_data[&#39;区域&#39;]).sum() ----> 2 sum_area=file_data[&#39;总面积(㎡)&#39;].groupby(file_data[&#39;区域&#39;]).sum() 3 df_all[&#39;房租总金额&#39;]=sum_price.values 4 df_all[&#39;总面积(㎡)&#39;]=sum_area.values File D:\pythonpachong\Lib\site-packages\pandas\core\frame.py:4102, in DataFrame.__getitem__(self, key) 4100 if self.columns.nlevels > 1: 4101 return self._getitem_multilevel(key) -> 4102 indexer = self.columns.get_loc(key) 4103 if is_integer(indexer): 4104 indexer = [indexer] File D:\pythonpachong\Lib\site-packages\pandas\core\indexes\base.py:3812, in Index.get_loc(self, key) 3807 if isinstance(casted_key, slice) or ( 3808 isinstance(casted_key, abc.Iterable) 3809 and any(isinstance(x, slice) for x in casted_key) 3810 ): 3811 raise InvalidIndexError(key) -> 3812 raise KeyError(key) from err 3813 except TypeError: 3814 # If we have a listlike key, _check_indexing_error will raise 3815 # InvalidIndexError. Otherwise we fall through and re-raise 3816 # the TypeError. 3817 self._check_indexing_error(key) KeyError: &#39;总面积(㎡)&#39;
06-07
# 计算每日持仓统计和前5大持仓 def calculate_daily_positions(df): # 连续日期范围 all_dates = pd.date_range(start=df[&#39;date&#39;].min(), end=df[&#39;date&#39;].max(), name=&#39;date&#39;).strftime("%Y-%m-%d") all_clients = df[&#39;client_id&#39;].unique() # 完整的时间-客户 date_client_panel = pd.MultiIndex.from_product( [all_dates, all_clients], names=[&#39;date&#39;, &#39;client_id&#39;] ).to_frame(index=False) # 合并原始数据(填充缺失日期) merged = date_client_panel.merge( df, on=[&#39;date&#39;, &#39;client_id&#39;], how=&#39;left&#39; ) # 标记持仓方向 merged[&#39;position_type&#39;] = np.where( merged[&#39;cum_qty&#39;] > 0, &#39;long&#39;, np.where(merged[&#39;cum_qty&#39;] < 0, &#39;short&#39;, &#39;neutral&#39;) ) # 计算每日持仓统计 daily_stats = merged.groupby([&#39;client_id&#39;, &#39;date&#39;]).agg( long_count=(&#39;instrument_id&#39;, lambda x: (x.notnull() & (merged.loc[x.index, &#39;position_type&#39;] == &#39;long&#39;)).nunique()), short_count=(&#39;instrument_id&#39;, lambda x: (x.notnull() & (merged.loc[x.index, &#39;position_type&#39;] == &#39;short&#39;)).nunique()), long_qty=(&#39;cum_qty&#39;, lambda x: x[x > 0].sum()), short_qty=(&#39;cum_qty&#39;, lambda x: abs(x[x < 0].sum())) ).reset_index() # 计算前5大持仓 def top5_holdings(group): # 分离多头和空头 long_pos = group[group[&#39;position_type&#39;] == &#39;long&#39;] short_pos = group[group[&#39;position_type&#39;] == &#39;short&#39;] # 多头前5 if not long_pos.empty: top5_long = long_pos.nlargest(5, &#39;cum_qty&#39;) long_top5_qty = top5_long[&#39;cum_qty&#39;].sum() long_top5_ratio = long_top5_qty / group[&#39;long_qty&#39;].iloc[0] else: long_top5_qty = 0 long_top5_ratio = 0 # 空头前5(按绝对值排序) if not short_pos.empty: short_pos[&#39;abs_qty&#39;] = short_pos[&#39;cum_qty&#39;].abs() top5_short = short_pos.nlargest(5, &#39;abs_qty&#39;) short_top5_qty = top5_short[&#39;abs_qty&#39;].sum() short_top5_ratio = short_top5_qty / group[&#39;short_qty&#39;].iloc[0] else: short_top5_qty = 0 short_top5_ratio = 0 return pd.Series({ &#39;long_top5_qty&#39;: long_top5_qty, &#39;long_top5_ratio&#39;: long_top5_ratio, &#39;short_top5_qty&#39;: short_top5_qty, &#39;short_top5_ratio&#39;: short_top5_ratio }) top5_stats = merged.groupby([&#39;client_id&#39;, &#39;date&#39;]).apply(top5_holdings).reset_index() # 合并结果 final_daily_stats = daily_stats.merge(top5_stats, on=[&#39;client_id&#39;, &#39;date&#39;]) # 计算换手率(使用前一日持仓量) final_daily_stats[&#39;prev_long_qty&#39;] = final_daily_stats.groupby(&#39;client_id&#39;)[&#39;long_qty&#39;].shift(1) final_daily_stats[&#39;prev_short_qty&#39;] = final_daily_stats.groupby(&#39;client_id&#39;)[&#39;short_qty&#39;].shift(1) # 获取当日交易量(从原始数据) daily_trade = df.groupby([&#39;client_id&#39;, &#39;date&#39;])[&#39;td_qty&#39;].sum().abs().reset_index(name=&#39;daily_trade&#39;) final_daily_stats = final_daily_stats.merge(daily_trade, on=[&#39;client_id&#39;, &#39;date&#39;], how=&#39;left&#39;) # 计算换手率 final_daily_stats[&#39;turnover_rate&#39;] = final_daily_stats[&#39;daily_trade&#39;] / ( final_daily_stats[&#39;prev_long_qty&#39;] + final_daily_stats[&#39;prev_short_qty&#39;] ).replace(0, np.nan) return final_daily_stats # 计算每日持仓统计 daily_positions_df = calculate_daily_positions(multi_cpty_df) daily_positions_df 你这里的代码好像有点问题,报错:--------------------------------------------------------------------------- KeyError Traceback (most recent call last) File c:\Users\matianht\.conda\envs\nomura\lib\site-packages\pandas\core\indexes\base.py:3805, in Index.get_loc(self, key) 3804 try: -> 3805 return self._engine.get_loc(casted_key) 3806 except KeyError as err: File index.pyx:167, in pandas._libs.index.IndexEngine.get_loc() File index.pyx:196, in pandas._libs.index.IndexEngine.get_loc() File pandas\\_libs\\hashtable_class_helper.pxi:7081, in pandas._libs.hashtable.PyObjectHashTable.get_item() File pandas\\_libs\\hashtable_class_helper.pxi:7089, in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: &#39;short_qty&#39; The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) Cell In[57], line 87 84 return final_daily_stats 86 # 计算每日持仓统计 ---> 87 daily_positions_df = calculate_daily_positions(multi_cpty_df) 89 daily_positions_df Cell In[57], line 66, in calculate_daily_positions(df) 57 short_top5_ratio = 0 59 return pd.Series({ 60 &#39;long_top5_qty&#39;: long_top5_qty, 61 &#39;long_top5_ratio&#39;: long_top5_ratio, 62 &#39;short_top5_qty&#39;: short_top5_qty, 63 &#39;short_top5_ratio&#39;: short_top5_ratio 64 }) ---> 66 top5_stats = merged.groupby([&#39;client_id&#39;, &#39;date&#39;]).apply(top5_holdings).reset_index() 68 # 合并结果 69 final_daily_stats = daily_stats.merge(top5_stats, on=[&#39;client_id&#39;, &#39;date&#39;]) File c:\Users\matianht\.conda\envs\nomura\lib\site-packages\pandas\core\groupby\groupby.py:1824, in GroupBy.apply(self, func, include_groups, *args, **kwargs) 1822 with option_context("mode.chained_assignment", None): 1823 try: -> 1824 result = self._python_apply_general(f, self._selected_obj) 1825 if ( 1826 not isinstance(self.obj, Series) 1827 and self._selection is None 1828 and self._selected_obj.shape != self._obj_with_exclusions.shape 1829 ): 1830 warnings.warn( 1831 message=_apply_groupings_depr.format( 1832 type(self).__name__, "apply" (...) 1835 stacklevel=find_stack_level(), 1836 ) File c:\Users\matianht\.conda\envs\nomura\lib\site-packages\pandas\core\groupby\groupby.py:1885, in GroupBy._python_apply_general(self, f, data, not_indexed_same, is_transform, is_agg) 1850 @final 1851 def _python_apply_general( 1852 self, (...) 1857 is_agg: bool = False, 1858 ) -> NDFrameT: 1859 """ 1860 Apply function f in python space 1861 (...) 1883 data after applying f 1884 """ -> 1885 values, mutated = self._grouper.apply_groupwise(f, data, self.axis) 1886 if not_indexed_same is None: 1887 not_indexed_same = mutated File c:\Users\matianht\.conda\envs\nomura\lib\site-packages\pandas\core\groupby\ops.py:919, in BaseGrouper.apply_groupwise(self, f, data, axis) 917 # group might be modified 918 group_axes = group.axes --> 919 res = f(group) 920 if not mutated and not _is_indexed_like(res, group_axes, axis): 921 mutated = True Cell In[57], line 54, in calculate_daily_positions.<locals>.top5_holdings(group) 52 top5_short = short_pos.nlargest(5, &#39;abs_qty&#39;) 53 short_top5_qty = top5_short[&#39;abs_qty&#39;].sum() ---> 54 short_top5_ratio = short_top5_qty / group[&#39;short_qty&#39;].iloc[0] 55 else: 56 short_top5_qty = 0 File c:\Users\matianht\.conda\envs\nomura\lib\site-packages\pandas\core\frame.py:4102, in DataFrame.__getitem__(self, key) 4100 if self.columns.nlevels > 1: 4101 return self._getitem_multilevel(key) -> 4102 indexer = self.columns.get_loc(key) 4103 if is_integer(indexer): 4104 indexer = [indexer] File c:\Users\matianht\.conda\envs\nomura\lib\site-packages\pandas\core\indexes\base.py:3812, in Index.get_loc(self, key) 3807 if isinstance(casted_key, slice) or ( 3808 isinstance(casted_key, abc.Iterable) 3809 and any(isinstance(x, slice) for x in casted_key) 3810 ): 3811 raise InvalidIndexError(key) -> 3812 raise KeyError(key) from err 3813 except TypeError: 3814 # If we have a listlike key, _check_indexing_error will raise 3815 # InvalidIndexError. Otherwise we fall through and re-raise 3816 # the TypeError. 3817 self._check_indexing_error(key) KeyError: &#39;short_qty&#39;
07-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值