检查字符串是否在abc ord中

2024-09-30 01:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,函数应该计算大写字母不按abc顺序排列的次数。在

>>> abc('ABBZHDL')
    2

上面,z和d坏了。在

^{pr2}$

我的代码:

 def abc(check):
 order=ABCDEFGHIJKLMNOPQRSTUVWXYZ
   for c in check:
      if check != order:
   #then I get stuck here

指针?在


Tags: 函数代码inforifdefcheckorder
3条回答
def abc(check):
   last = ''
   count = 0
   for letter in check:
      if not letter.isupper():
           continue
      if letter < last:
           count += 1
      last = letter
   return count 
import string

a = 'acbdefr'
b = 'abdcfe'

assert ''.join(sorted(b)) in string.ascii_letters
assert ''.join(sorted(a)) in string.ascii_letters #should fail

它真的很简单每个人似乎都有点过分复杂?在

这个问题界定不清。附近问题的一个解决方案是使用内置sorted():

def abc(s):
    count = 0
    s = ''.join(i for i in s if i.isupper())
    l = sorted(s)
    for i,c in enumerate(s):
        if l[i] != c:
            count += 1
    return count

它统计按字母顺序排列的字符串与原始字符串不匹配的所有位置。在

相关问题 更多 >

    热门问题