华为机考入门python3--(0)模拟题3-计算字符串重新排列数

分类:排列组合

知识点:

  1. 计算字符串中每个字符出现的次数 Counter(string)

  2. 计算列表中每个元素出现的次数 Counter(list)

  3. 阶乘 math.factorial(num)

  4. 排列去重

题目来自【华为招聘模拟考试】

先把每个字符当成唯一出现过一次,计算所有排列数;

再统计重复出现的字母,除去每个字母的排列次数。

例如:

python 复制代码
import math
from collections import Counter
# If you need to import additional packages or classes, please import here.

def func():

    # please define the python3 input here. For example: a,b = map(int, input().strip().split())
    S = input().strip()
    # please finish the function body here.
    # please define the python3 output here. For example: print().
    # Step1: 先把每个字符当成唯一出现过一次,计算所有排列数
    up = math.factorial(len(S))

    # Step2: 再统计重复出现的字母的排列数
    down_list = []
    # print(Counter(S))
    # 统计每个字符的数量 Counter({'A': 2, 'B': 1})
    for letter, n in Counter(S).items():
        if n > 1:
            # 计算每个字符出现的排列次数
            down_list.append(math.factorial(n))

    # print(down_list)
    # [6, 2]

    down = 1
    for i in down_list:
        down *= i

    # 除去每个字母的排列次数
    # // 取整除 - 往小的方向取整数
    print(up // down)

if __name__ == "__main__":
    func()

参考:

https://blog.csdn.net/weixin_44052055/article/details/124076922

https://blog.csdn.net/qq_43486538/article/details/132911707

Counter用法

python 复制代码
from collections import Counter

# 示例字符串
example_string = "abracadabra"

# 使用 Counter 计算字符串中每个字符的出现次数
char_counts = Counter(example_string)

# 打印结果
print(char_counts)
python 复制代码
from collections import Counter

# 示例列表
example_list = [1, 2, 3, 1, 2, 4, 1, 3, 5]

# 使用 Counter 计算列表中每个元素的出现次数
element_counts = Counter(example_list)

# 打印结果
print(element_counts)

by 软件工程小施同学

相关推荐
天上路人13 分钟前
A-59F 多功能语音处理模组在本地会议系统扩音啸叫处理中的技术应用与性能分析
人工智能·神经网络·算法·硬件架构·音视频·语音识别·实时音视频
yang_B6211 小时前
噪声处理方法
大数据·人工智能·算法
菜菜小狗的学习笔记1 小时前
剑指Offer算法题(九)搜索
数据结构·算法·深度优先
JosieBook1 小时前
【C#】C# 所有关键字总结
开发语言·算法·c#
无忧智库1 小时前
算力、算法、数据三位一体:构建城市级AI大模型算力池的全景式解构与未来展望(WORD)
大数据·人工智能·算法
蓝天守卫者联盟11 小时前
2026乙酸乙酯回收设备厂家选型与技术实践
java·jvm·python·算法
DDzqss1 小时前
3.25打卡day45
c++·算法
爆更小小刘1 小时前
2.3.1_2 浮点数的表示 IEEE 754(例题训练)
算法
赫瑞2 小时前
Java中的 Dijkstra 算法
java·算法
小羊羔heihei2 小时前
Python编程实战:12道趣味算法题
笔记·python·学习·其他·算法·学习方法·交友