题目1:
编写函数pay(),带两个输入参数:小时工资和上周员工工作了的小时数。函数计算并返回员工的工资。加班工资的计算方法如下:大于40小时但小于或等于60小时按平时小时薪酬的1.5倍给薪;大于60小时则按平时小时薪酬的2倍给薪。函数接口定义: pay(salaryHour, hours)注:salaryHour是平时小时薪酬,hours是员工工作的小时数
案例一:
def pay(salaryHour, hours):
salary = 0
if hours <= 40:
salary = salaryHour * hours
elif 40 < hours <= 60:
salary = 40 * salaryHour + (hours - 40) * salaryHour * 1.5
else: # 超过60小时
salary = 40 * salaryHour + 20 * salaryHour * 1.5 + (hours - 60) * salaryHour * 2
return salary # 将return移到所有条件判断之外,确保任何情况都能返回结果
#测试用例
hours = 65
salaryHour = 40
print(f"工作了{hours}小时")
print(f"应得工资:{pay(salaryHour, hours)}元")
题目2:
输入三个正实数(浮点数),如果能够组成三角形,输出三角形面积,如果不能,输出"error"。三个数能够组成三角形的条件是:任意两边之和大于第三边。已知三边长求三角形面积的公式为:s=(a+b+c)/2area=sqrt(s(s−a)(s−b)(s−c))
案例二:
import math
a = float(input("输入正实数a:"))
b = float(input("输入正实数b:"))
c = float(input("输入正实数c:"))
if a + b > c and a + c > b and b + c > a:
s = (a + b + c) / 2
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
print(f"三边长为{a}、{b}、{c}的三角形的面积为{area:.2f}")
else:
print("error")
题目3:
创建正方形画布,以画布中心为原点画出坐标轴,并按以下公式绘制函数曲线:x = wh × ( cos(t) + (1/2) × cos(7t) + (1/3) × sin(17t) ) / 2y = hh × ( sin(t) + (1/2) × sin(7t) + (1/3) × cos(17t) ) / 2其中wh、hh的取值分别为画布的半宽和半高,t的取值范围为0至2π,步长为0.01.
案例三:
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0, np.pi * 2, 0.01)
wh = 100
hh = 100
x = wh * (np.cos(t) + 1/2 * np.cos(7*t) + 1/3 * np.sin(17*t)) / 2
y = hh * (np.sin(t) + 1/2 * np.sin(7*t) + 1/3 * np.cos(17*t)) / 2
plt.subplots(figsize=(wh, hh))
plt.plot(x, y)
plt.grid() # 网格
plt.show()
题目4:
给定一个数组,将数组中的元素向右移动k个位置,其中k是非负数。示例:nums = [1, 2, 3, 4, 5, 6, 7]k = 3result = [5,6,7,1,2,3,4]
案例四:
# 示例:
# nums = [1, 2, 3, 4, 5, 6, 7]
# k = 3
# result = [5,6,7,1,2,3,4]
def move_k(nums, k):
if len(nums) == 0: # 数组为空
return nums
k = k % len(nums)
left = nums[:-k]
right = nums[-k:]
return right + left
# 测试用例
nums = [1, 2, 3, 4, 5, 6, 7]
k = 3
print(move_k(nums, k))
题目5:
给一个长度为 n 的数组,如果数组中有一个数字出现的次数超过数组长度的一半,就输出这个数字,否则输出-1。例如输入一个长度为9的数组[1,2,3,2,2,2,5,4,2]。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。
案例五:
def find_majority(nums):
n = len(nums)
threshold = n // 2
count_dict = {}
for num in nums:
count_dict[num] = count_dict.get(num, 0) + 1
if count_dict[num] > threshold:
return num
return -1
# 示例测试
print(find_majority([1,2,3,2,2,2,5,4,2])) # 输出: 2