给定一个纯英文字母组成的单词,我们的任务就是找出其中处在中间位置的字符。如果单词长度为基数,则返回正中位置的单个字符;如果单词长度为偶数,则返回中间的2个字符。
示例:
输入:testing
,输出:t
。
输入:hogwarts
,输出:wa
。
题目难度:简单
题目来源:CodeWars:Get the Middle Character
def solution(words: str) -> str:
# your code here
assert solution("testing") == "t"
assert solution("hogwarts") == "wa"
assert solution("A") == "A"
assert solution("of") == "of"
Kawi
2022 年2 月 10 日 03:14
2
def solution(words: str) -> str:
return words[(len(words) // 2)-1:(len(words) // 2) + 1] if len(words) % 2 == 0 else words[len(words) // 2]
assert solution("testing") == "t"
assert solution("hogwarts") == "wa"
assert solution("A") == "A"
assert solution("of") == "of"
def solution(words: str) -> str:
l = len(words)
if l % 2 == 0:
return words[l // 2 - 1] + words[l // 2]
else:
return words[l // 2]
assert solution("testing") == "t"
assert solution("hogwarts") == "wa"
assert solution("A") == "A"
assert solution("of") == "of"
def solution(words: str) -> str:
l = len(words)
if l % 2 == 0:
return words[l // 2 - 1] + words[l // 2]
else:
return words[l // 2]
assert solution("testing") == "t"
assert solution("hogwarts") == "wa"
assert solution("A") == "A"
assert solution("of") == "of"
def solution(words: str) -> str:
return words[len(words) // 2-1:len(words) // 2 + 1] if len(words) % 2 == 0 else words[len(words) // 2]
assert solution("testing") == "t"
assert solution("hogwarts") == "wa"
assert solution("A") == "A"
assert solution("of") == "of"
def solution(words: str) -> str:
return words[len(words) // 2 - 1] + words[len(words) // 2] if len(words) % 2 == 0 else words[len(words) // 2]
public static String middleword(String words){
if (words.length()%2==0){
return words.substring(words.length()/2-1,words.length()/2+1);
}else {
return words.substring(words.length()/2,words.length()/2+1);
}
}
def solution(words: str) -> str:
if (len_word % 2) != 0:
mid_num = len_word // 2
print(f"这是一个奇数: 中间字母是 '{word[mid_num]}'")
return word[mid_num]
else:
print("这是一个偶数")
mid_num = (len_word // 2) - 1
print(mid_num, mid_num + 2)
print(f"中间的两个字母是 '{word[mid_num:mid_num + 2]}'")
return word[mid_num:mid_num + 2]
def solution(words:str):
if words.isalpha():
l = len(words)
mid_num = l % 2
match mid_num:
case 0:
return words[l//2-1:l//2+1]
case _:
return words[l//2]
else:
return (‘您输入的值非纯英文字母单词,请重新输入’)
assert solution(‘125’) == ‘您输入的值非纯英文字母单词,请重新输入’
assert solution(“testing”) == “t”