首页 > 解决方案 > 我不知道为什么不是我所有重叠的数字都没有被附加到列表中

问题描述

我正在使用二进制搜索编写一个文件重叠函数,该函数采用两个参数:longestFile 和更短的File。我想看看两个文件是否有相同的数字,如果有,它会将该数字附加到一个空列表中。这是我用于程序的两个列表:这是我们需要使用的第一个文件,这是我们需要使用第二个文件

def longestFile(firstFile, secondFile):
   if len(firstFile)>len(secondFile):
      return firstFile
   else:
      return secondFile

def shortestFile(firstFile, secondFile):
   if len(firstFile) < len(secondFile):
      return firstFile
   else:
      return secondFile

def middleNumber(theLongestFile):
   return theLongestFile[len(theLongestFile)//2]

def fileOverlap(lstFirstFile,lstSecondFile):
   lstMatchingNums = []
   lstLongerFile = longestFile(lstFirstFile,lstSecondFile)
   lstShortestFile = shortestFile(lstFirstFile,lstSecondFile)
   for eachLines in range(len(lstShortestFile)):
       lstLongerFile = longestFile(lstFirstFile,lstSecondFile)
       for eachLine in range(len(lstLongerFile)):
          if lstShortestFile[eachLines] == middleNumber(lstLongerFile):
              lstMatchingNums.append(lstShortestFile[eachLines])
              break
          elif lstShortestFile[eachLines] < middleNumber(lstLongerFile):
             lstLongerFile = lstLongerFile[0:(len(lstLongerFile)//2)+1]
             if len(lstLongerFile) <= 2 and lstLongerFile[0] == lstShortestFile[eachLines]:
                 lstMatchingNums.append(lstShortestFile[eachLines])
                 break
             elif middleNumber(lstLongerFile) != lstShortestFile[eachLines] and len(lstLongerFile) <=2:
                 break
          elif lstShortestFile[eachLines] > middleNumber(lstLongerFile):
              lstLongerFile = lstLongerFile[(len(lstLongerFile)//2):]
              if len(lstLongerFile) <= 2 and lstLongerFile[0] == lstShortestFile[eachLines]:
                 lstMatchingNums.append(lstShortestFile[eachLines])
                 break
              elif middleNumber(lstLongerFile) != lstShortestFile[eachLines] and len(lstLongerFile) <= 2:
                 break
  return lstMatchingNums

lstHappyNums = open('happynumbs.txt','r')
lstReadingHappyLines = lstHappyNums.readlines()
lstHappyNums.close()
lstPrimeNumsFile = open('primenumbers.txt', 'r')
lstReadingPrimeLines = lstPrimeNumsFile.readlines()
print(fileOverlap(lstReadingHappyLines,  lstReadingPrimeLines))

如果我运行这个程序,我会得到:['19\n', '193\n', '239\n', '263\n', '293\n', '313\n', '331\n', '367\n', '379\n', '383\n', '397\n', '487\n', '563\n', '617\n', '653\n', '673\n', '683\n', '709\n', '739\n', '761\n', '881\n', '907\n', '937\n']我不知道为什么我会得到部分重叠的数字,而不是全部。我不确定为什么我的二进制搜索对此不起作用。

标签: pythonpython-3.xbinary-search

解决方案


推荐阅读