checkio编程挑战题目

最近发现了一个有趣的网站:https://py.checkio.org/ 是一个编程挑战的网站 支持python和js

下面我们要挑战的 题目是这个岛屿,还剩几道题目没有挑战
checkio编程挑战题目_第1张图片
先从第一题开始好了

  1. 第一题 给定一个函数,函数接收2个整数位参数,返回两个参数的乘积

小白题目 没有难度

def mult_two(a, b):
    # your code here
    return 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!")

2.你的任务是编写一个根据给出的属性参数来介绍一个人的函数

输入: 两个参数。一个字符串(str)和一个正整数(int)。

输出: 字符串(str)。

范例:

say_hi(“Alex”, 32) == “Hi. My name is Alex and I’m 32 years old”
say_hi(“Frank”, 68) == “Hi. My name is Frank and I’m 68 years old”

这道题考察的是字符串的拼接 没有难度

# 1. on CheckiO your solution should be a function
# 2. the function should return the right answer, not print it.

def say_hi(name: str, age: int) -> str:
    """
        Hi!
    """
    # your code here
    return "Hi. My name is " + name + " and I'm " + str(age) + " years old"

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert say_hi("Alex", 32) == "Hi. My name is Alex and I'm 32 years old", "First"
    assert say_hi("Frank", 68) == "Hi. My name is Frank and I'm 68 years old", "Second"
    print('Done. Time to Check.')

3:在这里你的任务是创建得到一个元组,并返回一个包含三个元素(第一,第三和倒数第二的给定元组)的元组与的功能。

输入: 一个不少于三个元素的元组

输出: 一个元组.

举个栗子:

easy_unpack((1, 2, 3, 4, 5, 6, 7, 9)) == (1, 3, 7)
easy_unpack((1, 1, 1, 1)) == (1, 1, 1)
easy_unpack((6, 3, 7)) == (6, 7, 3)

考察如何返回一个元组,没有难度

def easy_unpack(elements: tuple) -> tuple:
    """
        returns a tuple with 3 elements - first, third and second to the last
    """
    # your code here
    return (elements[0],elements[2],elements[-2],)

if __name__ == '__main__':
    print('Examples:')
    print(easy_unpack((1, 2, 3, 4, 5, 6, 7, 9)))
    
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert easy_unpack((1, 2, 3, 4, 5, 6, 7, 9)) == (1, 3, 7)
    assert easy_unpack((1, 1, 1, 1)) == (1, 1, 1)
    assert easy_unpack((6, 3, 7)) == (6, 7, 3)
    print('Done! Go Check!')

  1. 您将获得一个具有正数和数字N的数组。您应该在索引为N的数组中找到元素的N次方。如果N在数组之外,则返回-1。不要忘记第一个元素的索引为0。

让我们看几个例子:
-array = [1、2、3、4]且N = 2,则结果为3 2 == 9;
-数组= [1、2、3],并且N = 3,但是N在数组之外,因此结果为-1。

输入:两个参数。一个数组,它是一个整数列表,一个数字是一个整数。

输出:结果为整数。

前提条件: 0 0≤N
all(对于x in数组0≤x≤100)

def index_power(array: list, n: int) -> int:
    """
        Find Nth power of the element with index N.
    """
    if len(array) <= n:
        return -1
    else:
        return array[n] ** n


if __name__ == '__main__':
    print('Example:')
    print(index_power([1, 2, 3, 4], 2))
    
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert index_power([1, 2, 3, 4], 2) == 9, "Square"
    assert index_power([1, 3, 10, 100], 3) == 1000000, "Cube"
    assert index_power([0, 1], 0) == 1, "Zero power"
    assert index_power([1, 2], 3) == -1, "IndexError"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

5:给你一个正整数,请你写一个函数来实现:传入正整数的每一位(不包括00)的乘积

例如:给你 123405, 你应该这样处理 12345=120(别忘了把0丢掉)

输入: 一个正整数.

输出: 正整数的每一位的乘积
举个栗子:

checkio(123405) == 120
checkio(999) == 729
checkio(1000) == 1
checkio(1111) == 1
1
2
3
4
你将学到: 在这个任务中你将学会一些简单的数据类型的转换。

前提条件: 0 < number < 106

def checkio(number: int) -> int:
    result = 1
    for i in str(number):
        i = int(i)
        if not i:
            continue
        else:
            result *= i
    return result


if __name__ == '__main__':
    print('Example:')
    print(checkio(123405))
    
    # These "asserts" using only for self-checking and not necessary for auto-testing
    assert checkio(123405) == 120
    assert checkio(999) == 729
    assert checkio(1000) == 1
    assert checkio(1111) == 1
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

6:Secret Message
这道题目是要找出给定字符串中的所有大写字母
Example:
find_message(“How are you? Eh, ok. Low or Lower? Ohhh.”) == “HELLO”
find_message(“hello world!”) == “”

	思路:遍历这个字符串,然后用isupper()方法判断每一个元素是否为大写,如果是大写,将它存储在一个变量中,循环完毕
	我们返回这个结果
def find_message(text: str) -> str:
    """Find a secret message"""
    result = ""
    for word in text:
        if word.isupper():
            result += word
    return result


if __name__ == '__main__':
    print('Example:')
    print(find_message("How are you? Eh, ok. Low or Lower? Ohhh."))
    
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert find_message("How are you? Eh, ok. Low or Lower? Ohhh.") == "HELLO", "hello"
    assert find_message("hello world!") == "", "Nothing"
    assert find_message("HELLO WORLD!!!") == "HELLOWORLD", "Capitals"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

7:“Fizz buzz” 是一个单词游戏,我们将教会机器人学会关于除法的一些知识。
checkio编程挑战题目_第2张图片

你将要使用python写一个方法,方法接收一个整数,然后返回:
“Fizz Buzz” 如果这个整数可以整除3并且可以整除5;
“Fizz” 如果整个整数可以整除3;
“Buzz” 如果这个整数可以整除5;
其他情况则返回传入的这个整数;
输入: 一个整数值。

输出: 一个字符串类型的答案。

举个栗子:

checkio(15) == “Fizz Buzz”
checkio(6) == “Fizz”
checkio(5) == “Buzz”
checkio(7) == “7”

1
2
3
4
5
6
你将学到什么: 这个任务可以让你学会写一个十分简单的方法,并学会使用if-else 语句。

– 考察的if else语句 没有难度

# Your optional code here
# You can import some modules or create additional functions


def checkio(number: int) -> str:
    # Your code here
    # It's main function. Don't remove this function
    # It's using for auto-testing and must return a result for check.
    if number % 3 == 0 and number % 5 == 0:
        return "Fizz Buzz"
    elif number % 3 == 0:
        return "Fizz"
    elif number % 5 == 0:
        return "Buzz"
    else:
        return str(number)

# Some hints:
# Convert a number in the string with str(n)

# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    print('Example:')
    print(checkio(15))
    
    assert checkio(15) == "Fizz Buzz", "15 is divisible by 3 and 5"
    assert checkio(6) == "Fizz", "6 is divisible by 3"
    assert checkio(5) == "Buzz", "5 is divisible by 5"
    assert checkio(7) == "7", "7 is not divisible by 3 or 5"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

7: 考察切片的使用checkio编程挑战题目_第3张图片

def checkio(array):
    """
        sums even-indexes elements and multiply at the last
    """
    if not array:
        return 0
    return sum(array[::2]) * array[-1]

    

#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    print('Example:')
    print(checkio([0, 1, 2, 3, 4, 5]))
    
    assert checkio([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)*5=30"
    assert checkio([1, 3, 5]) == 30, "(1+5)*5=30"
    assert checkio([6]) == 36, "(6)*6=36"
    assert checkio([]) == 0, "An empty array = 0"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

  1. 找出字典中最大值对应的键checkio编程挑战题目_第4张图片
def best_stock(data):
    # your code here
    max_price = 0
    answer = ''
    for i in data:
        if data[i] > max_price:
            max_price = data[i]
            answer = i
    return answer


if __name__ == '__main__':
    print("Example:")
    print(best_stock({
        'CAC': 10.0,
        'ATX': 390.2,
        'WIG': 1.2
    }))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert best_stock({
        'CAC': 10.0,
        'ATX': 390.2,
        'WIG': 1.2
    }) == 'ATX', "First"
    assert best_stock({
        'CAC': 91.1,
        'ATX': 1.01,
        'TASI': 120.9
    }) == 'TASI', "Second"
    print("Coding complete? Click 'Check' to earn cool rewards!")

9:checkio编程挑战题目_第5张图片
correct_sentence(“greetings, friends”) == “Greetings, friends.”
correct_sentence(“Greetings, friends”) == “Greetings, friends.”
correct_sentence(“Greetings, friends.”) == “Greetings, friends.”

要求就是给定一个句子如果没有以大写字母开头,则将首个单词的字母大写,如果没有以.号结尾,要求你以.号结尾,如果一个语句已经以句点结尾,返回它本身就可以了

日本剑道有二刀流,咱么大python也有一行流了,让你见识一下一行流的厉害

def correct_sentence(text: str) -> str:
    """
        returns a corrected sentence which starts with a capital letter
        and ends with a dot.
    """
    # your code here
    return text[0].upper() + text[1:] + "." if not text.endswith(".") else text


if __name__ == '__main__':
    print("Example:")
    print(correct_sentence("greetings, friends"))
    
    # These "asserts" are used for self-checking and not for an auto-testing
    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."
    
    print("Coding complete? Click 'Check' to earn cool rewards!")

10: 谷歌翻译 有点怪怪的checkio编程挑战题目_第6张图片
left_join((“left”, “right”, “left”, “stop”)) == “left,left,left,stop”
left_join((“bright aright”, “ok”)) == “bleft aleft,ok”
left_join((“brightness wright”,)) == “bleftness wleft”
left_join((“enough”, “jokes”)) == “enough,jokes”

def left_join(phrases):
    """
        Join strings and replace "right" to "left"
    """
    return ",".join(phrases).replace("right", "left")

if __name__ == '__main__':
    print('Example:')
    print(left_join(("left", "right", "left", "stop")))
    
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert left_join(("left", "right", "left", "stop")) == "left,left,left,stop", "All to left"
    assert left_join(("bright aright", "ok")) == "bleft aleft,ok", "Bright Left"
    assert left_join(("brightness wright",)) == "bleftness wleft", "One phrase"
    assert left_join(("enough", "jokes")) == "enough,jokes", "Nothing to replace"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

11:checkio编程挑战题目_第7张图片
second_index(“sims”, “s”) == 3
second_index(“find the river”, “e”) == 12
second_index(“hi”, " ") is None

def second_index(text: str, symbol: str) -> [int, None]:
    """
        returns the second index of a symbol in a given text
    """
    # your code here
    if text.count(symbol) < 2:
        return None
    first = text.find(symbol)
    return text.find(symbol, first + 1)



if __name__ == '__main__':
    print('Example:')
    print(second_index("sims", "s"))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert second_index("sims", "s") == 3, "First"
    assert second_index("find the river", "e") == 12, "Second"
    assert second_index("hi", " ") is None, "Third"
    assert second_index("hi mayor", " ") is None, "Fourth"
    assert second_index("hi mr Mayor", " ") == 5, "Fifth"
    print('You are awesome! All tests are done! Go Check it!')

12:checkio编程挑战题目_第8张图片
那么这里我们进行举一反三,如果要求你按照别的方式排序,你知道怎么做嘛
key参数接收函数名,可以按照指定的函数规则排序数据
也可以写lamdba表达式,不过lamdba表达式总是让人很困惑

def checkio(numbers_array: tuple) -> list:
    return sorted(numbers_array, key=abs)

#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    print('Example:')
    print(list(checkio((-20, -5, 10, 15))))

    def check_it(array):
        if not isinstance(array, (list, tuple)):
            raise TypeError("The result should be a list or tuple.")
        return list(array)

    assert check_it(checkio((-20, -5, 10, 15))) == [-5, 10, 15, -20], "Example"  # or (-5, 10, 15, -20)
    assert check_it(checkio((1, 2, 3, 0))) == [0, 1, 2, 3], "Positive numbers"
    assert check_it(checkio((-1, -2, -3, 0))) == [0, -1, -2, -3], "Negative numbers"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

13:
checkio编程挑战题目_第9张图片
考察可变参数也就是*args的用法

def checkio(*args):
    return max(args) - min(args) if len(args) > 0 else 0

#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    def almost_equal(checked, correct, significant_digits):
        precision = 0.1 ** significant_digits
        return correct - precision < checked < correct + precision
        
    print('Example:')
    print(checkio(1, 2, 3))
    
    assert almost_equal(checkio(1, 2, 3), 2, 3), "3-1=2"
    assert almost_equal(checkio(5, -5), 10, 3), "5-(-5)=10"
    assert almost_equal(checkio(10.2, -2.2, 0, 1.1, 0.5), 12.4, 3), "10.2-(-2.2)=12.4"
    assert almost_equal(checkio(), 0, 3), "Empty"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

14:给定一个字符串 找出第一个单词
checkio编程挑战题目_第10张图片
字符串方法split()默认按照空格拆分 所以我们可以拆分后用索引拿到第一个字母,
如果让你拿到最后一个,或者倒数第几个 现在你学会了嘛

def first_word(text: str) -> str:
    """
        returns the first word in a given text.
    """
    # your code here
    return text.split()[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!")

15:上一题的增强版
如果字符串中包含多个符号,那么如果获取第一个单词呢
可以使用replace()方法,将多余的标点符号替换掉在进行split()

def first_word(text: str) -> str:
    """
        returns the first word in a given text.
    """
    # your code here
    return text.replace('.', ' ').replace(',', ' ').strip().split()[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("don't touch it") == "don't"
    assert first_word("greetings, friends") == "greetings"
    assert first_word("... and so on ...") == "and"
    assert first_word("hi") == "hi"
    assert first_word("Hello.World") == "Hello"
    print("Coding complete? Click 'Check' to earn cool rewards!")

16:
checkio编程挑战题目_第11张图片
checkio编程挑战题目_第12张图片

def checkio(words: str) -> bool:
    count = 0
    for word in words.split():
        if word.isalpha():
            count += 1
            if count == 3:
                return True
        else:
            count = 0
    return False

#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    print('Example:')
    print(checkio("Hello World hello"))
    
    assert checkio("Hello World hello") == True, "Hello"
    assert checkio("He is 123 man") == False, "123 man"
    assert checkio("1 2 3 4") == False, "Digits"
    assert checkio("bla bla bla bla") == True, "Bla Bla"
    assert checkio("Hi") == False, "Hi"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

17:
checkio编程挑战题目_第13张图片
checkio编程挑战题目_第14张图片
lamdba表达式总是让人感到困惑

def bigger_price(limit: int, data: list) -> list:
    """
        TOP most expensive goods
    """
    # your code here
    return sorted(data, key=lambda x: x['price'], reverse=True)[:limit]


if __name__ == '__main__':
    from pprint import pprint
    print('Example:')
    pprint(bigger_price(2, [
        {"name": "bread", "price": 100},
        {"name": "wine", "price": 138},
        {"name": "meat", "price": 15},
        {"name": "water", "price": 1}
    ]))

    # These "asserts" using for self-checking and not for auto-testing
    assert bigger_price(2, [
        {"name": "bread", "price": 100},
        {"name": "wine", "price": 138},
        {"name": "meat", "price": 15},
        {"name": "water", "price": 1}
    ]) == [
        {"name": "wine", "price": 138},
        {"name": "bread", "price": 100}
    ], "First"

    assert bigger_price(1, [
        {"name": "pen", "price": 5},
        {"name": "whiteboard", "price": 170}
    ]) == [{"name": "whiteboard", "price": 170}], "Second"

    print('Done! Looks like it is fine. Go and check it')

你可能感兴趣的:(编程挑战,Python学习)