【Python】Python 在线Coding汇总

本文详述了在py.checkio.org上进行的Python编程练习,涵盖从禁止使用特定标识符求和,到罗马数字转换,再到棋盘游戏策略等多元问题。每个挑战都附有作者解决方案和最优解决方案的对比,旨在提升Python编程技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本篇用于记录py.checkio.org在线编程网站中的练习结果及最佳solution参照(所谓Best Solution仅仅是某一方面最佳,并非严格的最佳)。

1. 禁止使用如下标识符,要求计算给定数字序列的和。

The list of banned words are as follows: sum import for while reduce 

Mysolution:

def checkio(data,total=0):
    if len(data) == 1:
        return data[0]+total
    else:
        total += data[0]
        return checkio(data[1:],total)

Best Solution:

def checkio(data):
    if len(data)==0: return 0
    return data[0]+checkio(data[1:])

2. 给定罗马数字和阿拉伯数字的对应规则,要求将给出的阿拉伯数字转为罗马数字的表达形式

Mysolution:

def checkio(data):

    #replace this for solution
    romannum_ones = ['I','V','X']
    romannum_tens = ['X', 'L', 'C']
    romannum_hundreds = ['C', 'D', 'M']
    romannum_thousands = ['M']
    romannum = [romannum_ones,romannum_tens,romannum_hundreds,romannum_thousands]
    ones = int (data % 10)
    tens = int((data % 100) / 10 )
    hundreds = int((data % 1000) / 100 )
    thousands = int (data / 1000)
    datanum = [ones,tens,hundreds,thousands]
    romandatanum = []
    for item in list(range(4))[::-1]:
        if datanum[item] == 0:
            pass
        elif datanum[item] >= 1 and datanum[item] <= 3:
            temproman = romannum[item][0] * datanum[item]
            romandatanum.append(temproman)
        elif datanum[item] == 4:
            romandatanum.append(romannum[item][0]+romannum[item][1])
        elif datanum[item] >=5 and datanum[item] <= 8:
            romandatanum.append(romannum[item][1] + romannum[item][0]*(datanum[item]-5))
        elif datanum[item] == 9 :
            romandatanum.append(romannum[item][0] + romannum[item][2])
    romanstring = "".join(romandatanum)
    return romanstring

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert checkio(6) == 'VI', '6'
    assert checkio(76) == 'LXXVI', '76'
    assert checkio(499) == 'CDXCIX', '499'
    assert checkio(3888) == 'MMMDCCCLXXXVIII', '3888'
    print('Done! Go Check!')

Best Solution:

def checkio(n):
    result = ''
    for arabic, roman in zip((1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1),
                             'M     CM   D    CD   C    XC  L   XL  X   IX V  IV I'.split()):
        result += n // arabic * roman
        n %= arabic
    return result

3. 给定NxN的方形矩阵,要求找出在矩阵的横行、竖列以及所有对角线中,是否存在大于等于4个以上的连续相同元素

Mysolution:

def findmatch(mylist):
    matchlen = 1
    templen = 1
    for i in range(len(mylist)-1):
        if mylist[i] == mylist[i+1]:
            templen += 1
            if i == len(mylist)-2:
                if matchlen < templen :
                    matchlen = templen
        else:
            if matchlen < templen :
                matchlen = templen
            templen = 1
    if matchlen >= 4:
        return True
    else:
        return False
def checkio(matrix):
    #replace this for solution
    listgroup = []
    for i in matrix:
        listgroup.append(i)
    for i in list(zip(*matrix)):
        listgroup.append(i)
    L = len(matrix)
    NW_SE_point = [[0,0],[0,L-4],[L-4,0]]
    NE_SW_point = [[0,L-1],[0,3],[L-4,L-1]]
    NW_SE_step = [1,1]
    NE_SW_step = [1,-1]
    for i in range(NW_SE_point[0][1],NW_SE_point[1][1]+1):
        start_x = 0
        start_y = i
        templist = [matrix[start_x][start_y],]
        while start_x < L-1 and start_y < L-1 :
            templist.append(matrix[start_x+NW_SE_step[0]][start_y+NW_SE_step[1]])
            start_x += NW_SE_step[0]
            start_y += NW_SE_step[1]
        if templist not in listgroup:
            listgroup.append(templist)
    for i in range(NW_SE_point[0][0],NW_SE_point[2][0]+1):
        start_x = i
        start_y = 0
        templist = [matrix[start_x][start_y],]
        while start_x < L-1 and start_y < L-1 :
            templist.append(matrix[start_x+NW_SE_step[0]][start_y+NW_SE_step[1]])
            start_x += NW_SE_step[0]
            start_y += NW_SE_step[1]
        if templist not in listgroup:
            listgroup.append(templist)
    for i in range(NE_SW_point[1][1],NE_SW_point[0][1]+1):
        start_x = 0
        start_y = i
        templist = [matrix[start_x][start_y],]
        while start_x < L-1 and start_y > 0 :
            templist.append(matrix[start_x+NE_SW_step[0]][start_y+NE_SW_step[1]])
            start_x += NE_SW_step[0]
            start_y += NE_SW_step[1]
        if templist not in listgroup:
            listgroup.append(templist)
    for i in range(NE_SW_point[0][0],NE_SW_point[2][0]+1):
        start_x = i
        start_y = L-1
        templist = [matrix[start_x][start_y],]
        while start_x < L-1 and start_y > 0 :
            templist.append(matrix[start_x+NE_SW_step[0]][start_y+NE_SW_step[1]])
            start_x += NE_SW_step[0]
            start_y += NE_SW_step[1]
        if templist not in listgroup:
            listgroup.append(templist)
    matchflag = False
    for i in listgroup:
        if findmatch(i):
            matchflag = True
    return matchflag

Best Solution:

def checkio(matrix):
    N = len(matrix)
    def seq_len(x, y, dx, dy, num):
        if 0 <= x < N and 0 <= y < N and matrix[y][x] == num:
            return 1 + seq_len(x + dx, y + dy, dx, dy, num)
        else:
            return 0

    DIR = [(dx, dy) for dy in range(-1, 2)
                    for dx in range(-1, 2)
                    if dx != 0 or dy != 0]
    for y in range(N):
        for x in range(N):
            for dx, dy in DIR:
                if seq_len(x, y, dx, dy, matrix[y][x]) >= 4:
                    return True
    return False

4. 分别用两个类定义勇士和骑士,要求输出不同场景下的决斗结果。

Mysolution:

class Warrior:
    def __init__(self):
        self.health = 50
        self.attack = 5
        self.is_alive = True
    def hitted(self,attack):
        self.health -= attack
        if self.health <= 0:
            self.is_alive = False

class Knight(Warrior):
    def __init__(self):
        super().__init__()
        self.attack = 7

def fight(unit_1, unit_2):
    round = 2
    while True:
        if round % 2 == 0:
            unit_2.hitted(unit_1.attack)
        else:
            unit_1.hitted(unit_2.attack)
        if unit_1.is_alive == False :
            return False
        elif  unit_2.is_alive == False :
            return True
        else:
            round += 1


if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing

    chuck = Warrior()
    bruce = Warrior()
    carl = Knight()
    dave = Warrior()
    mark = Warrior()

    assert fight(chuck, bruce) == True
    assert fight(dave, carl) == False
    assert chuck.is_alive == True
    assert bruce.is_alive == False
    assert carl.is_alive == True
    assert dave.is_alive == False
    assert fight(carl, mark) == False
    assert carl.is_alive == False

    print("Coding complete? Let's try tests!")

Best Solution:

class Warrior:
    def __init__(self):
        self.health = 50
        self.attack = 5

    @property
    def is_alive(self) -> bool:
        return self.health >= 0


class Knight(Warrior):
    def __init__(self):
        super().__init__()
        self.attack = 7


def fight(unit_1, unit_2):
    while unit_1.is_alive and unit_2.is_alive:
        unit_2.health -= unit_1.attack
        if unit_2.is_alive:
            unit_1.health -= unit_2.attack
    return unit_1.is_alive

5. 给定一个九宫格,检测其中是否有X或者O形成一整行或一整列或对角线。

Mysolution:

def checkio(game_result: List[str]) -> str:
    resultlist = [item[0] for item in [game_result[0],game_result[1],game_result[2],game_result[0][0]+game_result[1][0]+game_result[2][0],game_result[0][1]+game_result[1][1]+game_result[2][1],game_result[0][2]+game_result[1][2]+game_result[2][2],game_result[0][0]+game_result[1][1]+game_result[2][2],game_result[0][2]+game_result[1][1]+game_result[2][0]] if item[1:] == item[:-1]]
    if ( 'X'  not in resultlist and 'O' not in resultlist) or ( 'X' in resultlist and 'O' in resultlist):
        return 'D'
    if 'X' in resultlist:
        return 'X'
    if 'O' in resultlist:
        return 'O'
    #return "D" or "X" or "O"

Best Solution:

def checkio(result):
    rows = result
    cols = map(''.join, zip(*rows))
    diags = map(''.join, zip(*[(r[i], r[2 - i]) for i, r in enumerate(rows)]))
    lines = rows + list(cols) + list(diags)

    return 'X' if ('XXX' in lines) else 'O' if ('OOO' in lines) else 'D'

6. 给定一系列Chess棋盘中小兵的坐标,根据指定规则检测位置安全的小兵总数

Mysolution:

def safe_pawns(pawns: set) -> int:
    return len([1 for item in pawns if "".join([chr(ord(item[0])-1),str(int(item[1])-1)]) in pawns or "".join([chr(ord(item[0])+1),str(int(item[1])-1)]) in pawns])

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!")

Best Solution:

def safe_pawns(pawns):
    answer = 0
    for pawn in pawns :
        if chr(ord(pawn[0])-1)+str(int(pawn[1])-1) in pawns or chr(ord(pawn[0])+1)+str(int(pawn[1])-1) in pawns : answer +=1
    return answer

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

7. 根据给定的太阳时刻计算相应角度

Mysolution:

def sun_angle(time):
    #replace this for solution
    hour, minu = time.split(":")
    if int(hour) < 6 or int(hour) > 18 or ( int(hour) == 18 and int(minu) > 0):
        return "I don't see the sun!"
    else:
        return float(((int(hour)-6)*60 + int(minu))*180)/720

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!")

Best Solution:

def sun_angle(time):
    h, m = list(map(int, time.split(':')))
    angle = 15 * h + m / 4 - 90
    return angle if 0 <= angle <= 180 else "I don't see the sun!"



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!")

8. 按照给定的偏移度将给出的字符串序列进行处理

Mysolution:

def wordform(word,delta):
    originnum = ord(word)+delta
    if originnum < 97:
        finalnum = originnum + 26
    elif originnum > 122:
        finalnum = originnum - 26
    else:
        finalnum = originnum
    return chr(finalnum)
    
def to_encrypt(text, delta):
    #replace this for solution
    return "".join([wordform(i,delta) if i != ' ' else i for i in text ])

if __name__ == '__main__':
    print("Example:")
    print(to_encrypt('abc', 10))

    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert to_encrypt("a b c", 3) == "d e f"
    assert to_encrypt("a b c", -3) == "x y z"
    assert to_encrypt("simple text", 16) == "iycfbu junj"
    assert to_encrypt("important text", 10) == "swzybdkxd dohd"
    assert to_encrypt("state secret", -13) == "fgngr frperg"
    print("Coding complete? Click 'Check' to earn cool rewards!")

Best Solution:

from string import ascii_lowercase as ascii


def to_encrypt(text, delta):
    return ''.join([ascii[(ascii.index(char) + delta) % len(ascii)] if char in ascii else char for char in text])


if __name__ == '__main__':
    print("Example:")
    print(to_encrypt('abc', 10))

    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert to_encrypt("a b c", 3) == "d e f"
    assert to_encrypt("a b c", -3) == "x y z"
    assert to_encrypt("simple text", 16) == "iycfbu junj"
    assert to_encrypt("important text", 10) == "swzybdkxd dohd"
    assert to_encrypt("state secret", -13) == "fgngr frperg"
    print("Coding complete? Click 'Check' to earn cool rewards!")

9. 判断给出的序列是否所有元素都相同

Mysolution:

from typing import List, Any


def all_the_same(elements: List[Any]) -> bool:
    # your code here
    if len(elements) == 0:
        return True
    if elements.count(elements[0]) == len(elements):
        return True
    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!")

Best Solution:

def all_the_same(elements):
   return elements[1:] == elements[:-1]

10. 计算给定序列中最长的相同元素组成的子序列长度

Mysolution:

def long_repeat(line):
    """
        length the longest substring that consists of the same char
    """
    # your code here
    maxlen,templen = 1,1
    linelen = len(line)
    if linelen == 0:
        return 0
    iter = 0
    while iter < (linelen-1):
        if line[iter] == line[iter+1]:
            templen += 1
        else:
            if templen > maxlen:
                maxlen = templen
            templen = 1
        iter += 1
        if iter == ( linelen - 1 ):
            if templen > maxlen:
                maxlen = templen
            
    return maxlen

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert long_repeat('sdsffffse') == 4, "First"
    assert long_repeat('ddvvrwwwrggg') == 3, "Second"
    assert long_repeat('abababaab') == 2, "Third"
    assert long_repeat('') == 0, "Empty"
    print('"Run" is good. How is "Check"?')

Best Solution:

from itertools import groupby

def long_repeat(line):
    return max((sum(1 for _ in g) for k, g in groupby(line)), default=0)

11. 检测给定字符串序列中出现给定word的次数

Mysolution:

def count_words(text: str, words: set) -> int:
    return len([1 for i in words if i in text.lower()])


if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert count_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"}) == 3, "Example"
    assert count_words("Bananas, give me bananas!!!", {"banana", "bananas"}) == 2, "BANANAS!"
    assert count_words("Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
                       {"sum", "hamlet", "infinity", "anything"}) == 1, "Weird text"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

Best Solution:

def count_words(text, words):
    return sum(w in text.lower() for w in words)

12. 删除给定序列中的唯一存在元素

My Solution:

def checkio(data: list) -> list:
    #replace this for solution
    tempdata = data[:]
    historylist = []
    for item in tempdata:
        if item not in historylist:
            if tempdata.count(item) == 1:
                data.remove(item)
            else:
                historylist.append(item)
            
    return data

Best Solution:

def checkio(data: list) -> list:
    return [e for e in data if data.count(e) > 1]

13. 检测给定序列是否符合规则

My Solution:

def checkio(data):

    #replace this for solution
    if not isinstance(data,str):
        return False
    if len(data) < 10 :
        return False
    import re
    rgx1=re.compile(r'[0-9a-zA-Z]+')
    rgx2=re.compile(r'.*[0-9].*')
    rgx3=re.compile(r'.*[a-z].*')
    rgx4=re.compile(r'.*[A-Z].*')
    if not rgx1.match(data):
        return False
    if not rgx2.match(data):
        return False
    if not rgx3.match(data):
        return False
    if not rgx4.match(data):
        return False
    
    return True

Best Solution:

import re

DIGIT_RE = re.compile('\d')
UPPER_CASE_RE = re.compile('[A-Z]')
LOWER_CASE_RE = re.compile('[a-z]')

def checkio(data):
    """
    Return True if password strong and False if not
    
    A password is strong if it contains at least 10 symbols,
    and one digit, one upper case and one lower case letter.
    """
    if len(data) < 10:
        return False
    
    if not DIGIT_RE.search(data):
        return False

    if not UPPER_CASE_RE.search(data):
        return False

    if not LOWER_CASE_RE.search(data):
        return False
        
    return True

14. 检测给定序列中最经常出现的字母

My Solution:

def checkio(text: str) -> str:

    #replace this for solution
    import re
    mfnumber = 0
    historylist = []
    rgx = re.compile(r'[a-zA-Z]')
    for item in text:
        if not rgx.match(item):
            continue
        else:
            if item not in historylist:
                tempitem1 = item.upper()
                tempitem2 = item.lower()
                historylist.append(tempitem1)
                historylist.append(tempitem2)
                tempitemnumber = text.count(tempitem1) + text.count(tempitem2)
                if tempitemnumber > mfnumber :
                    mfnumber = tempitemnumber
                    mfletter = tempitem2
                elif tempitemnumber == mfnumber :
                    if tempitem2 < mfletter :
                        mfletter = tempitem2                 
            else:
                continue
    return mfletter
        

Best Solution:

import string

def checkio(text):
    """
    We iterate through latyn alphabet and count each letter in the text.
    Then 'max' selects the most frequent letter.
    For the case when we have several equal letter,
    'max' selects the first from they.
    """
    text = text.lower()
    return max(string.ascii_lowercase, key=text.count)

15. TBD

My Solution:

Best Solution:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值