首页 > 解决方案 > 如何获得数组中某物的最短重复?

问题描述

假设您有一个列表,它只有两种类型的值并且类似于['t','r','r','r','t','t','r','r','t']并且您想找到两端'r'都有s 的最小序列号的长度。't'

在这种情况下,最小的序列的'r'长度为 2,因为有 firstt,r,r,r,t和 then t,r,r,t,,而后者'r'在被包围的一行中的 s数量最少,'t'并且 s 的数量'r'为 2。

我将如何编码以查找该号码?

这是由于尝试与朋友一起去看戏的问题,并且您希望与朋友坐得尽可能近,因此您试图在一场比赛中的两个空闲座位之间找到最少的被占用座位。“#”是一个已坐的座位和一个“。” 是免费座位。给你座位数量和座位安排(免费座位和占用座位),它们都在一条线上。输入的一个例子是:

5
#.##.

在两个空闲座位之间有两个座位(##)。

这是我的代码,它不适用于我不知道的输入,但适用于我抛出的输入。

import sys

seats = int(input())
configuration = input()
seatsArray = []
betweenSeats = 1
betweenSeatsMin = 1
checked = 0
theArray = []
dotCount = 0
for i in configuration:
  seatsArray.append(i)

for i in range(len(seatsArray)):
  if i == len(seatsArray) - 1:
    break
  if seatsArray[i] == "." and seatsArray[i+1] == ".":
    print(0)
    sys.exit()

for i in range(0,len(seatsArray)):
  if i > 0:
    if checked == seats:
      break
  checked += 1
  if seatsArray[i] == "#":
    if i > 0:
      if seatsArray[i-1] == "#":
        betweenSeats += 1

  if seatsArray[i] == ".":
    dotCount += 1
    if dotCount > 1:
      theArray.append(betweenSeats)
    betweenSeats = 1

theArray = sorted(theArray)
if theArray.count(1) > 0:
  theArray.remove(1)
theArray = list(dict.fromkeys(theArray))

print(theArray[0])

标签: pythonlist

解决方案


这是一个菜鸟和一个 !optimal 方法来解决您的问题,使用计数器来计算最小和最大序列,其中 ew 比较两者并返回最小值。

''' create a funciton that
    will find min sequence
    of target char
    in a list'''
    
def finder(a, target):
    max_counter = 0
    min_counter = 0

    ''' iterate through our list
    and if the element is the target
    increase our max counter by 1 
    '''
    for i in x:
        if i == target:
            max_counter += 1
            
            '''min here is 0
            so it will always be less
            so we overwrite it's value
            with the value of max_counter'''
            if min_counter < max_counter:
                min_counter = max_counter

            '''at last iteration max counter will be less than min counter
            so we overwrite it'''
            if max_counter < min_counter:
                min_counter = max_counter
    
        else:

            max_counter = 0
    return min_counter


x = ['t','r','r','r','t','t','r','r','t','t','t','r','t'] 
y = 'r'
print(finder(x,y))

推荐阅读