CHECKIO----HOME

本文集提供了一系列用Python解决的实际问题案例,包括数据处理、字符串操作、列表管理等常见任务,旨在帮助读者通过动手实践提高编程技能。

Sum Numbers

在这里插入图片描述

def sum_numbers(text: str) -> int:
    sum = 0
    for i in text.split(" "):
        if i.isdigit():
            sum +=int(i)       
    return sum


if __name__ == '__main__':
    print("Example:")
    print(sum_numbers('hi'))

Even the Last

在这里插入图片描述

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

#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]))

Three Words

在这里插入图片描述

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

Right to Left

在这里插入图片描述

def left_join(phrases: tuple) -> str:
    """
    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")))

First Word

在这里插入图描述

    a = text.replace(".",' ')
    print(a)
    b = a.split()
    print(b)
    c = (b[0]).rstrip(",")
    return c

大神方法:利用正则表达式来进行字符串的匹配

import re


def first_word(text: str) -> str:
    return re.search("([\w']+)", text).group(1)

Days Between

在这里插入图片描述

from datetime import datetime 

def days_diff(a, b):
    c = datetime(*a)  #将元组(1982,4,19)---》1982-4-19
    d = datetime(*b)
    print(a,type(a))
    print(b,type(b))
    print(c,type(c))
    return abs((c-d).days)

Count Digits

在这里插入图片描述

def count_digits(text: str) -> int:
    a = 0
#   print(text)
    for i in text:k
        print(i)
        if i.isdigit():            
            a += 1
    return a

if __name__ == '__main__':
    print("Example:")
    print(count_digits('hi'))

大神方法:filter() 用于过滤序列,过滤掉不符合条件的元素,返回符合条件的元素组成新列表

def count_digits(text: str) -> int:
    return len(list(filter(lambda c: c.isdigit(), text)))

Backward Each Word

在这里插入图片描述

def backward_string_by_word(text: str) -> str:
    text = text.split(' ')
    print(text)
    c = []
    for i in text:
        b = i[::-1]
        c.append(b)
    print(c)
    d = ' '.join(c)
    return d

更好的方法:使用列表推导式进行处理

def backward_string_by_word(text: str) -> str:
    text = text.split(' ')
    text = ' '.join([x[::-1] for x in text])
    return text

Bigger Price

在这里插入图片描述

def bigger_price(limit: int, data: list) -> list:
    """
        TOP most expensive goods
    """
    a = []
    for i in data:
        print(i)
        index = i.get('price')
        a.append(index)
    print(a)
    
    b = list(zip(a,data))
    print(b)
    b.sort(key = lambda x:x[0],reverse=True)
    return list(list(zip(*b[0:limit])))[1]

大神方法:

def bigger_price(limit: int, data: list) -> list:
    return sorted(data, reverse=True, key=lambda item: item["price"])[0:limit]

Between Markers

在这里插入图片描述

def between_markers(text: str, begin: str, end: str) -> str:
    """
        returns substring between two given markers
    """
    start = text.find(begin)
    finish = text.find(end)
    
    if start !=-1 and finish !=-1:
        return text[start+len(begin):finish]
    elif start == -1  and finish != -1:
        return text[:finish]
    elif start != -1 and finish == -1:
        return text[start+len(begin):]
    elif start == -1 and finish == -1:
        return text

其他方法

    try:
        if text.index(end) < text.index(begin):
            return ""
    except ValueError:
        pass
    #print(text.split(begin)[-1].split(end)[0])
    return text.split(begin)[-1].split(end)[0]

find()与 index()的区别:
Python find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。
Python index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。

Non-unique Elements

在这里插入图片描述

#方法一、
def checkio(data: list) -> list:
    #Your code here
    #It's main function. Don't remove this function
    #It's used for auto-testing and must return a result for check.  

    #replace this for solution
    data1 = []
    for i in data:
        if data.count(i)>1:
            data1.append(i)
    return  data1



#方法二、
def checkio(data: list) -> list:
    #Your code here
    #It's main function. Don't remove this function
    #It's used for auto-testing and must return a result for check.  

    #replace this for solution
    data1 = data.copy()
    for i in data:
        if data.count(i) == 1:
            data1.remove(i)
    return  data1




#方法三、
def checkio(data: list) -> list:
    #Your code here
    #It's main function. Don't remove this function
    #It's used for auto-testing and must return a result for check.  

    #replace this for solution
    
    return [x for x in data if data.count(x) > 1]

Popular Words

在这里插入图片描述

def popular_words(text: str, words: list) -> dict:
    # your code here
    print(text)
    text1 = (text.lower()).replace('\n',' ').split(' ')
    print(text1,type(text1))
    return {x:text1.count(x) for x in words}
    

if __name__ == '__main__':
    print("Example:")
    print(popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']))

Second Index

在这里插入图片描述

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

Sort Array by Element Frequency

在这里插入图片描述

def frequency_sort(items):
    # your code here
    return sorted(items,key=lambda x: (-items.count(x),items.index(x)))


if __name__ == '__main__':
    print("Example:")
    print(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4]))

Pawn Brotherhood

在这里插入图片描述

#安全棋子:在左下方或右下方有棋子则为安全
def safe_pawns(pawns: set) -> int:
    num = 0
    for i in pawns:
        left = chr(ord(list(i)[0])-1) + chr(ord(list(i)[1])-1)
        right = chr(ord(list(i)[0])+1) + chr(ord(list(i)[1])-1)
        
        if left in pawns or right in pawns:
            num += 1
    return num

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) == 6
    assert safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}) == 1
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

Sun Angle

在这里插入图片描述
1 小时 15度
1 分钟 0.25度

from typing import Union


def sun_angle(time: str) -> Union[int, str]:
    hour = 15
    mi = 0.25
    
    timelist = [int(i)for i in time.split(":")]
    if timelist[0] < 6 or (timelist[0] >= 18 and timelist[1] > 0) :
        return ("I don't see the sun!")
    else :
#         print(timelist[0])
#         print(timelist[1])
        a = ((((timelist[0])-6)*hour) + (timelist[1]*mi))
        return a


if __name__ == '__main__':
    print("Example:")
    print(sun_angle("07:00"))

    # These "asserts" using only for self-checking and not necessary for auto-testing
    assert sun_angle("07:00") == 15
    assert sun_angle("01:23") == "I don't see the sun!"
    print("Coding complete? Click 'Check' to earn cool rewards!")

Split List

在这里插入图片描述

import math
def split_list(items: list) -> list:
    a = []
    if items:
        a.append ( items[0:math.ceil(len(items) /2)])
        a.append (items[math.ceil(len(items) / 2) :])
    else:
        a = [[],[]]
    return a

if __name__ == '__main__':
    print("Example:")
    print(split_list([1, 2, 3]))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert split_list([1, 2, 3, 4, 5, 6]) == [[1, 2, 3], [4, 5, 6]]
    assert split_list([1, 2, 3]) == [[1, 2], [3]]
    assert split_list([1, 2, 3, 4, 5]) == [[1, 2, 3], [4, 5]]
    assert split_list([1]) == [[1], []]
    assert split_list([]) == [[], []]
    print("Coding complete? Click 'Check' to earn cool rewards!")

All the Same

在这里插入图片描述

from typing import List, Any


def all_the_same(elements: List[Any]) -> bool:
    if len(set(elements)) <= 1 :
        return True
    else:
        return False


if __name__ == '__main__':
    print("Example:")
    print(all_the_same([1, 1, 1]))
    
    # These "asserts" are used for self-checking and not for an auto-testing
    assert all_the_same([1, 1, 1]) == True
    assert all_the_same([1, 2, 1]) == False
    assert all_the_same(['a', 'a', 'a']) == True
    assert all_the_same([]) == True
    assert all_the_same([1]) == True
    print("Coding complete? Click 'Check' to earn cool rewards!")


Date and Time Converter

在这里插入图片描述

学习 datetime 中的strftime 与 strptime 函数
datetime.strptime(date_string, format) :
将时间转换为格式 :2000-01-01 00:00:00
是将一个时间元组进行格式化:接收时间元组,并返回以可读字符串表示的当地时间,格式由参数format决定。
语法:datetime.strftime(format[, t])。

from datetime import datetime
def date_time(time: str) -> str:
    dtime = datetime.strptime(time,"%d.%m.%Y %H:%M")
    print(dtime)
    hour = 'hour' if dtime.hour == 1 else 'hours'
    minute = 'minute' if dtime.minute ==1 else 'minutes'
    return dtime.strftime(f'%#d %B %Y year %#H {hour} %#M {minute}')

if __name__ == "__main__":
    print("Example:")
    print(date_time("01.01.2000 00:00"))

    # These "asserts" using only for self-checking and not necessary for auto-testing
    assert (
        date_time("01.01.2000 00:00") == "1 January 2000 year 0 hours 0 minutes"
    ), "Millenium"
    assert (
        date_time("09.05.1945 06:30") == "9 May 1945 year 6 hours 30 minutes"
    ), "Victory"
    assert (
        date_time("20.11.1990 03:55") == "20 November 1990 year 3 hours 55 minutes"
    ), "Somebody was born"
    print("Coding complete? Click 'Check' to earn cool rewards!")

Morse Decoder

在这里插入图片描述

MORSE = {
    ".-": "a",
    "-...": "b",
    "-.-.": "c",
    "-..": "d",
    ".": "e",
    "..-.": "f",
    "--.": "g",
    "....": "h",
    "..": "i",
    ".---": "j",
    "-.-": "k",
    ".-..": "l",
    "--": "m",
    "-.": "n",
    "---": "o",
    ".--.": "p",
    "--.-": "q",
    ".-.": "r",
    "...": "s",
    "-": "t",
    "..-": "u",
    "...-": "v",
    ".--": "w",
    "-..-": "x",
    "-.--": "y",
    "--..": "z",
    "-----": "0",
    ".----": "1",
    "..---": "2",
    "...--": "3",
    "....-": "4",
    ".....": "5",
    "-....": "6",
    "--...": "7",
    "---..": "8",
    "----.": "9",
}


def morse_decoder(code):
    c = code.replace("  "," ").split(" ")
    print(c)
    result = ""
    for i in c:
        if i:
            result += MORSE[i]
        else:
            result +=  ' '
    return result.capitalize()  


if __name__ == "__main__":
    print("Example:")
    print(morse_decoder("... --- ..."))

    # These "asserts" using only for self-checking and not necessary for auto-testing
    assert morse_decoder("... --- -- .   - . -..- -") == "Some text"
    assert morse_decoder("..--- ----- .---- ---..") == "2018"
    assert (
        morse_decoder(".. -   .-- .- ...   .-   --. --- --- -..   -.. .- -.--")
        == "It was a good day"
    )
    print("Coding complete? Click 'Check' to earn cool rewards!")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值