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 sum
if __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 Iterable
def 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 False
if __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 Iterable
def replace_first(items: list) -> Iterable:
if len(items)>2:
items.append(items[0])
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([])) == []
# 参考答案
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 list1
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('')) == []
# 参考答案
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 str1
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."
# 参考答案
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:] + ""
本人很菜,说明主要是用来给自己复习用的,请勿吐槽
若有大牛有更好的方法,欢迎大佬留言~~