python - 如何获得数组中某物的最短重复?
问题描述
假设您有一个列表,它只有两种类型的值并且类似于['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])
解决方案
这是一个菜鸟和一个 !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))
推荐阅读
- android - Android:Intellij 按钮导航模板创建未使用的空间,隐藏其下的节点
- mongoose-schema - nodejs:mogoose嵌套对象自定义需要和自定义验证
- wso2is - WSO2 身份服务器:无法登录?
- flutter - 计算 SVG 图像的平均颜色 (SvgPicture.network(""))
- c# - 如果刚刚更改了 transform.position,Unity,Rigidbody.MovePosition() 将不起作用
- javascript - 我正在尝试导出我的 npm 包。如何正确地做到这一点?
- django - 尝试使用flutter通过id搜索从API获取数据,而http.get没有解析从API获取的数据
- python - 等效于矩阵的 `log1p`,又名 `logdet_eyep`
- security - 如何以编程方式从 doodrive 下载文件?
- node.js - Mongoose.updateOne() 不更新数据库中的值