checkio編程挑戰題目

最近發現了一個有趣的網站:https://py.checkio.org/ 是一個編程挑戰的網站 支持python和js
在這裏插入圖片描述

下面我們要挑戰的 題目是這個島嶼,還剩幾道題目沒有挑戰
在這裏插入圖片描述
先從第一題開始好了
在這裏插入圖片描述

  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 <len(array)≤10
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” 是一個單詞遊戲,我們將教會機器人學會關於除法的一些知識。
在這裏插入圖片描述

你將要使用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: 考察切片的使用在這裏插入圖片描述

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. 找出字典中最大值對應的鍵List item
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:在這裏插入圖片描述
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: 谷歌翻譯 有點怪怪的在這裏插入圖片描述
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:在這裏插入圖片描述
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:在這裏插入圖片描述
那麼這裏我們進行舉一反三,如果要求你按照別的方式排序,你知道怎麼做嘛
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:
在這裏插入圖片描述
考察可變參數也就是*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:給定一個字符串 找出第一個單詞
在這裏插入圖片描述
字符串方法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:
在這裏插入圖片描述
在這裏插入圖片描述

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:
在這裏插入圖片描述
在這裏插入圖片描述
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')

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章