Dakota Brown
Dakota Brown

Reputation: 57

Check 2D list for containing only 2 specific values

I need to check a 2d array to ensure that it only contains 2 specific characters.

Assume I have this in a 2d array stored in a list called (data):

**%****%%%***
%***%*%%****%
****%%%$*****

I need to validate that the array only contains ('*', '%') If it contains any other value such as ('$'), it needs to return false and print a statement to the user.

I tried using forall but could not get it to work with a 2d array.

Also in Python 3x

Upvotes: 0

Views: 25

Answers (1)

Abhijith Asokan
Abhijith Asokan

Reputation: 1875

data = [ '**%****%%%***', '%***%*%%****%', '****%%%$*****' ]
result = all( (len(x) == x.count('*') + x.count('%')) for x in  data)

I have represented the 2D array here as list of strings.

If you change the representation to list of lists, it will still work (as count function is available for both str and list).

Upvotes: 1

Related Questions