user5447339
user5447339

Reputation:

check whether an Array contains a particular list of numbers

Given an P of X integers and integer Q, checks whether P contains numbers 1,2,..., Q.

For example given the following array P and Q=3

P[0] = 1
P[1] = 1
P[2] = 2
P[3] = 3
P[4] = 3

The function should return True.

Below is what I have got but I am not sure I got it right or not?

def solution(P, Q):
    n = len(P)
    for i in xrange(n - 1):
        if (P[i] + 1 < P[i + 1]):
            return False
    if (P[0] != 1 and P[n - 1] != Q):
        return False
    else:
        return True

Upvotes: 0

Views: 2698

Answers (3)

md. saroar Jahan
md. saroar Jahan

Reputation: 1

def solution(A, K):
n = len(A)
for i in range(K-1):
    if (A[i] + 1 < A[i + 1]):
        return False
if (A[0] != 1 or A[K - 1] != K):
    return False
else:
    return True

Upvotes: 0

Daniel Fr&#252;hauf
Daniel Fr&#252;hauf

Reputation: 311

As I understood your problem, the array needs to increase with 1 or be the same from i to i+1. Therefore you need to change the sign in the if statement.

def solution(A, K):
    n = len(A)
    for i in xrange(n - 1):
        if (A[i] != A[i + 1] and A[i] + 1 != A[i + 1]):
            return False
    if (A[0] != 1 or A[n - 1] != K):
        return False
    else:
        return True

>>>solution([1,2,3],3)
True
>>>solution([1,2,2,3,3],3)
True
>>>solution([1,2,3],4)
False
>>>solution([1,2,3],2)
False

Upvotes: 1

DYZ
DYZ

Reputation: 57033

Convert your array to a set and compare the set to a set of all integer numbers between 1 and K:

set(A)==set(range(1,K+1))

As an added bonus, A does not have to be sorted anymore.

Upvotes: 3

Related Questions