C++实现乘法口诀表的课程作业

版权申诉
0 下载量 162 浏览量 更新于2024-10-02 收藏 559B RAR 举报
资源摘要信息:"CSC_220_Assignment_2.rar_assignment" 在本次资源摘要中,我们将详细探讨与标题"CSC_220_Assignment_2.rar_assignment"相关的知识点,以及描述中提及的通过C++语言实现乘法口诀表的编程实践。 首先,标题中的"CSC_220"很可能指的是计算机科学(Computer Science)的一门课程代码,而"Assignment 2"表明这是一个第二份作业任务。"rar"是文件的压缩格式,通常用于减少文件大小以方便传输。".assignment"则可能是对文件类型的描述,表明这是一个教学任务或作业文件。 描述部分指出,本次作业的目标是通过C++语言来实现乘法口诀表。C++是一种广泛使用的高级编程语言,它支持面向对象、泛型和过程化等多种编程范式。C++在系统软件、游戏开发、实时物理模拟等领域有广泛的应用。实现乘法口诀表对于初学者来说是一个基础但很有教育意义的练习,因为它涉及到循环结构(如for循环和while循环)的使用,以及可能的函数封装和数组操作。 以下是一个简单的C++乘法口诀表示例代码,它展示了如何使用嵌套循环(一个循环在另一个循环内部)来生成口诀表: ```cpp #include <iostream> using namespace std; int main() { int size = 9; // 乘法口诀表通常为9x9 for (int i = 1; i <= size; ++i) { // 外层循环控制行数 for (int j = 1; j <= i; ++j) { // 内层循环控制每行显示的列数,使其不超过行号 cout << j << " x " << i << " = " << i*j << "\t"; // 输出乘法口诀的一条记录,使用制表符\t控制对齐 } cout << endl; // 每行结束后换行 } return 0; } ``` 这段代码将输出一个标准的9x9乘法口诀表,其中每一行显示的乘法表达式的个数逐渐增多,从"1 x 1 = 1"到"9 x 9 = 81"。 对于标签"assignment",这通常表示这是一个特定的课程作业或项目任务。在计算机科学的课程中,学生通过完成这些作业来巩固他们在课堂上学到的理论知识,并通过实践提高编程技能。 从压缩包子文件的文件名称列表"CSC_220_Assignment_2.cpp"可以看出,作业文件是一个C++源代码文件。文件扩展名".cpp"是C++源代码文件的标准扩展名,它告诉计算机该文件是一个可以被编译器编译成可执行程序的源代码文件。 通过本次作业,学生能够练习以下知识点和技能: 1. C++基础语法的使用,包括变量声明、循环结构、条件语句等。 2. 理解并实践基本的算法逻辑,如乘法口诀表的生成。 3. 熟悉C++标准输入输出流库(iostream)的使用,特别是cout用于屏幕输出。 4. 掌握程序的结构化设计,可能会涉及到将代码分解成函数来提高代码的可读性和复用性。 5. 学习调试和测试技巧,确保程序能够正确执行并生成预期的输出结果。 总结上述内容,本次作业是一个典型的编程入门练习,它帮助学生将理论知识转化为实际应用能力,为进一步的编程学习和软件开发打下坚实的基础。

import pandas as pd import numpy as np # 计算用户对歌曲的播放比例 triplet_dataset_sub_song_merged_sum_df = triplet_dataset_sub_song_mergedpd[['user', 'listen_count']].groupby('user').sum().reset_index() triplet_dataset_sub_song_merged_sum_df.rename(columns={'listen_count': 'total_listen_count'}, inplace=True) triplet_dataset_sub_song_merged = pd.merge(triplet_dataset_sub_song_mergedpd, triplet_dataset_sub_song_merged_sum_df) triplet_dataset_sub_song_mergedpd['fractional_play_count'] = triplet_dataset_sub_song_mergedpd['listen_count'] / triplet_dataset_sub_song_merged['total_listen_count'] # 将用户和歌曲编码为数字 small_set = triplet_dataset_sub_song_mergedpd user_codes = small_set.user.drop_duplicates().reset_index() song_codes = small_set.song.drop_duplicates().reset_index() user_codes.rename(columns={'index': 'user_index'}, inplace=True) song_codes.rename(columns={'index': 'song_index'}, inplace=True) song_codes['so_index_value'] = list(song_codes.index) user_codes['us_index_value'] = list(user_codes.index) small_set = pd.merge(small_set, song_codes, how='left') small_set = pd.merge(small_set, user_codes, how='left') # 将数据转换为稀疏矩阵形式 from scipy.sparse import coo_matrix mat_candidate = small_set[['us_index_value', 'so_index_value', 'fractional_play_count']] data_array = mat_candidate.fractional_play_count.values row_array = mat_candidate.us_index_value.values col_array = mat_candidate.so_index_value.values data_sparse = coo_matrix((data_array, (row_array, col_array)), dtype=float) # 使用SVD方法进行矩阵分解并进行推荐 from scipy.sparse import csc_matrix from scipy.sparse.linalg import svds import math as mt def compute_svd(urm, K): U, s, Vt = svds(urm, K) dim = (len(s), len(s)) S = np.zeros(dim, dtype=np.float32) for i in range(0, len(s)): S[i, i] = mt.sqrt(s[i]) U = csc_matrix(U, dtype=np.float32) S = csc_matrix(S, dtype=np.float32) Vt = csc_matrix(Vt, dtype=np.float32) return U, S, Vt def compute_estimated_matrix(urm, U, S, Vt, uTest, K, test): rightTerm = S * Vt max_recommendation = 250 estimatedRatings = np.zeros(shape=(MAX_UID, MAX_PID), dtype=np.float16) recomendRatings = np.zeros(shape=(MAX_UID, max_recommendation), dtype=np.float16) for userTest in uTest: prod = U[userTest, :] * rightTerm estimatedRatings[userTest, :] = prod.todense() recomendRatings[userTest, :] = (-estimatedRatings[userTest, :]).argsort()[:max_recommendation] return recomendRatings K = 50 urm = data_sparse MAX_PID = urm.shape[1] MAX_UID = urm.shape[0] U, S, Vt = compute_svd(urm, K) uTest = [4, 5, 6, 7, 8, 73, 23] # uTest=[1b5bb32767963cbc215d27a24fef1aa01e933025] uTest_recommended_items = compute_estimated_matrix(urm, U, S, Vt 继续将这段代码输出完整

2023-05-19 上传

将上述代码放入了Recommenders.py文件中,作为一个自定义工具包。将下列代码中调用scipy包中svd的部分。转为使用Recommenders.py工具包中封装的svd方法。给出修改后的完整代码。import pandas as pd import math as mt import numpy as np from sklearn.model_selection import train_test_split from Recommenders import * from scipy.sparse.linalg import svds from scipy.sparse import coo_matrix from scipy.sparse import csc_matrix # Load and preprocess data triplet_dataset_sub_song_merged = triplet_dataset_sub_song_mergedpd # load dataset triplet_dataset_sub_song_merged_sum_df = triplet_dataset_sub_song_merged[['user','listen_count']].groupby('user').sum().reset_index() triplet_dataset_sub_song_merged_sum_df.rename(columns={'listen_count':'total_listen_count'},inplace=True) triplet_dataset_sub_song_merged = pd.merge(triplet_dataset_sub_song_merged,triplet_dataset_sub_song_merged_sum_df) triplet_dataset_sub_song_merged['fractional_play_count'] = triplet_dataset_sub_song_merged['listen_count']/triplet_dataset_sub_song_merged['total_listen_count'] # Convert data to sparse matrix format small_set = triplet_dataset_sub_song_merged user_codes = small_set.user.drop_duplicates().reset_index() song_codes = small_set.song.drop_duplicates().reset_index() user_codes.rename(columns={'index':'user_index'}, inplace=True) song_codes.rename(columns={'index':'song_index'}, inplace=True) song_codes['so_index_value'] = list(song_codes.index) user_codes['us_index_value'] = list(user_codes.index) small_set = pd.merge(small_set,song_codes,how='left') small_set = pd.merge(small_set,user_codes,how='left') mat_candidate = small_set[['us_index_value','so_index_value','fractional_play_count']] data_array = mat_candidate.fractional_play_count.values row_array = mat_candidate.us_index_value.values col_array = mat_candidate.so_index_value.values data_sparse = coo_matrix((data_array, (row_array, col_array)),dtype=float) # Compute SVD def compute_svd(urm, K): U, s, Vt = svds(urm, K) dim = (len(s), len(s)) S = np.zeros(dim, dtype=np.float32) for i in range(0, len(s)): S[i,i] = mt.sqrt(s[i]) U = csc_matrix(U, dtype=np.float32) S = csc_matrix(S, dtype=np.float32) Vt = csc_matrix(Vt, dtype=np.float32) return U, S, Vt def compute_estimated_matrix(urm, U, S, Vt, uTest, K, test): rightTerm = S*Vt max_recommendation = 10 estimatedRatings = np.zeros(shape=(MAX_UID, MAX_PID), dtype=np.float16) recomendRatings = np.zeros(shape=(MAX_UID,max_recommendation ), dtype=np.float16) for userTest in uTest: prod = U[userTest, :]*rightTerm estimatedRatings[userTest, :] = prod.todense() recomendRatings[userTest, :] = (-estimatedRatings[userTest, :]).argsort()[:max_recommendation] return recomendRatings K=50 # number of factors urm = data_sparse MAX_PID = urm.shape[1] MAX_UID = urm.shape[0] U, S, Vt = compute_svd(urm, K) # Compute recommendations for test users # Compute recommendations for test users uTest = [1,6,7,8,23] uTest_recommended_items = compute_estimated_matrix(urm, U, S, Vt, uTest, K, True) # Output recommended songs in a dataframe recommendations = pd.DataFrame(columns=['user','song', 'score','rank']) for user in uTest: rank = 1 for song_index in uTest_recommended_items[user, 0:10]: song = small_set.loc[small_set['so_index_value'] == song_index].iloc[0] # Get song details recommendations = recommendations.append({'user': user, 'song': song['title'], 'score': song['fractional_play_count'], 'rank': rank}, ignore_index=True) rank += 1 display(recommendations)

2023-06-07 上传