gpt4 book ai didi

python - 检查一个字符串的字符是否按字母顺序升序并且它的升序是均匀间隔的python

转载 作者:行者123 更新时间:2023-11-28 20:09:49 24 4
gpt4 key购买 nike

因此需要检查字符串的字符是否按字母顺序升序以及升序是否均匀分布。

a = "abc"
b = "ceg"

所以 a 是按字母顺序升序的,它的间距是 1(如果你转换为序数值,它们是 97,98,99)。而 b 也是按字母顺序升序,它的间距是 2 (99,101,103)。

我坚持使用以下代码:

a = 'jubjub'
words1 = []
ords = [ord(letter) for letter in a]
diff = ords[1] - ords[0]
for ord_val in range(1, len(ords)-1):
if diff > 0:
if ords[ord_val + 1] - ords[ord_val] == diff:
if a not in words1:
words1.append((a, diff))
print words1

为什么 'jubjub' 有效,'ace' 有效,但 'catcat' 无效?

最佳答案

>>> from itertools import product
>>> from string import lowercase
>>> a="abc"
>>> any(a in lowercase[i::j+1] for i,j in product(range(26),repeat=2))
True
>>> b="ceg"
>>> any(b in lowercase[i::j+1] for i,j in product(range(26),repeat=2))
True
>>> c="longer"
>>> any(c in string.lowercase[i::j+1] for i,j in product(range(26),repeat=2))
False
>>> d="bdfhj"
>>> any(d in string.lowercase[i::j+1] for i,j in product(range(26),repeat=2))
True

不需要用product,这样做效率会高一点

>>> any(a in string.lowercase[i::j+1] for i in range(26) for j in range(26-i))
True

关于python - 检查一个字符串的字符是否按字母顺序升序并且它的升序是均匀间隔的python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9922436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com