gpt4 book ai didi

python - 计算排列中的排列数

转载 作者:行者123 更新时间:2023-12-05 05:32:23 24 4
gpt4 key购买 nike

一个大小为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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com