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 (’’). 将字符串分割为两个字符对。如果字符串包含奇数个字符,那么最后一对中缺失的第二个字符应该用下划线(’’)替换。
Input: A string.
Output: An iterable of strings.
Example:
split_pairs(‘abcd’) == [‘ab’, ‘cd’] split_pairs(‘abc’) == [‘ab’, ‘c_’]
Precondition: 0<=len(str)<=100
def split_pairs(a):
res = []
num = len(a)//2
for i in range(num):
res.append(a[0:2])
a = a[2:]
if a != '':
res.append(a+'_')
return res
if __name__ == '__main__':
print("Example:")
print(list(split_pairs('abcd')))
assert list(split_pairs('abcd')) == ['ab', 'cd']
assert list(split_pairs('abc')) == ['ab', 'c_']
assert list(split_pairs('abcdf')) == ['ab', 'cd', 'f_']
assert list(split_pairs('a')) == ['a_']
assert list(split_pairs('')) == []
print("Coding complete? Click 'Check' to earn cool rewards!")
def split_pairs(a):
a += '_' if len(a) % 2 else ''
return [a[i:i + 2] for i in range(0, len(a), 2)]
def split_pairs(a):
return [ch1+ch2 for ch1,ch2 in zip(a[::2],a[1::2]+'_')]
Beginning Zeros
You have a string that consist only of digits. You need to find how many zero digits (“0”) are at the beginning of the given string. 你有一个只由数字组成的字符串。需要找到在给定字符串的开头有多少个零(“0”)。
Input: A string, that consist of digits.
Output: An Int.
Example:
beginning_zeros(‘100’) == 0 beginning_zeros(‘001’) == 2 beginning_zeros(‘100100’) == 0 beginning_zeros(‘001001’) == 2 beginning_zeros(‘012345679’) == 1 beginning_zeros(‘0000’) == 4
Precondition: 0-9
def beginning_zeros(number: str) -> int:
return len(number)-len(number.lstrip('0'))
if __name__ == '__main__':
print("Example:")
print(beginning_zeros('100'))
assert beginning_zeros('100') == 0
assert beginning_zeros('001') == 2
assert beginning_zeros('100100') == 0
assert beginning_zeros('001001') == 2
assert beginning_zeros('012345679') == 1
assert beginning_zeros('0000') == 4
print("Coding complete? Click 'Check' to earn cool rewards!")
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.
Input: Two arguments. A list of values in the set form. The sought value is an int.
Output: Int.
Example:
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:
values = sorted(values)
le = len(values)
if one < values[0]:
return values[0]
if one > values[-1]:
return values[-1]
while(1):
if one <= values[len(values)//2]:
if one >= values[len(values)//2-1]:
return values[len(values)//2] if abs(one-values[len(values)//2]) < abs(one-values[len(values)//2-1]) else values[len(values)//2-1]
else:
values = values[:len(values)//2]
else:
if one <= values[len(values) // 2 + 1]:
return values[len(values)//2] if abs(one-values[len(values)//2]) <= abs(one-values[len(values)//2+1]) else values[len(values)//2+1]
else:
values = values[len(values) // 2:]
if __name__ == '__main__':
print("Example:")
print(nearest_value({4, 7, 10, 11, 12, 17}, 9))
assert nearest_value({4, 7, 10, 11, 12, 17}, 9) == 10
assert nearest_value({4, 7, 10, 11, 12, 17}, 8) == 7
assert nearest_value({4, 8, 10, 11, 12, 17}, 9) == 8
assert nearest_value({4, 9, 10, 11, 12, 17}, 9) == 9
assert nearest_value({4, 7, 10, 11, 12, 17}, 0) == 4
assert nearest_value({4, 7, 10, 11, 12, 17}, 100) == 17
assert nearest_value({5, 10, 8, 12, 89, 100}, 7) == 8
assert nearest_value({-1, 2, 3}, 0) == -1
print("Coding complete? Click 'Check' to earn cool rewards!")
def nearest_value(values: set, one: int) -> int:
return min(sorted(values), key = lambda i: abs(i - one))
Between Markers (simplified)
You are given a string and two markers (the initial one and final). You have to find a substring enclosed between these two markers. But there are a few important conditions.
This is a simplified version of the Between Markers mission.
- The initial and final markers are always different.
- The initial and final markers are always 1 char size.
- The initial and final markers always exist in a string and go one after another.
Input: Three arguments. All of them are strings. The second and third arguments are the initial and final markers.
Output: A string.
Example:
between_markers(‘What is >apple<’, ‘>’, ‘<’) == ‘apple’
How it is used: For text parsing.
Precondition: There can’t be more than one final and one initial markers.
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
return text[text.index(begin)+1:text.index(end)]
if __name__ == '__main__':
print('Example:')
print(between_markers('What is >apple<', '>', '<'))
assert between_markers('What is >apple<', '>', '<') == "apple"
assert between_markers('What is [apple]', '[', ']') == "apple"
assert between_markers('What is ><', '>', '<') == ""
assert between_markers('>apple<', '>', '<') == "apple"
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.
Input: A string.
Output: A string.
Example:
1 correct_sentence(“greetings, friends”) == “Greetings, friends.” 2 correct_sentence(“Greetings, friends”) == “Greetings, friends.” 3 correct_sentence(“Greetings, friends.”) == “Greetings, friends.”
Precondition: No leading and trailing spaces, text contains only spaces, a-z A-Z , and .
def correct_sentence(text: str) -> str:
"""
returns a corrected sentence which starts with a capital letter
and ends with a dot.
"""
return text[0].upper() + text[1:] + ("." if text[-1] != "." else "")
if __name__ == '__main__':
print("Example:")
print(correct_sentence("greetings, friends"))
print(correct_sentence("welcome to New York"))
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."
assert correct_sentence("welcome to New York") == "Welcome to New York."
Is Even
Check if the given number is even or not. Your function should return True if the number is even, and False if the number is odd.
Input: An int.
Output: A bool.
Example:
is_even(2) == True is_even(5) == False is_even(0) == True
How it’s used: (math is used everywhere)
Precondition: both given ints should be between -1000 and 1000
def is_even(num: int) -> bool:
return num & 1 == 0
if __name__ == '__main__':
print("Example:")
print(is_even(2))
assert is_even(2) == True
assert is_even(5) == False
assert is_even(0) == True
print("Coding complete? Click 'Check' to earn cool rewards!")
|