简体   繁体   English

如何返回任意两个字母之间的最大距离(az 忽略大小写)?

[英]How to return the biggest distance between any two letters (a-z ignoring case)?

I'm trying to return a function which takes a string as input and returns the biggest distance between any two letters (az ignoring case).我正在尝试返回一个函数,该函数将字符串作为输入并返回任意两个字母之间的最大距离(az 忽略大小写)。 Distance in this case means the number of letters apart in the alphabet.在这种情况下,距离是指字母表中相隔的字母数。 Eg Distance between "a" and "b" is 1. Should I be using string.index or chr and ord ?例如,“a”和“b”之间的距离是 1。我应该使用string.index还是chrord

My code so far:到目前为止我的代码:

def biggest_letter_distance(string):
    dist = [chr(i) for i in range(ord('a'),ord('z')+1)]
    return dist    

What I'm trying to test on:我正在尝试测试的内容:

assert(biggest_letter_distance("Hello World") == 19)
assert(biggest_letter_distance("!!") == -1)
def biggest_letter_distance(string):
    string = [char.lower() for char in string if char.isalpha()]
    if not string:
        return -1
    letters = sorted(set(string))
    return ord(letters[-1]) - ord(letters[0])

Explaining:解释:

  1. Selects only the alphabetic characters and turns them to lowercase.仅选择字母字符并将它们转换为小写。
  2. Orders the selection订购选择
  3. Returns the distance between the first and last items返回第一个和最后一个项目之间的距离

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何用python删除字母[AZ] - How to delete letters [A-Z] with python 如何在python 3中创建所有字母(az)的txt频率计数器 - How to create txt frequency counter with all letters (a-z) in python 3 如果我只按任何字母(AZ,az)或数字(0 - 9),如何将焦点从 QListWidget 更改为 QLineEdit? - How to Change the Focus from QListWidget to QLineEdit, If I press only any Alphabets (A-Z, a-z) or numbers(0 - 9)? 两个 excel 文件的 AZ 排序不同 - A-Z sorting is different between two excel files 如何使用 re.sub() 只留下字母 az、AZ、数字 0-9 和空格而不是除数? - How to use re.sub() to leave only letters a-z, A-Z, numbers 0-9 and spaces but not divide numbers? 使用句子中的字符(字母和标点符号)以及每个字符出现的频率创建一个有序列表 (az) - Create a ordered list (a-z) with the characters (letters and punctuation) in the sentence and how often each character appears Python Regex用于忽略具有两个连续大写字母的句子 - Python Regex for ignoring a sentence with two consecutive upper case letters 如何忽略[az] [AZ]以外的字符 - how to Ignore characters other than [a-z][A-Z] Python:在给定单词的每个字母后添加多个随机字母(AZ;az)? - Python: add a number of random letters (A-Z; a-z) after each letter in a given word? 如何使用python中的返回方法计算两点之间的距离? - How to calculate the distance between two points using return methods in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM