python练习之CheckiO-ELEMENTARY小岛

python练习之CheckiO-ELEMENTARY小岛,第1张

概述EndZerosTrytofindouthowmanyzerosagivennumberhasattheend.Example:end_zeros(0)==1end_zeros(1)==0end_zeros(10)==1end_zeros(101)==0#我的答案defend_zeros(num:int)->int:#yourcodeherenum=str(num)llen=len(num) 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:    # your code here    num=str(num)    llen=len(num)    sum=0    for i in range(llen):        if num[llen-1]!='0':            break        elif i > 0:            if num[llen-i]=='0' and num[llen-i-1]=='0':                sum+=1                continue            elif num[llen-i]=='0' and num[llen-i-1]!='0':                sum+=1                break        elif i==0 and num[i]=='0':            sum+=1    return sumif __name__ == '__main__':    print(end_zeros(100100))    assert end_zeros(0) == 1
# 参考答案def end_zeros(num: int) -> int:    return len(s := str(num)) - len(s.rstrip('0'))    # 总长度-减去末尾0后剩下的长度=末尾0的长度

注意: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]

# 我的答案from tyPing import Iterabledef remove_all_before(items: List, border: int) -> Iterable:    # your code here    List1=[]    for i in range(len(items)):        if items[i]==border:            for j in range(i,len(items)):                List1.append(items[j])            break        elif border not in items:            return items    return List1
# 参考答案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    text=text.replace(' ','')    if text=='':        return True    elif text.isupper()==True:            return True    elif text.isdigit()==True:        return True    else:        return Falseif __name__ == '__main__':    print(is_all_upper('ALL UPPER'))    assert is_all_upper('ALL UPPER') == True
# 参考答案def is_all_upper(text: str) -> bool:    # your code here    return text.upper() == text

说明:判断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]

# 我的答案from tyPing import Iterabledef replace_first(items: List) -> Iterable:    if len(items)>2:        items.append(items[0])        items.pop(0)    return itemsif __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([])) == []
# 参考答案def replace_first(items: List) -> List:    if items:        items.append(items.pop(0))    return items

说明: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):    a=List(a)    List1=[]    for i in range(0,len(a),2):        if i+1 < len(a):            if len(a) % 2==1:                a.append('_')            List1.append(''+a[i]+a[i+1])        if len(a)==1:            a.append('_')            List1.append(a[0]+'_')            break        if len(a)==0:            return a    return List1if __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('')) == []
# 参考答案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');

说明: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:    # your code here    values = List(values)    values.sort()    if one <= values[0]:        return values[0]    elif one >= values[len(values)-1]:        return values[len(values)-1]    else:        for i in range(len(values)):            if values[i]==one:                return one                break            elif values[i]>one and values[i-1]<one:                if values[i]-one>=one-values[i-1]:                    return values[i-1]                    break                else:                    return values[i]                    break  if __name__ == '__main__':    print(nearest_value({4, 7, 10, 11, 12, 17}, 9))    assert nearest_value({4, 7, 10, 11, 12, 17}, 9) == 10
# 参考答案def nearest_value(values: set, one: int) -> int:    return min(values, key=lambda n: (abs(one - n), n))

说明: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:    # your code here    text=List(text)    str1=''    for i in range(len(text)):        if i==0 and text[i].isupper()==False:            text[i] = text[i].upper()        if i==len(text)-1 and text[len(text)-1]!='.':            text.append('.')               for j in range(len(text)):        str1 = str1 + text[j]         return str1if __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."
# 参考答案def correct_sentence(text: str) -> str:       return text[0].upper() + text[1:] + ("." if text[-1] != "." else "")

说明:

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

本人很菜,说明主要是用来给自己复习用的,请勿吐槽
若有大牛有更好的方法,欢迎大佬留言~~

总结

以上是内存溢出为你收集整理的python练习之CheckiO-ELEMENTARY小岛全部内容,希望文章能够帮你解决python练习之CheckiO-ELEMENTARY小岛所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1184830.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存