# More examples of arrays, strings, loops and functions. #Here is a function that tests if an array is sorted (in increasing order): def sorted(A): # True iff A is sorted answer = True # forall type of problem: the empty list is sorted i = 0 while answer and iA[i+1]: answer = False i += 1 #while return answer #sorted. # Given an array such as A = [2,4,6,8], the built-in operation A.insert(2,9) # will insert 9 into position 2 in A, shifting other values downwards. A # becomes [2,4,9,6,8]. This operation is destructive like append. # the following function inserts a number into a sorted array and keeps it # sorted: def sortedinsert(x,A): # destructive insert x into sorted array A i = 0 # index A inserted = False # will stop array while not(inserted) and i6): return "invalid" else: return DofW[n] #numtoday print numtoday(3) # should print "Wednesday" ## Another example on strings: the following function loops through a # string and retuns a list/array of vowels. Vowels = ["a","e","i","o","u","A","E","I","O","U"] def findvowels(s): # return list of vowels in string s V = [] # array to be built (of unknown size) i = 0 # indexes s while i=ord('A') and asci <= ord('Z'): # is upper case letter asci = asci + 32 # convert to ascii value of lower case letter # asci stays unchanged if not upper case letter ax = ax + chr(asci) # add char to string being built i += 1 #while return ax #lower_case # The following function tests if two strings are equal regardless of case: def nceq(s,t): # returns True iff strings s and t are equal regardless of case return lower_case(s) == lower_case(t) #nceq # The above function is slightly inefficient because it needs to traverse # the strings three times: one on s, one on t and one when testing for ==. # It also uses more memory because it builds two new strings, although the # memory will be reclaimed when the function call ends. The following # is slightly more efficient, but more difficult to write. To make things # simpler first I will define a function to check if two individual characters # are equal regardless of case: def eqchar(a,b): # True iff a an b are equal regardless of case ac,bc = ord(a),ord(b) # get ascii values if (ac>=65 and ac<=90): ac += 32 # convert value to lower case if (bc>=65 and bc<=90): bc += 32 # convert value to lower case return ac == bc # eqchar def nceq2(s,t): if len(s)!=len(t): return False answer = True # this is a FORALL type of function i = 0 # indexes s and t while answer and i