Ask Your Question
1

Checking that all values in an array satisfy an inequality

asked 6 years ago

anonymous user

Anonymous

I would like to know how to check element-wise that every entry in an array is less than or equal to a particular number. It would seem that something like this would require a loop, but I am not sure. Could someone help me? Thank you in advance

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
1

answered 6 years ago

tmonteil gravatar image

updated 6 years ago

You can use any of all as follows:

sage: L = [1,2,3,4,5]
sage: all(x < 10 for x in L)
True

sage: all(x < 3 for x in L)
False

sage: any(x < 3 for x in L)
True
Preview: (hide)
link
1

answered 6 years ago

rburing gravatar image

updated 6 years ago

No explicit loop is necessary; you can use a generator expression in combination with all. If L is the list and c is the particular number, you can do:

all(el <= c for el in L)
Preview: (hide)
link

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 6 years ago

Seen: 517 times

Last updated: Feb 01 '19