9 Matching Annotations
  1. Oct 2022
    1. Write a function revstring(mystr) that uses a stack to reverse the characters in a string. Save & RunShow FeedbackShow CodetestEqual(revstring('1234567890'),'0987654321') 1from test import testEqual2from pythonds.basic import Stack3​4def revstring(mystr):5 # your code here6​7testEqual(revstring('apple'),'elppa')8testEqual(revstring('x'),'x')9testEqual(revstring('1234567890'),'0987654321')10​

      def revstring(s): sta = Stack() for i in range(0, len(s)): sta.push(s[i])

      outputstr = ''
      while not sta.isempty(): 
          outputstr = outputstr + sta.pop()
      return outputstr
      
    1. Given a list of numbers in random order, write an algorithm that works in O(nlog⁡(n)) to find the kth smallest number in the list.

      def findLargestIndex(l): x = 0 for i in range(0, len(l)): if l[i] > x: x = l[i] x_index = i return x_index

      def klsearch(l, k): kl = l[0:k] ind = findLargestIndex(kl)

      for i in range(k, len(l)): 
          if l[i] < kl[ind]:
              kl[ind] = l[i]
              ind = findLargestIndex(kl)
      
      return kl[ind]
      
    2. Devise an experiment to verify that the list index operator is

      import timeit

      test = timeit.Timer("lt[50] == 50", "from main import lt") for i in range(1000, 10000): lt = list(range(0, i)) lttime = test.timeit(number=1000) print(lttime)