【问题标题】:Is there a way to get the starts and ends of numbers between a split from an array?有没有办法在数组拆分之间获取数字的开始和结束?
【发布时间】:2021-01-18 13:15:32
【问题描述】:

对不起,我什至不知道给这个问题起什么标题。

我有一组我称之为页的数字。

它们是我需要从浏览器物理打印出来的页面。

pagesToPrint = [2,3,4,5,7,8,9,12,14,15,16,17,18,19,20]

现在,只打印2,3,4,5,7...20 有什么问题?

当一页或多页被发送到打印机时,发送和处理需要一段时间。因此,为了加快流程,最好只分批打印。说不是打印2-23-34-4,而是打印2-5,我们不能打印2-20,因为它会打印页面6,10,11,13等等。

我真的不在乎答案是哪种编程语言,而是它背后的逻辑。 最终我试图在 AutoHotkey 中解决这个问题。

【问题讨论】:

标签: python autohotkey


【解决方案1】:

你可以通过一些“自上而下”的思考来解决这个问题。在理想情况下,已经有一个可以调用的函数:split_into_consecutive_batches(pages)

的层面上,你会如何描述它是如何工作的?这基本上只是对您最初的帖子和要求的稍微更精确的改写!

“只要页面列表中还有页面,它就应该给我下一批。”

啊哈!

def split_into_consecutive_batches(pages):
  batches = []
  while pages:
    batches.append(grab_next_batch(pages))

  return batches

啊哈!那不是那么糟糕,对吧?大的整体问题现在被简化为一个更小、更简单的问题。我们如何获取下一批?好吧,我们抓住第一页。然后我们检查下一页是否是连续页面。如果是,我们将其添加到批处理中并继续。如果没有,我们认为批处理完成并停止:

def grab_next_batch(pages):
  first_page = pages.pop(0)  # Grab (and delete) first page from list.
  batch = [first_page]

  while pages:
    # Check that next page is one larger than the last page in our batch:
    if pages[0] == batch[-1] + 1:
      # It is consecutive! So remove from pages and add to batch
      batch.append(pages.pop(0))
    else:
      # Not consecutive! So the current batch is done! Return it!
      return batch
  # If we made it to here, we have removed all the pages. So we're done too!
  return batch

应该这样做。虽然可以稍微清理一下;也许您不喜欢从页面列表中删除项目的副作用。而不是复制你周围的东西可以找出索引。我会把它留作练习:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    相关资源
    最近更新 更多