pyCheckio -- Home

1. Solve The Most Wanted Letter

这道题的要求是提取出一个给定字符串中出现次数最多的字母的小写形式。代码如下:

def checkio(text):
    text = text.lower()  # 转换为小写形式
    results = {}  # 设两个空字典
    result = {}
    for letter in text:  # 遍历字符串中字符
        if letter not in results and letter.isalpha():  #  如果字符为出现在results字典中且是该字符为字母
            results[letter] = text.count(letter)   # 记录该字符出现次数
    num = sorted(results.items(), key=lambda x: x[1], reverse=True)[0][1]  # 降序排序results字典并提取最大数字
    for k, value in results.items():   # 遍历results中键值对
        if value == num:  # 如果元素个数与最大值相同则输出该元素
            result[k] = value  
    sorted_dicts = sorted(result.items(), key=lambda x: x[0])[0][0]   # 按字母表顺序对个数相同的元素进行排序并输出第一个值
    print(sorted_dicts)
    return sorted_dicts

这里需要注意的是字典的排序方式,具体介绍如下:

def sortDict():
    # 函数原型:sorted(dic,value,reverse)
    # 按字典中的键进行升序排序
    print("按键进行升序排序结果为:",\
          sorted(dic.items(), key=lambda x: x[0], reverse=False))
    # 按字典中的键进行降序排序
    print("按键进行降序排序结果为:",\
          sorted(dic.items(), key=lambda x: x[0], reverse=True))
    # 按字典中的值进行升序排序
    print("按值进行升序排序结果为:",\
          sorted(dic.items(), key=lambda x: x[1], reverse=False))
    # 按字典中的值进行降序排序
    print("按值进行降序排序结果为:",\
          sorted(dic.items(), key=lambda x: x[1], reverse=True))

最佳答案:

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)

2. Non-unique Elements

该题目要求去除列表中出现次数仅为1次的字符,并在不改变原位置的条件下输出列表。代码如下:

def unique(data):
    result = []
    for i in data:
        if data.count(i) > 1:
            result.append(i)
    print(result)
    return result

最佳答案如下:

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

3. Monkey Typing

查找一个字符串中包含的指定元组中元素的个数,代码如下:

import re
def count_words(text, word):
    count = 0
    text = text.lower()
    for i in word:
        if re.search(i, text):
            count = count + 1
    print(count)
    return count

最佳答案:

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

4. Xs and Os Referee

井字游戏,代码如下:

def checkio(game_result):
    a = []
    rows = game_result
    cols = list(map(''.join, zip(*rows)))
    for i, r in enumerate(rows):
        b = r[i] + r[2-i]
        a.append(b)
        diags = list(map(''.join, zip(*a)))
    lines = rows + cols + diags
    print(rows, cols, a)
    if 'XXX' in lines:
        print('X')
        return 'X'
    elif 'OOO' in lines:
        print('O')
        return 'O'
    else:
        print('D')
        return 'D'

关于enumerate函数的介绍,参考教程

关于zip函数的介绍,参考教程

关于map函数的介绍,参考教程



猜你喜欢

转载自blog.csdn.net/muumian123/article/details/80564506
今日推荐