I have the following arrays:
passing_grades = ["A", "B", "C", "D"]
student2434 = ["F", "A", "C", "C", "B"]
and I need to verify that all elements in the student
array are included in the passing_grades
array. In the scenario above, student2434
would return false. But this student:
student777 = ["C", "A", "C", "C", "B"]
would return true
. I tried something like:
if student777.include? passing_grades then return true else return false end
without success. Any help is appreciated.
includes() You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.
One simple solution is to use two nested loops. For every element, check if it repeats or not. If any element repeats, return false. If no element repeats, return false.
Use numpy. isin() to find the elements of a array belongs to another array or not. it returns a boolean array matching the shape of other array where elements are to be searched. numpy.
PASSING_GRADES = ["A", "B", "C", "D"]
def passed?(grades)
(grades - PASSING_GRADES).empty?
end
similar to what CDub had but without bug. more readable in my opinion
You could have a method that does the difference of the arrays, and if any results are present, they didn't pass:
PASSING_GRADES = ["A", "B", "C", "D"]
def passed?(grades)
grades.all? {|grade| PASSING_GRADES.include?(grade)}
end
Example:
1.9.3-p484 :117 > student777 = ["C", "A", "C", "C", "B"]
=> ["C", "A", "C", "C", "B"]
1.9.3-p484 :118 > passed?(student777)
=> true
1.9.3-p484 :118 > passed?(student2434)
=> false
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