A non-empty array A
consisting of N
integers is given.
A permutation is a sequence containing each element from 1 to N
exactly once each.
For example, [4,2,1,3]
is a permutation, but [4,1,3]
is not a permutation, because value 2
is missing.
The goal is to check whether the input array A
is a permutation.
constraints
A
is an integer within the range [1..1,000,000,000].My code:
# 1 = permutation 0 = not a permutation
def solution(A):
total = sum(A)
formula_total = (len(A)*(len(A)+1))/(2)
if total == formula_total:
return 1
return 0
my solution is failing on Antisum (I don't know what that is )
You can then check if the minimum value of the list is 1 and if the maximum value is equal to the length of the list. You can then convert the list to a set to check if the length is equal, and if so, all items in the list are unique and therefore the list is what you consider a permutation:
def solution(A):
return min(A) == 1 and max(A) == len(A) == len(set(A))
so that:
print(solution([4,2,1,3]))
print(solution([4,1,3]))
print(solution([4,2,1,4]))
print(solution([4,2,5,3]))
outputs:
True
False
False
False
If you want 1
and 0
as the returning value you can pass the Boolean value to the int()
constructor instead:
def solution(A):
return int(min(A) == 1 and max(A) == len(A) == len(set(A)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With