python练习之CheckiO-ELEMENTARY小岛

题目网址:https://py.checkio.org/

End Zeros

Try to find out how many zeros a given number has at the end.
Example:
end_zeros(0) == 1
end_zeros(1) == 0
end_zeros(10) == 1
end_zeros(101) == 0

# 参考答案
def end_zeros(num: int) -> int:
    return len(s := str(num)) - len(s.rstrip('0'))
    # 总长度-减去末尾0后剩下的长度=末尾0的长度
if __name__ == '__main__':
    print(end_zeros(100100))
    assert end_zeros(0) == 1

注意:rstrip() 表示删除 string 字符串末尾的指定字符(默认为空格),用法为str.rstrip([chars])

Remove All Before

Not all of the elements are important. What you need to do here is to remove from the list all of the elements before the given one.
example
For the illustration we have a list [1, 2, 3, 4, 5] and we need to remove all elements that go before 3 - which is 1 and 2.
We have two edge cases here: (1) if a cutting element cannot be found, then the list shoudn’t be changed. (2) if the list is empty, then it should remain empty.
Example:
remove_all_before([1, 2, 3, 4, 5], 3) == [3, 4, 5]
remove_all_before([1, 1, 2, 2, 3, 3], 2) == [2, 2, 3, 3]

# 参考答案
def remove_all_before(items, border):
    try:
        return items[items.index(border):]
    except ValueError:
        return items

注意:list[i:]代表获取从下标i到len(list)的元素

All Upper I

Check if a given string has all symbols in upper case. If the string is empty or doesn’t have any letter in it - function should return True.
Example:
is_all_upper(‘ALL UPPER’) == True
is_all_upper(‘all lower’) == False
is_all_upper(‘mixed UPPER and lower’) == False
is_all_upper(’’) == True
is_all_upper(‘444’) == True
is_all_upper(‘55 55 5’) == True

# 参考答案
def is_all_upper(text: str) -> bool:
    # your code here
    return text.upper() == text
if __name__ == '__main__':
    print(is_all_upper('ALL UPPER'))
    assert is_all_upper('ALL UPPER') == True

说明:判断text转化为大写与text本身是否一致,一致为True,不一致为False

Replace First

In a given list the first element should become the last one. An empty list or list with only one element should stay the same.
Example:
replace_first([1, 2, 3, 4]) == [2, 3, 4, 1]
replace_first([1]) == [1]

# 参考答案
def replace_first(items: list) -> list:
    if items:
        items.append(items.pop(0))
    return items
if __name__ == '__main__':
    print(list(replace_first([])))
    assert list(replace_first([1, 2, 3, 4])) == [2, 3, 4, 1]
    assert list(replace_first([1])) == [1]
    assert list(replace_first([])) == []

说明:list.pop()会返回被删除的元素

Split Pairs

Split the string into pairs of two characters. If the string contains an odd number of characters, then the missing second character of the final pair should be replaced with an underscore (’’).
Example:
split_pairs(‘abcd’) == [‘ab’, ‘cd’]
split_pairs(‘abc’) == [‘ab’, 'c
’]

# 参考答案
def split_pairs(a):
    return [ch1+ch2 for ch1,ch2 in zip(a[::2],a[1::2]+'_')]
    # a='abc'时,ch1循环('a','c'),ch2循环('b','_');
    # a='abcd'时,ch1循环('a','c'),ch2循环('b','d');
if __name__ == '__main__':
    print(list(split_pairs('abc')))
    assert list(split_pairs('abcd')) == ['ab', 'cd']
    assert list(split_pairs('abc')) == ['ab', 'c_']
    assert list(split_pairs('a')) == ['a_']
    assert list(split_pairs('')) == []

说明:zip()函数将序列进行组合,形成一个元组序列,然后ch1循环(a[::2])为取偶数,ch2循环(a[1::2]+’*’)为取奇数,故当a的长度是奇数时,(’’)的下标为奇数,ch2会取到(’’),当a的长度是偶数时,(’*’)的下标为偶数,ch2循环就跳过了(’_’)

Nearest Value

Find the nearest value to the given one.
You are given a list of values as set form and a value for which you need to find the nearest one.
For example, we have the following set of numbers: 4, 7, 10, 11, 12, 17, and we need to find the nearest value to the number 9. If we sort this set in the ascending order, then to the left of number 9 will be number 7 and to the right - will be number 10. But 10 is closer than 7, which means that the correct answer is 10.
A few clarifications:
If 2 numbers are at the same distance, you need to choose the smallest one;
The set of numbers is always non-empty, i.e. the size is >=1;
The given value can be in this set, which means that it’s the answer;
The set can contain both positive and negative numbers, but they are always integers;
The set isn’t sorted and consists of unique numbers.
nearest_value({4, 7, 10, 11, 12, 17}, 9) == 10
nearest_value({4, 7, 10, 11, 12, 17}, 8) == 7

# 参考答案
def nearest_value(values: set, one: int) -> int:
    return min(values, key=lambda n: (abs(one - n), n))
if __name__ == '__main__':
    print(nearest_value({4, 7, 10, 11, 12, 17}, 9))
    assert nearest_value({4, 7, 10, 11, 12, 17}, 9) == 10

说明:values为对该数据values进行后续操作
key=lambda n: (abs(one - n), n)解释为:

def func(n):
    return abs(one - n)

返回的key为数组;min()为先对abs(one - n)进行取最小值,当有相同最小绝对值时,对n进行取最小

Correct Sentence

For the input of your function, you will be given one sentence. You have to return a corrected version, that starts with a capital letter and ends with a period (dot).
Pay attention to the fact that not all of the fixes are necessary. If a sentence already ends with a period (dot), then adding another one will be a mistake.
Example:
correct_sentence(“greetings, friends”) == “Greetings, friends.”
correct_sentence(“Greetings, friends”) == “Greetings, friends.”
correct_sentence(“Greetings, friends.”) == “Greetings, friends.”

# 参考答案
def correct_sentence(text: str) -> str:   
    return text[0].upper() + text[1:] + ("." if text[-1] != "." else "")
if __name__ == '__main__':
    print(correct_sentence("greetings, friends"))
    assert correct_sentence("greetings, friends") == "Greetings, friends."
    assert correct_sentence("Greetings, friends") == "Greetings, friends."
    assert correct_sentence("Greetings, friends.") == "Greetings, friends."
    assert correct_sentence("hi") == "Hi."

说明:

if text[-1] != ".":
	return text[0].upper() + text[1:] + "."
else:
	return text[0].upper() + text[1:] + ""

本人很菜,说明主要是用来给自己复习用的,请勿吐槽
若是有写错的地方,欢迎大佬指教~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值