python test8

46 阅读3分钟
# 题目1:找出数组中只出现一次的两个数字
def find_one(nums):
    dc = {}
    for num in nums:
        if num not in dc:
            dc[num] = 1
        else:
            dc[num] += 1
    result = []
    for key, value in dc.items():
        if value == 1:
            result.append(key)
    return result

# 测试用例
nums1 = [1, 4, 1, 6]
nums2 = [1, 2, 3, 3, 2, 9]
print(f"数组{nums1}的结果为{find_one(nums1)}")  # [4, 6]
print(f"数组{nums2}的结果为{find_one(nums2)}")  # [1, 9]


# 题目2:查找字符串数组中的最长公共前缀
def find_longest(strs):
    if not strs:
        return ""
    # 以第一个字符串为基准
    for i in range(len(strs[0])):
        # 与其他字符串逐个字符比较
        for s in strs[1:]:
            # 超出长度或字符不匹配则返回前缀
            if i >= len(s) or strs[0][i] != s[i]:
                return strs[0][:i]
    # 所有字符都匹配
    return strs[0]

# 测试用例
strs1 = ["flower", "flow", "flight"]
strs2 = ["dog", "racecar", "car"]
print(find_longest(strs1))  # "fl"
print(find_longest(strs2))  # ""


# 题目3:判断有效的括号
def match_strs(s):
    stack = []  # 创建栈
    # 右括号与左括号的映射关系
    dc = {
        ')': '(',
        ']': '[',
        '}': '{'
    }
    for char in s:
        if char in dc:  # 如果是右括号
            # 栈为空或栈顶元素不匹配
            if not stack or stack.pop() != dc[char]:
                return False
        else:  # 如果是左括号,入栈
            stack.append(char)
    # 栈为空说明所有括号都匹配
    return not stack

# 测试用例
s1 = "()[]{}"
s2 = "(]"
s3 = "([)]"
s4 = "{[]}"
print(match_strs(s1))  # True
print(match_strs(s2))  # False
print(match_strs(s3))  # False
print(match_strs(s4))  # True


# 题目4:电商用户行为数据分析
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 设置中文显示
plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
plt.rcParams["axes.unicode_minus"] = False  # 解决负号显示问题

# 读取CSV文件数据到DataFrame
df = pd.read_csv(
    "用户行为.csv",
    encoding="utf-8",
    index_col="用户ID"
)
print("原始数据:")
print(df.head())

# 1. 计算不同用户等级的平均浏览时长、平均下单次数和平均支付金额
mean_data = df.groupby('用户等级(1-5级)').agg(
    平均浏览时长=('浏览时长(分钟)', 'mean'),
    平均下单次数=('下单次数', 'mean'),
    平均支付金额=('支付金额(元)', 'mean')
)
print("\n不同用户等级的统计数据:")
print(mean_data)

# 2. 计算所有用户的“支付金额”的最大值、最小值、标准差和中位数
payment_stats = df['支付金额(元)'].agg(['max', 'min', 'std', 'median'])
print("\n支付金额统计:")
print(f"最大值:{payment_stats['max']}")
print(f"最小值:{payment_stats['min']}")
print(f"标准差:{payment_stats['std']:.2f}")
print(f"中位数:{payment_stats['median']}")

# 3. 为每位用户添加“单均支付金额”列(支付金额 / 下单次数)
# 处理下单次数为0的情况,避免除零错误
df['单均支付金额'] = df.apply(
    lambda row: row['支付金额(元)'] / row['下单次数'] if row['下单次数'] != 0 else 0,
    axis=1
)
print("\n添加单均支付金额后的数据:")
print(df.head())

# 4. 绘制不同用户等级的“平均支付金额”柱状图
plt.figure(figsize=(10, 6))
mean_data['平均支付金额'].plot(kind='bar', color='skyblue')
plt.title('不同用户等级的平均支付金额')
plt.xlabel('用户等级')
plt.ylabel('平均支付金额(元)')
plt.xticks(rotation=0)  # 不旋转x轴标签
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
plt.show()