Multiply(乘法)
'''
题目:
编写一个接收 2 个数字作为输入的函数,它应该返回这 2 个数字的乘法
'''
"""
例子:
mult_two(2, 3) == 6
mult_two(1, 0) == 0
"""
"""
官方的代码:
def mult_two(a, b):
#自己的代码
return sum
if __name__ == '__main__':
print("Example:")
print(mult_two(3, 2))
# These "asserts" are used for self-checking and not for an auto-testing
assert mult_two(3, 2) == 6
assert mult_two(1, 0) == 0
print("Coding complete? Click 'Check' to earn cool rewards!")
"""
自己的方法:
'''
建一个参数,接受两个数的乘积
'''
def mult_two(a, b):
sum = a*b
return sum
if __name__ == '__main__':
print("Example:")
print(mult_two(3, 2))
# These "asserts" are used for self-checking and not for an auto-testing
assert mult_two(3, 2) == 6
assert mult_two(1, 0) == 0
print("Coding complete? Click 'Check' to earn cool rewards!")
大神方法:
import numpy as np
def mult_two(a, b):
return np.product([a, b])
if __name__ == '__main__':
print("Example:")
print(mult_two(3, 2))
# These "asserts" are used for self-checking and not for an auto-testing
assert mult_two(3, 2) == 6
assert mult_two(1, 0) == 0
print("Coding complete? Click 'Check' to earn cool rewards!")
First Word(第一个数字)
'''
题目:
给你一个字符串,你必须找到它的第一个单词。
这是 First Word 任务的简化版 ,以后可以解决。
输入字符串仅由英文字母和空格组成。
字符串的开头和结尾没有任何空格
例子:
first_word("Hello world") == "Hello"
'''
"""
官方代码:
def first_word(text: str) -> str:
"""
returns the first word in a given text.
"""
#自己的代码
return null
if __name__ == '__main__':
print("Example:")
print(first_word("Hello world"))
# These "asserts" are used for self-checking and not for an auto-testing
assert first_word("Hello world") == "Hello"
assert first_word("a word") == "a"
assert first_word("hi") == "hi"
print("Coding complete? Click 'Check' to earn cool rewards!")
"""
自己的方法:
def first_word(text: str) -> str:
"""
returns the first word in a given text.
"""
r = text.split()
return r[0]
if __name__ == '__main__':
print("Example:")
print(first_word("Hello world"))
# These "asserts" are used for self-checking and not for an auto-testing
assert first_word("Hello world") == "Hello"
assert first_word("a word") == "a"
assert first_word("hi") == "hi"
print("Coding complete? Click 'Check' to earn cool rewards!")
大神方法:
first_word=lambda s:s.split()[0]
Acceptable Password I
'''
题目:
In this mission, you need to create a password verification function.
The verification condition is:
the length should be bigger than 6.
例子:
is_acceptable_password('short') == False
is_acceptable_password('muchlonger') == True
'''
#官方代码:
def is_acceptable_password(password: str) -> bool:
#自己的代码
return null
if __name__ == '__main__':
print("Example:")
print(is_acceptable_password('short'))
# These "asserts" are used for self-checking and not for an auto-testing
assert is_acceptable_password('short') == False
assert is_acceptable_password('muchlonger') == True
assert is_acceptable_password('ashort') == False
print("Coding complete? Click 'Check' to earn cool rewards!")
自己的方法:
def is_acceptable_password(password: str) -> bool:
if len(password)> 6:
return True
else:
return False
if __name__ == '__main__':
print("Example:")
print(is_acceptable_password('short'))
# These "asserts" are used for self-checking and not for an auto-testing
assert is_acceptable_password('short') == False
assert is_acceptable_password('muchlonger') == True
assert is_acceptable_password('ashort') == False
print("Coding complete? Click 'Check' to earn cool rewards!")
大神方法:
def is_acceptable_password(password: str) -> bool:
return len(password) > 6
if __name__ == '__main__':
print("Example:")
print(is_acceptable_password('short'))
# These "asserts" are used for self-checking and not for an auto-testing
assert is_acceptable_password('short') == False
assert is_acceptable_password('muchlonger') == True
assert is_acceptable_password('ashort') == False
print("Coding complete? Click 'Check' to earn cool rewards!")
def is_acceptable_password(password: str) -> bool:
return bool(password[7::])
if __name__ == '__main__':
print("Example:")
print(is_acceptable_password('short'))
# These "asserts" are used for self-checking and not for an auto-testing
assert is_acceptable_password('short') == False
assert is_acceptable_password('muchlonger') == True
assert is_acceptable_password('ashort') == False
print("Coding complete? Click 'Check' to earn cool rewards!")
- def is_acceptable_password(a: str) -> bool: 强制进行类型的转换,将字符型转换为布尔型
Number Length
'''
题目:
You have a positive integer. Try to find out how many digits it has?
例子:
number_length(10) == 2
number_length(0) == 1
'''
自己的方法:
def number_length(a: int) -> int:
b = len(str(a))
return b
if __name__ == '__main__':
print("Example:")
print(number_length(10))
# These "asserts" are used for self-checking and not for an auto-testing
assert number_length(10) == 2
assert number_length(0) == 1
assert number_length(4) == 1
assert number_length(44) == 2
print("Coding complete? Click 'Check' to earn cool rewards!")
End Zeros
'''
题目:
Try to find out how many zeros a given number has at the end.
例子:
end_zeros(0) == 1
end_zeros(1) == 0
end_zeros(10) == 1
end_zeros(101) == 0
'''
自己的方法
def end_zeros(num: int) -> int:
x = str(num)
y= x.rstrip('0')
z = len(x)-len(y)
return z
if __name__ == '__main__':
print("Example:")
print(end_zeros(0))
# These "asserts" are used for self-checking and not for an auto-testing
assert end_zeros(0) == 1
assert end_zeros(1) == 0
assert end_zeros(10) == 1
assert end_zeros(101) == 0
assert end_zeros(245) == 0
assert end_zeros(100100) == 2
print("Coding complete? Click 'Check' to earn cool rewards!")
大神方法:
def end_zeros(num: int) -> int:
return len(s := str(num)) - len(s.rstrip('0'))
Backward String
'''
题目:
You should return a given string in reverse order.
例子:
backward_string('val') == 'lav'
backward_string('') == ''
backward_string('ohho') == 'ohho'
backward_string('123456789') == '987654321'
'''
方法:
def backward_string(val: str) -> str:
# your code here
return val[::-1]
if __name__ == '__main__':
print("Example:")
print(backward_string('val'))
# These "asserts" are used for self-checking and not for an auto-testing
assert backward_string('val') == 'lav'
assert backward_string('') == ''
assert backward_string('ohho') == 'ohho'
assert backward_string('123456789') == '987654321'
print("Coding complete? Click 'Check' to earn cool rewards!")
Remove All Before
## 自己的代码
from typing import Iterable
def remove_all_before(items: list, border: int) -> Iterable:
if border in items:
items = items[items.index(border)::1]
return items
if __name__ == '__main__':
print("Example:")
print(list(remove_all_before([1, 2, 3, 4, 5], 3)))
# These "asserts" are used for self-checking and not for an auto-testing
assert list(remove_all_before([1, 2, 3, 4, 5], 3)) == [3, 4, 5]
assert list(remove_all_before([1, 1, 2, 2, 3, 3], 2)) == [2, 2, 3, 3]
assert list(remove_all_before([1, 1, 2, 4, 2, 3, 4], 2)) == [2, 4, 2, 3, 4]
assert list(remove_all_before([1, 1, 5, 6, 7], 2)) == [1, 1, 5, 6, 7]
assert list(remove_all_before([], 0)) == []
assert list(remove_all_before([7, 7, 7, 7, 7, 7, 7, 7, 7], 7)) == [7, 7, 7, 7, 7, 7, 7, 7, 7]
print("Coding complete? Click 'Check' to earn cool rewards!")
大神代码:
def remove_all_before(items, border):
try:
return items[items.index(border):]
except ValueError:
return items
All Upper I
def is_all_upper(text: str) -> bool:
if text.upper() == text:
return True
else:
return False
if __name__ == '__main__':
print("Example:")
print(is_all_upper('ALL UPPER'))
# These "asserts" are used for self-checking and not for an auto-testing
assert is_all_upper('ALL UPPER') == True
assert is_all_upper('all lower') == False
assert is_all_upper('mixed UPPER and lower') == False
assert is_all_upper('') == True
assert is_all_upper(' ') == True
assert is_all_upper('444') == True
assert is_all_upper('55 55 5') == True
print("Coding complete? Click 'Check' to earn cool rewards!")
Replace First
def replace_first(items: list) -> Iterable:
if len(items) > 1:
return items[1:] + items[:1]
else:
return items
Max Digit
def max_digit(number: int) -> int:
a = list(str(number))
b = a.sort(reverse=True)
return int(a[0])
if __name__ == '__main__':
print("Example:")
print(max_digit(0))
# These "asserts" are used for self-checking and not for an auto-testing
assert max_digit(0) == 0
assert max_digit(52) == 5
assert max_digit(634) == 6
assert max_digit(1) == 1
assert max_digit(10000) == 1
print("Coding complete? Click 'Check' to earn cool rewards!")
第二方法:
max_digit = lambda number: int(max(str(number)))
Split Pairs
def split_pairs(a):
if len(a)%2 !=0:
a = a+'_'
return [a[i:i+2] for i in range(0,len(a),2)]
else:
return [a[i:i+2] for i in range(0,len(a),2)]
if __name__ == '__main__':
print("Example:")
print(list(split_pairs('abcd')))
# These "asserts" are used for self-checking and not for an auto-testing
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):
return [ch1+ch2 for ch1,ch2 in zip(a[::2],a[1::2]+'_')]
def split_pairs(a):
b = [ch1+ch2 for ch1,ch2 in zip(a[::2],a[1::2]+'_')]
print(a[::2])
print((a[1::2]+'_'))
print()
print(b)
if __name__ == '__main__':
print("Example:")
print(list(split_pairs('abcdef')))
c = ('a','b')
d = ('c','d')
f = [c+d]
print(f)
var1=[1,2,3,4]
var2=['a','b','c']
var3=('A','B','C','D')
res = zip(var1,var2,var3)
print(next(res))
Beginning Zeros
def beginning_zeros(number: str) -> int:
a = len(number)
b = number.lstrip('0')
c = len(b)
return a-c
def beginning_zeros(number: str) -> int:
zeros = 0
for digit in number:
print(digit)
if digit != '0':
break
zeros += 1
return zeros
Nearest Value
个人思路:
将所要比较的值放入序列中,从序列中寻找最近的值(注意开头与结尾)
def nearest_value(values: set, one: int) -> int:
a = list(values)
a.append(one)
a.sort()
b = a.index(one)
if b == len(a)-1:
return a[-2]
elif b == 0:
return a[1]
elif (abs(a[b+1]-one) < (abs(a[b-1]-one))):
return a[b+1]
else:
return a[b-1]
大神思路:使用匿名函数与min函数,将序列中的值与要比较的值进行相减,最后取绝对值最小的
def nearest_value(values: set, one: int) -> int:
return min(values, key=lambda n: (abs(one - n), n))
Between Markers (simplified)
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
a = text.index(begin)
b = text.index(end)
return text[a+1:b:1]
if __name__ == '__main__':
print('Example:')
print(between_markers('What is >apple<', '>', '<'))
Correct Sentence
def correct_sentence(text: str) -> str:
"""
returns a corrected sentence which starts with a capital letter
and ends with a dot.
"""
if text[-1]!='.':
return text[0].upper()+text[1:]+'.'
else:
return text[0].upper()+text[1:]
if __name__ == '__main__':
print("Example:")
print(correct_sentence("greetings, friends"))
Is Even
def is_even(num: int) -> bool:
if num%2 == 0:
return True
else:
return False