华为机考入门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 软件工程小施同学

相关推荐
不是吧这都有重名1 小时前
[论文阅读]Deeply-Supervised Nets
论文阅读·人工智能·算法·大语言模型
homelook1 小时前
matlab simulink双边反激式变压器锂离子电池均衡系统,双目标均衡策略,仿真模型,提高均衡速度38%
算法
什码情况2 小时前
星际篮球争霸赛/MVP争夺战 - 华为OD机试真题(A卷、Java题解)
java·数据结构·算法·华为od·面试·机试
天上路人2 小时前
采用AI神经网络降噪算法的通信语音降噪(ENC)模组性能测试和应用
人工智能·神经网络·算法
字节高级特工2 小时前
【C++】”如虎添翼“:模板初阶
java·c语言·前端·javascript·c++·学习·算法
.Vcoistnt2 小时前
Codeforces Round 1024 (Div. 2)(A-D)
数据结构·c++·算法·贪心算法·动态规划·图论
晴天下小雨o2 小时前
排序算法总结
java·算法·排序算法
程序员爱钓鱼3 小时前
循环语句:for、range -《Go语言实战指南》
java·数据结构·算法
LabVIEW开发3 小时前
LabVIEW中算法开发的系统化解决方案与优化
算法·labview
chenyuhao20243 小时前
链表面试题7之相交链表
数据结构·算法·链表·面试·c#