Using JavaScript create the following functions: E. A function called median, th
ID: 3847921 • Letter: U
Question
Using JavaScript create the following functions:
E. A function called median, that accepts three values and returns the median. The median of three values is the value that is greater than or equal to one of the other values and less than or equal to the remaining value.
f. A function called numberOfZeroes that returns the number of zeros in a given array. For example, the call numberOfZeroes([4, 0, false, 5, 0]) should return 2.
g. A function called cntOccurrences, that returns the number of occurrences of a given character in a string. For example, given the string "Rat-a-tat-tat" and the character t, your function should return 5.
h. A function called isPrime, that takes an array of numbers and returns an array containing the numbers that are prime. For example. The call isPrime([1, 5, 17, 25, 30]) should return [1, 5, 17].
Explanation / Answer
#e
def median(lst):
sortedLst = sorted(lst)
lstLen = len(lst)
index = (lstLen - 1) // 2
if (lstLen % 2):
return sortedLst[index]
else:
return (sortedLst[index] + sortedLst[index + 1])/2.0
#f
def numberOfZeroes(lst):
count=0
for val in lst:
if val==0:
count+=1
return count
#g
def cntOccurrences(string,char):
count=0
for ch in string:
if ch==char:
count+=1
return count
#h
def isPrime(lst):
prime_lst=[]
for val in lst:
if val > 1:
for i in range(2,val):
if (val % i) == 0:
break
else:
if val not in prime_lst:
prime_lst.append(val)
return prime_lst
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.