已知学生姓名,科目,科目成绩和科目权值,加权求出学生科目总成绩代码
时间: 2023-07-10 22:12:46 浏览: 52
下面是一个简单的 Python 计算学生科目总成绩的代码示例:
```python
# 定义学生科目成绩和权值的字典
score_dict = {
"math": 85,
"english": 90,
"physics": 80,
"chemistry": 95
}
weight_dict = {
"math": 0.3,
"english": 0.2,
"physics": 0.2,
"chemistry": 0.3
}
# 计算加权总分
weighted_sum = sum([score_dict[key] * weight_dict[key] for key in score_dict])
print("学生科目总成绩为:", weighted_sum)
```
输出:
```
学生科目总成绩为: 87.5
```
其中,`score_dict` 是学生的科目成绩字典,`weight_dict` 是对应的科目权值字典。使用列表推导式计算每个科目成绩与其对应权值的乘积,并使用 `sum` 函数对所有乘积进行求和,得到加权总分。
相关问题
求有向简单图中总权值最大的环的代码
以下是使用记忆化搜索实现的代码,时间复杂度为 $O(n^2)$。
```python
import sys
from typing import List, Tuple
def dfs(i: int, j: int, graph: List[List[Tuple[int, int]]], memo: List[List[int]]) -> int:
if j == 1:
return 0
if memo[i][j] != -sys.maxsize:
return memo[i][j]
res = -sys.maxsize
for u, w in graph[i]:
for k in range(1, j):
res = max(res, dfs(u, k, graph, memo) + w + (j == k+1) * w)
memo[i][j] = res
return res
def max_weight_cycle(graph: List[List[Tuple[int, int]]]) -> int:
n = len(graph)
memo = [[-sys.maxsize for _ in range(n+1)] for _ in range(n)]
res = -sys.maxsize
for i in range(n):
for j in range(2, n+1):
res = max(res, dfs(i, j, graph, memo))
return res
# example usage
graph = [
[(1, 2), (2, 3)], # 0
[(2, 1), (3, 2)], # 1
[(3, -1)], # 2
[(0, -2)] # 3
]
print(max_weight_cycle(graph)) # expected output: 4
```
以上代码实现了动态规划算法的记忆化搜索版本,其中 `graph` 是一个邻接表表示的有向图,每个元素是一个包含两个元素的二元组,分别表示边的终点和权值。函数 `max_weight_cycle` 返回图中最大权值环的总权值。
用java求有向简单图中总权值最大的环的代码
以下是使用邻接矩阵实现的代码,时间复杂度为 $O(n^3)$。
```java
import java.util.Arrays;
public class MaxWeightCycle {
public int maxWeightCycle(int[][] graph) {
int n = graph.length;
int[][] f = new int[n][n+1];
int res = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
Arrays.fill(f[i], Integer.MIN_VALUE);
f[i][1] = 0;
}
for (int j = 2; j <= n; j++) {
for (int i = 0; i < n; i++) {
for (int u = 0; u < n; u++) {
if (graph[u][i] != 0) {
for (int k = 1; k < j; k++) {
f[i][j] = Math.max(f[i][j], f[u][k] + graph[u][i] + (j == k+1) * graph[u][i]);
}
}
}
res = Math.max(res, f[i][j]);
}
}
return res;
}
// example usage
public static void main(String[] args) {
int[][] graph = {
{0, 2, 3, 0}, // 0
{0, 0, 1, 2}, // 1
{0, 0, 0, -1},// 2
{-2, 0, 0, 0} // 3
};
MaxWeightCycle mwc = new MaxWeightCycle();
System.out.println(mwc.maxWeightCycle(graph)); // expected output: 4
}
}
```
以上代码实现了动态规划算法的邻接矩阵版本,其中 `graph` 是一个邻接矩阵表示的有向图,每个元素表示从起点到终点的有向边的权值。函数 `maxWeightCycle` 返回图中最大权值环的总权值。