PYTHON   64
secondLargest
Guest on 13th September 2023 02:10:32 PM


  1. def secondLargest(L):
  2.     return secondLargestHelper(L, None, None)
  3.  
  4. def secondLargestHelper(L, largest, secondLargest):
  5.     if L == []:
  6.         return secondLargest
  7.     first = L[0]
  8.     rest = L[1:]
  9.     if largest == None or first > largest:
  10.         secondLargest = largest
  11.         largest = first
  12.     elif secondLargest == None or (first > secondLargest):
  13.         secondLargest = first
  14.     return secondLargestHelper(rest, largest, secondLargest)
  15.  
  16. def vowelRun(s):
  17.     if s == '' or s[0] not in "aeiouAEIOU":
  18.         return 0
  19.     else:
  20.         return 1 + vowelRun(s[1:])
  21.  
  22. def longestVowelRun(s):
  23.     if s == '':
  24.         return 0
  25.     vowelLength = vowelRun(s)
  26.     bestRun = longestVowelRun(s[1:])
  27.     if vowelLength > bestRun:
  28.         return vowelLength
  29.     return bestRun
  30.  
  31. def testSecondLargest():
  32.     print('Testing secondLargest()...', end= '')
  33.     assert(secondLargest([2, 5, 3, 4, 1]) == 4)
  34.     assert(secondLargest([6, 5, 6, 6, 6]) == 6)
  35.     assert(secondLargest([1]) == None)
  36.     assert(secondLargest([]) == None)
  37.     assert(secondLargest([2, 24, 120, 39]) == 39)
  38.     print("Passed!")
  39.  
  40. def testLongestVowelRun():
  41.     print('Testing longestVowelRun()...', end= '')
  42.     assert(longestVowelRun('AbcAeiD aEoa ba') == 4)
  43.     assert(longestVowelRun('cnsnts') == 0)
  44.     assert(longestVowelRun('aeiouAEIOU') == 10)
  45.     assert(longestVowelRun('') == 0)
  46.     print("Passed!")
  47.  
  48. testSecondLargest()
  49. testLongestVowelRun()

Raw Paste

Login or Register to edit or fork this paste. It's free.