python - 计算排列中的排列数

标签 python r algorithm permutation

一个大小为n的排列是一个n个整数的序列,其中从1到n的每个值恰好出现一次。例如,序列 [3, 1, 2]、[1] 和 [1, 2, 3, 4] 是排列,而 [2]、[4, 1, 2]、[3, 1] 不是.

所以我收到 2 个输入:1 - 排列中的数字数,2 - 排列本身。

问题是:有多少区间 [l;r](1 ≤ l ≤ r ≤ n) 序列 p[l..r] 也是一个排列? 例如:

input - 7; [6, 3, 4, 1, 2, 7, 5]
The answer is 4:
permutation is [6, 3, 4, 1, 2, 7, 5];
permutation is [1];
permutation is [1, 2];
permutation is [3, 4, 1, 2]

希望你没听懂这个问题。

我写了前两个案例,但我不知道如何检查其他案例:

numbers = int(input("Amount of elements in permutation: "))
perm = list(input("Permutation: "))
perm = [ int(x) for x in perm if x != " "]
amount = 1
first = 1
if len(perm) == numbers and int(max(perm)) == numbers and int(min(perm)) == 1:
    if first in perm and len(perm) > 1:
        amount += 1

最佳答案

l = [6, 3, 4, 1, 2, 7, 5]

left_bound = right_bound = l.index(1)

permutations = []

for i in range(1,len(l)+1):
    new_index = l.index(i)

    # special case if i == 1
    if new_index == left_bound == right_bound:
        pass

    # if new index if further to the left, update the left index
    elif new_index < left_bound:
        left_bound = new_index

    # same with the right one
    elif new_index > right_bound:
        right_bound = new_index

    # Because we always have all numbers up to and including i
    # in the list l[left_bound:right_bound+1], we know that if
    # it has not the length i, numbers that are not in the order
    # are in there -> no permutation.
    if len(l[left_bound:right_bound+1])==i:
        permutations.append(l[left_bound:right_bound+1])

print(permutations)

实际上只是用那个例子试了一下,如果有错误请告诉我。

关于python - 计算排列中的排列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74146246/

相关文章:

python - 如何在 Python 中使用 XSLT 转换 XML 文件?

python - Flask SQLAlchemy 无法将表情符号插入 MySQL

r - 如何在R中的分面图中标记最大值点?

algorithm - 如何生成具有均匀分布的随机 DFA?

c# - 在大量数据中快速(子)字符串搜索

python - 使用 python3 而不是 python 运行 Flask

python - ftplib 回调不起作用 - Python 3

r - R 中的迷你图用于 Latex 表(使用 Knitr)

R Shiny 且有计划地获取图例点击事件

algorithm - 使用 if 语句简化 Summation for 循环