python练习之CheckiO-HOME小岛

Even the Last

You are given an array of integers. You should find the sum of the integers with even indexes (0th, 2nd, 4th…). Then multiply this summed number and the final element of the array together. Don’t forget that the first element has an index of 0.
For an empty array, the result will always be 0 (zero).
Example:
checkio([0, 1, 2, 3, 4, 5]) == 30
checkio([1, 3, 5]) == 30
checkio([6]) == 36
checkio([]) == 0

# 参考答案
def checkio(array):
    """
        sums even-indexes elements and multiply at the last
    """
    if len(array) == 0: return 0
    return sum(array[0::2]) * array[-1]
if __name__ == '__main__':
    print(checkio([0, 1, 2, 3, 4, 5]))
    assert checkio([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)*5=30"
    assert checkio([]) == 0, "An empty array = 0"
Right to Left

One of the robots is charged with a simple task: to join a sequence of strings into one sentence to produce instructions on how to get around the ship. But this robot is left-handed and has a tendency to joke around and confuse its right-handed friends.
You are given a sequence of strings. You should join these strings into a chunk of text where the initial strings are separated by commas. As a joke on the right handed robots, you should replace all cases of the words “right” with the word “left”, even if it’s a part of another word. All strings are given in lowercase.

# 参考答案
def left_join(phrases):
    return (",".join(phrases)).replace("right","left")
if __name__ == '__main__':
    print(left_join(("left", "right", "left", "stop")))
    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"
Three Words

Let’s teach the Robots to distinguish words and numbers.
You are given a string with words and numbers separated by whitespaces (one space). The words contains only letters. You should check if the string contains three words in succession . For example, the string “start 5 one two three 7 end” contains three words in succession.

# 参考答案
def checkio(words):
    succ = 0
    for word in words.split():
        succ = (succ + 1)*word.isalpha()
        if succ == 3: return True
    else: return False
if __name__ == '__main__':
    print(checkio("one two 3 four five 6 7 eight 9 ten eleven tt"))
    assert checkio("Hello World hello") == True, "Hello"
    assert checkio("1 2 3 4") == False, "Digits"
    assert checkio("Hi") == False, "Hi"
    assert checkio("one two 3 four five 6 7 eight 9 ten eleven tt") == True, "Hi"
First Word

You are given a string where you have to find its first word.
When solving a task pay attention to the following points:
There can be dots and commas in a string.
A string can start with a letter or, for example, a dot or space.
A word can contain an apostrophe and it’s a part of a word.
The whole text can be represented with one word and that’s it.
Example:
first_word(“Hello world”) == “Hello”
first_word(“greetings, friends”) == “greetings”

# 参考答案
import re
def first_word(text: str) -> str:
    return re.search("([\w']+)", text).group(1)
if __name__ == '__main__':
    print(first_word(" a word "))
    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"
Days Between

How old are you in a number of days? It’s easy to calculate - just subtract your birthday from today. We could make this a real challenge though and count the difference between any dates.
You are given two dates as an array with three numbers - a year, month and day. For example: 19 April 1982 will be (1982, 4, 19). You should find the difference in days between the given dates. For example between today and tomorrow = 1 day. The difference will always be either a positive number or zero, so don’t forget about the absolute value.
Example:
days_diff((1982, 4, 19), (1982, 4, 22)) == 3
days_diff((2014, 1, 1), (2014, 8, 27)) == 238

from datetime import date
import datetime
def days_diff(a, b):
    return abs((datetime.date(*b)-datetime.date(*a)).days)

if __name__ == '__main__':
    print(days_diff((2014, 1, 1), (2014, 8, 27)))
    assert days_diff((1982, 4, 19), (1982, 4, 22)) == 3
    assert days_diff((2014, 1, 1), (2014, 8, 27)) == 238
    assert days_diff((2014, 8, 27), (2014, 1, 1)) == 238
Count Digits

You need to count the number of digits in a given string.
Example:
count_digits(‘hi’) == 0
count_digits(‘who is 1st here’) == 1
count_digits(‘my numbers is 2’) == 1
count_digits(‘This picture is an oil on canvas ’
‘painting by Danish artist Anna ’
‘Petersen between 1845 and 1910 year’) == 8
count_digits(‘5 plus 6 is’) == 2
count_digits(’’) == 0

def count_digits(text: str) -> int:
    return sum(c.isdigit() for c in text)
if __name__ == '__main__':
    print(count_digits('hi'))
    assert count_digits('hi') == 0
    assert count_digits('who is 1st here') == 1
    assert count_digits('This picture is an oil on canvas '
 'painting by Danish artist Anna '
 'Petersen between 1845 and 1910 year') == 8
    assert count_digits('5 plus 6 is') == 2
    assert count_digits('') == 0
Backward Each Word

In a given string you should reverse every word, but the words should stay in their places.
Example:
backward_string_by_word(’’) == ‘’
backward_string_by_word(‘world’) == ‘dlrow’
backward_string_by_word(‘hello world’) == ‘olleh dlrow’
backward_string_by_word(‘hello world’) == ‘olleh dlrow’

def backward_string_by_word(text):
    return ' '.join(word[::-1] for word in text.split(' '))

if __name__ == '__main__':
    print(backward_string_by_word('welcome to a game'))
    assert backward_string_by_word('') == ''
    assert backward_string_by_word('world') == 'dlrow'
    assert backward_string_by_word('hello world') == 'olleh dlrow'
    assert backward_string_by_word('hello   world') == 'olleh   dlrow'
    assert backward_string_by_word('welcome to a game') == 'emoclew ot a emag'
Bigger Price

You have a table with all available goods in the store. The data is represented as a list of dicts
Your mission here is to find the TOP most expensive goods. The amount we are looking for will be given as a first argument and the whole data as the second one
Example:
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}
]
bigger_price(1, [
{“name”: “pen”, “price”: 5},
{“name”: “whiteboard”, “price”: 170}
]) == [{“name”: “whiteboard”, “price”: 170}]

# 我的答案
import operator 
def bigger_price(limit: int, data: list) -> list:
    list1=[]
    sort_list = sorted(data, key=operator.itemgetter('price'),reverse=True)  
    for i in range(len(sort_list)):
        if i<limit:
            list1.append(sort_list[i])
        else:
            break
    return list1
if __name__ == '__main__':
    from pprint import pprint
    pprint(bigger_price(2, [
        {"name": "bread", "price": 100},
        {"name": "wine", "price": 138},
        {"name": "meat", "price": 15},
        {"name": "water", "price": 1}
    ]))
    
    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')
# 参考答案
def bigger_price(limit, data):
    return sorted(data, key=lambda x: x['price'], reverse=True)[:limit]
Between Markers

You are given a string and two markers (the initial and final). You have to find a substring enclosed between these two markers. But there are a few important conditions:
The initial and final markers are always different.
If there is no initial marker, then the first character should be considered the beginning of a string.
If there is no final marker, then the last character should be considered the ending of a string.
If the initial and final markers are missing then simply return the whole string.
If the final marker comes before the initial marker, then return an empty string.
Example:
between_markers(‘What is >apple<’, ‘>’, ‘<’) == ‘apple’
between_markers(‘No[/b] hi’, ‘[b]’, ‘[/b]’) == ‘No’

# 我的答案
def between_markers(text: str, begin: str, end: str) -> str:
    biao1=text.find(begin)
    biao2 = text.find(end)
    str1=''
    if biao1==-1 and biao2!=-1:
        for i in range(biao2):
            str1+=text[i]
            
    elif biao2==-1 and biao1!=-1:
        for i in range(biao1+len(begin),len(text)):
            str1+=text[i]
            
    elif biao2==-1 and biao1==-1:
        return text
            
    elif biao1!=-1 and biao2!=-1:
        for i in range(biao1+len(begin),biao2):
            str1+=text[i] 
            
    return str1
if __name__ == '__main__':
    print(between_markers('No [b]hi', '[b]', '[/b]'))
    assert between_markers('What is >apple<', '>', '<') == "apple", "One sym"
    assert between_markers("<head><title>My new site</title></head>",
                           "<title>", "</title>") == "My new site", "HTML"
    assert between_markers('No[/b] hi', '[b]', '[/b]') == 'No', 'No opened'
    assert between_markers('No [b]hi', '[b]', '[/b]') == 'hi', 'No close'
    assert between_markers('No hi', '[b]', '[/b]') == 'No hi', 'No markers at all'
    assert between_markers('No <hi>', '>', '<') == '', 'Wrong direction'
# 参考答案
def between_markers(text: str, begin: str, end: str) -> str:
    start = text.find(begin) + len(begin) if begin in text else None
    stop = text.find(end) if end in text else None
    return text[start:stop]
Non-unique Elements

You are given a non-empty list of integers (X). For this task, you should return a list consisting of only the non-unique elements in this list. To do so you will need to remove all unique elements (elements which are contained in a given list only once). When solving this task, do not change the order of the list. Example: [1, 2, 3, 1, 3] 1 and 3 non-unique elements and result will be [1, 3, 1, 3].
Example:
checkio([1, 2, 3, 1, 3]) == [1, 3, 1, 3]
checkio([1, 2, 3, 4, 5]) == []
checkio([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5]
checkio([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9]
checkio([2]) == []

# 我的答案
def checkio(data: list) -> list:
    #Your code here
    dict={}
    list=[]
    for i in data:
        if i in dict:
            dict[i]+=1
        else:
            dict.update({i:1})
    for k,v in dict.items():
        if v>1:
            list.append(k)
    list2=[]
    if len(list)==[]:
        return []
    else:
        for i in data:
            if i in list:
                list2.append(i)
    return list2
if __name__ == "__main__":
    print(checkio([10,20,30,10]))
    assert list(checkio([1, 2, 3, 1, 3])) == [1, 3, 1, 3], "1st example"
    assert list(checkio([1, 2, 3, 4, 5])) == [], "2nd example"
    assert list(checkio([5, 5, 5, 5, 5])) == [5, 5, 5, 5, 5], "3rd example"
    assert list(checkio([10, 9, 10, 10, 9, 8])) == [10, 9, 10, 10, 9], "4th example"
# 参考答案
def checkio(data):
        return [i for i in data if data.count(i) > 1]
Popular Words

In this mission your task is to determine the popularity of certain words in the text.
At the input of your function are given 2 arguments: the text and the array of words the popularity of which you need to determine.
When solving this task pay attention to the following points:
The words should be sought in all registers. This means that if you need to find a word “one” then words like “one”, “One”, “oNe”, “ONE” etc. will do.
The search words are always indicated in the lowercase.
If the word wasn’t found even once, it has to be returned in the dictionary with 0 (zero) value.
Example:
popular_words(’’’
When I was One
I had just begun
When I was Two
I was nearly new
‘’’, [‘i’, ‘was’, ‘three’, ‘near’]) == {
‘i’: 4,
‘was’: 3,
‘three’: 0,
‘near’: 0
}

#我的答案
def popular_words(text: str, words: list) -> dict:
    # your code here
    text = text.lower()
    list = text.replace('\n',' ').split(' ')
    dict={}
    for j in words:
        dict.update({j:0})
        for i in list:
            if i==j:
                if j in dict:
                    dict[j]+=1
    return dict
if __name__ == '__main__':
    print(popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']))

    assert popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']) == {
        'i': 4,
        'was': 3,
        'three': 0,
        'near': 0
    }

# 参考答案
def popular_words(text, words):
    lower_count = text.lower().split().count
    return {word: lower_count(word) for word in words}
Second Index

You are given two strings and you have to find an index of the second occurrence of the second string in the first one.
Let’s go through the first example where you need to find the second occurrence of “s” in a word “sims”. It’s easy to find its first occurrence with a function index or find which will point out that “s” is the first symbol in a word “sims” and therefore the index of the first occurrence is 0. But we have to find the second “s” which is 4th in a row and that means that the index of the second occurrence (and the answer to a question) is 3.
Example:
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]:
    result=0
    for i in range(len(text)):
        if text[i]==symbol:
            result+=1
            if result==2:
                return i

if __name__ == '__main__':
    print(second_index("sims", "s"))
    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"
# 参考答案
def second_index(text: str, symbol: str):
    try:
        return text.index(symbol, text.index(symbol) + 1)
    except ValueError:
        return None
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值