0

I have a simple class where one method is to get the index of a list for s specified value given that it contains the value. The method is the get_index_at_time(time) in the class below

class TimeStamp:
   def __init__(self):
      self.timeList = []
      self.indexList = []
      self.localDate = None

   def add(self, inTime, idx):
      if self.localDate is None:
         # Get todays date
         self.localDate = datetime.datetime.now()
      # Fix timeList with time adjusted to inTime
      thisTime = create_timestamp(self.localDate, inTime)
      self.timeList.append(thisTime)
      self.indexList.append(idx)

   def get_time_at_index(self, ix):
      if len(self.timeList) > ix and 0 <= ix:
         return self.timeList[ix]

   def get_index_at_time(self, inTime):
      ix = self.timeList.index(inTime)
      if ix:
         return self.indexList[ix]
      else:
         return -1

This fails for some strange reason for the first element in the list, e.g. index 0 but I have checked that the index method on a list with same data works for index 0 it is only when used inside the class it behaves strange.

Running the script gives this:

$ python3 simple_index_test.py 

====================================================
Testing list index method for dbgList:
Test passed
====================================================
Start testing TimeStamp.get_time_at_index
Test passed
====================================================
Start testing TimeStamp.get_index_at_time
 - Test Failed for time stamp: 2020-04-12 01:01:01
====================================================
Comparing the values in dbgList with idx1.TimeList
Test passed
====================================================

Here is the code:

import datetime

def create_timestamp(localDate, inTime):
   timeString = localDate.strftime('%Y-%m-%d') + ' ' + inTime
   return datetime.datetime.strptime(timeString, '%Y-%m-%d %H:%M:%S')

class TimeStamp:
   def __init__(self):
      self.timeList = []
      self.indexList = []
      self.localDate = None

   def add(self, inTime, idx):
      if self.localDate is None:
         # Get todays date
         self.localDate = datetime.datetime.now()
      # Fix timeList with time adjusted to inTime
      thisTime = create_timestamp(self.localDate, inTime)
      self.timeList.append(thisTime)
      self.indexList.append(idx)

   def get_time_at_index(self, ix):
      if len(self.timeList) > ix and 0 <= ix:
         return self.timeList[ix]

   def get_index_at_time(self, inTime):
      ix = self.timeList.index(inTime)
      if ix:
         return self.indexList[ix]
      else:
         return -1

log1 = [
   [0.123, '01:01:01', 0],
   [0.134, '01:01:02', 1],
   [0.145, '01:01:03', 1],
   [0.156, '01:01:04', 2],
   [0.167, '01:01:05', 2],
   [0.178, '01:01:06', 2],
   [0.189, '01:01:07', 3],
]

def main():
   # Get todays date
   localDate = datetime.datetime.now()
   idx1 = TimeStamp()
   # debug list for testing the index method directly
   dbgList = []
   # Fill idx1
   for ix,val in enumerate(log1):
      idx1.add(val[1], ix)
      # Debugging why test fails, create an identical list of same time stamp as in the TimeStamp class
      thisTime = create_timestamp(localDate, val[1])
      dbgList.append(thisTime)

   print('====================================================')
   print('Testing list index method for dbgList:')
   testPassed = True
   for ix, val in enumerate(dbgList):
      rx = dbgList.index(val)
      if rx != ix:
         print('List index() method failed match for: ' + str(val))
         testPassed = False
   if testPassed:
      print('Test passed')
   # Test method get_time_at_index
   print('====================================================')
   print('Start testing TimeStamp.get_time_at_index')
   testPassed = True
   # Loop over all elements in log1
   for ix,val in enumerate(log1):
      thisTime = idx1.get_time_at_index(ix)
      # Create the expected time stamp
      expectedTime = create_timestamp(localDate, val[1])
      if thisTime != expectedTime:
         print(' - Test Failed for index: ' + str(ix))
         testPassed = False
   if testPassed:
      print('Test passed')
   # Test method get_index_at_time
   print('====================================================')
   print('Start testing TimeStamp.get_index_at_time')
   testPassed = True
   # Loop over all elements in log1
   for ix,val in enumerate(log1):
      # Create the time we want to get index for
      wantedTime = create_timestamp(localDate, val[1])
      thisIndex = idx1.get_index_at_time(wantedTime)
      if thisIndex != ix:
         print(' - Test Failed for time stamp: ' + str(wantedTime))
         testPassed = False
   if testPassed:
      print('Test passed')
   print('====================================================')
   print('Comparing the values in dbgList with idx1.TimeList')
   testPassed = True
   for ix, val in enumerate(dbgList):
      idxTimeStamp = idx1.timeList[ix]
      if idxTimeStamp != val:
         print(' - Test Failed for time stamps (dbg) (idx1.timeList): ' + str(val) + ' ' + str(idxTimeStamp))
         testPassed = False
   if testPassed:
      print('Test passed')
   print('====================================================')


if __name__ == "__main__":
   main()

IgorLopez
  • 157
  • 1
  • 1
  • 10

1 Answers1

0

I see this problem just happend with first index(index-0). If you print thisIndex(at testing TimeStamp.get_index_at_time) variabel, that will be -1 for first loop.

See at your get_index_at_time() function. That happen because if statement will return False for 0. So, the function will return -1. U can fix add one more condition for if. Here we go:

def get_index_at_time(self, inTime):
      ix = self.timeList.index(inTime)
      if ix or ix == 0:
         return self.indexList[ix]
      else:
         return -1

The output will be:

====================================================
Testing list index method for dbgList:
Test passed
====================================================
Start testing TimeStamp.get_time_at_index
Test passed
====================================================
Start testing TimeStamp.get_index_at_time
Test passed
====================================================
Comparing the values in dbgList with idx1.TimeList
Test passed
====================================================

(Sorry bad english)

Ilya Trianggela
  • 305
  • 1
  • 9