CheckiO练习----Elementary

Say Hi

We have prepared a set of Editor's Choice Solutions. You will see them first after you solve the mission. In order to see all other solutions you should change the filter.

你的任务是编写一个根据给出的属性参数来介绍一个人的函数

输入: 两个参数。一个字符串(str)和一个正整数(int)。

输出: 字符串(str)。

def say_hi(name: str, age: int) -> str:
    """
        Hi!
    """
    # your code here
    
    return "Hi. My name is {} and I'm {} years old".format(name, age)#使用format函数格式化字符串到指定位置

Correct Sentence

对于你的功能的输入将被赋予一个句子。 您必须以某种方式返回其固定副本,以便始终以大写字母开头并以点结束。
请注意并非所有修复都是必需的。 如果一个句子已经以一个点结尾,那么添加另一个句子将是一个错误。

Input: A string.

Output: A string.

def correct_sentence(text: str) -> str:
    """
        returns a corrected sentence which starts with a capital letter
        and ends with a dot.
    """
    # your code here
    text = text[0].upper() + text[1:]#将字符串首字母大写并连接后面的字符串成为一个新的字符串
    if not text.endswith('.'):#如果字符串结尾不为'.'则在结尾添加'.'
        text += '.'
    
    return text#返回处理过的字符串
First Word

给你一个字符串,你必须找到它的第一个单词。
解决任务时要注意以下几点:
字符串中可以有点和逗号。
字符串可以以字母或例如点或空格开头。
一个词可以包含一个撇号,它是一个词的一部分。
整个文本可以用一个词来表示,就是这样。

def first_word(text: str) -> str:
    """
        returns the first word in a given text.
    """
    # your code here
    text = text.replace('.', ' ').replace(',', ' ').strip()#使用字符串replace方法将'.'','转换成空格,再用字符串strip方法移除字符串前后空格
    text = text.split()#用字符串split方法分割字符串
    return text[0]#返回字符串第一个单词
Second Index


给你两个字符串,你必须找到第一个字符串第二个字符串的索引。
让我们来看看第一个例子,你需要在单词“sims”中找到第二个“s”。 用函数索引很容易找到它的第一次出现,或者找到哪个指出“s”是单词“sims”中的第一个符号,因此第一次出现的索引是0.但是我们必须找到第二个“ s“,这是连续第4次,这意味着第二次发生的指数(以及对问题的回答)是3。

Input: Two strings.

Output: Int or 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: #如果该字母在字符串中仅出现一次,则返回None
        return None
    first = text.find(symbol)#使用find方法找到该字母在字符串中第一次出现位置
    return text.find(symbol, first + 1)#将find方法起始位置设为字母第一次出现后一位,返回得到字母出现第二次位置

Between Markers

给你一个字符串和两个标记(初始和最终)。 你必须在这两个标记之间找到一个子串。 但是有一些重要的条件:
最初和最后的标记总是不同的。
如果没有初始标记,则应将开始视为字符串的开始。
如果没有最终标记,则应该将结尾视为字符串的结尾。
如果缺少初始标记和最终标记,则只需返回整个字符串即可。
如果最后的标记站在最初的标记之前,则返回一个空字符串。


Input: Three arguments. All of them are strings. The second and third arguments are the initial and final markers.

Output: A string.

def between_markers(text: str, begin: str, end: str) -> str:
    """
        returns substring between two given markers
    """
    # your code here
    if begin in text:#如果初始标记在字符串中,则将字符串开始下标设为初始标记后一位
        b = text.find(begin) + len(begin)
    else:#如果没有初始标记则将开始下标设为0
        b = 0
    if end in text:#如果结束标记在字符串中,将结束下标设为结束标记位置;若不在,则设置结束下标为字符串结尾
        e = text.find(end)
    else:
        e = len(text)
    
    return text[b:e]
Best Stock


You are given the current stock prices. You have to find out which stocks cost more.

Input: The dictionary where the market identifier code is a key and the value is a stock price.

Output: A string and the market identifier code.

def best_stock(data):
    # your code here
    max = 0
    num = ''
    for i in data:#循环遍历data,data为一个字典
        if data[i] > max:#如果data[i]的值大于最大值则交换它们的值
            max = data[i]
            num = i#将num的值指向最大值的键i
    return num

Popular Words

在这个任务中,你的任务是确定文本中某些单词的受欢迎程度。
在函数的输入处给出2个参数:文本和您需要确定其流行度的单词数组。
解决这个任务时要注意以下几点:
应在所有登记册中查找这些词。 这意味着如果你需要找到一个单词“one”,那么诸如“one”,“One”,“oNe”,“ONE”等词将会起作用。
搜索词总是用小写表示。
如果这个单词没有被发现,那么它必须在字典中返回0(零)值。

Input: The text and the search words array.

Output: The dictionary where the search words are the keys and values are the number of times when those words are occurring in a given text.

def popular_words(text: str, words: list) -> dict:
    # your code here
    aDict = {}#定义一个字典
    text = text.lower()#使用lower方法将字符串全小写
    str = text.split()#将字符串切割成'I am alive'.split() --> ['I', 'am', 'alive']类似形式
    for s in words:
        aDict[s] = str.count(s)#使用count函数统计s在字符串中出现的次数,并将其赋给字典键s所对应的值
    return aDict

Bigger Price

你有一张桌子,里面有所有商品。 数据表示为一系列的字典
您的任务是找到最昂贵的商品。 我们正在寻找的数量将作为第一个参数给出,整个数据将作为第二个参数

Input: int and list of dicts. Each dicts has two keys "name" and "price"

Output: the same as the second Input argument.

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]#sorted函数可以对所有可迭代对象进行排序,key -- 主要是用来进行比较的元素,在这里对字典里的'price'键进行排序,reverse=True表示从大到小排序(默认为从小到大),limit限制排序的长度
Fizz Buzz

“Fizz buzz”是一款文字游戏,我们将用它来教授机器人关于师的事情。 让我们学习电脑吧。
你应该写一个函数来接收一个正整数并返回:
如果数字可以被3和5整除,那么“Fizz Buzz”;
如果数字可以被3整除,则为“Fizz”;
如果数字可以被5整除,则发出“Buzz”;
该数字作为其他情况下的字符串。

Input: A number as an integer.

Output: The answer as a string.

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.

    # replace this for solution
    if not number % 15:
        return 'Fizz Buzz'
    elif not number % 3:
        return 'Fizz'
    elif not number % 5:
        return 'Buzz'
    else:
        return str(number)

The Most Numbers

我们来处理数字。
给你一个数组(浮点数)。 您应该找到最大和最小元素之间的差异。 你的函数应该能够处理未定义数量的参数。 对于一个空的参数列表,该函数应该返回0。
计算机硬件中将浮点数表示为基2(二进制)分数。 所以我们应该以±0.001的精度检查结果。
想想如何使用任意数量的参数。

Input: An arbitrary number of arguments as numbers (int, float).

Output: The difference between maximum and minimum as a number (int, float).

def checkio(*args):#其实该题的意思就是求列表中最大值和最小值的差
    if not args:
        return 0
    else:
        return max(args) - min(args)#使用max和min找出最大最小值相减得出结果

Even the last

给你一个整数数组,需要你把具有偶数索引的元素相加(0,2,4 ...),然后把相加后得到的数与最后一个元素相乘。 不要忘记,第一个元素的索引是0。

如果传入的是一个空数组,则应该返回0。

输入: 一个整数列表

输出: 你得出的答案(整数值类型)

def checkio(array):
    """
        sums even-indexes elements and multiply at the last
    """
    sums = 0
    if len(array) == 0:
        return 0
    else:
        for i in range(len(array)):
            if i % 2 == 0:
                sums += array[i]
        return sums * array[-1]
Secret Message

曾经试图在没有使用邮政服务的情况下向他人发送秘密消息? 你可以用报纸来告诉你的秘密。 即使有人发现你的信息,也很容易将它们剔除,以及它的偏执狂和伪造的阴谋论。 隐藏秘密信息的最简单方法之一是使用大写字母。 让我们找到一些这些秘密消息。
给你一段文字。 按照它们出现在文本中的顺序,将所有大写字母收集在一个单词中。
例如:text = "How are you? Eh, ok. Low or Lower? Ohhh."如果我们收集所有的大写字母,就会得到“HELLO”的信息。

Input: A text as a string (unicode).

Output: The secret message as a string or an empty string.

def find_message(text: str) -> str:
    """Find a secret message"""
    return ''.join(c for c in text if c.isupper())#使用join方法将字符连接成一个新的字符串。用列表解析排除所有小写字母。

Three Words

让我们教机器人区分单词和数字。
给你一个字符串,用空白(一个空格)分隔单词和数字。 单词只包含字母。 您应该检查字符串是否包含三个字连续。 例如,字符串“start 5 one two three 7 end”连续包含三个单词。
输入:包含文字的字符串。
输出:作为布尔值的答案。

def checkio(words: str) -> bool:
    c = 0
    for i in words.split():#将用split方法分割的字符串for循环遍历
        if i.isalpha():#如果是字母的话则c自增1
            c += 1
        else:#关键点在这,如果其中有一次不是字母,都将c=0
            c = 0
        if c >= 3:#如果连续三次都是字母返回True
            return True
    else:
        return False
Index Power

给出一个正数和数N的数组。您应该在索引为N的数组中找到元素的N次方。如果N在数组外,则返回-1。 不要忘记,第一个元素的索引为0。
我们来看几个例子:
- array = [1,2,3,4],N = 2,则结果为32 == 9;
- array = [1,2,3]和N = 3,但是N在数组外,所以结果是-1。

Input: Two arguments. An array as a list of integers and a number as a integer.

Output: The result as an integer.

def index_power(array: list, n: int) -> int:
    """
        Find Nth power of the element with index N.
    """
    '''if n < len(array):
        for i in range(len(array)):
            if i == n:
                return array[i] ** n
    else:
        return -1'''
    return pow(array[n], n) if n < len(array) else -1#如果n下标在列表内,则将n下标的值做n次方运算,如果不在则返回-1
    

Right to Left

其中一个机器人负责一项简单的任务:将一系列字符串合并成一个句子,以产生如何绕过船只的指示。 但是这个机器人是左撇子,倾向于开玩笑和迷惑其惯用右手的朋友。
给你一串字符串。 您应该将这些字符串连接到初始字符串用逗号分隔的文本块中。 作为对右手机器人的一个笑话,你应该把所有的“right”这个词全部替换为“left”,即使它是另一个词的一部分。 所有字符串都以小写字母给出。

Input: A sequence of strings as a tuple of strings (unicode).

Output: The text as a string.

def left_join(phrases):
    """
        Join strings and replace "right" to "left"
    """
    return ','.join(phrases).replace('right', 'left')#使用replace方法将'right'替换成'left'后用join将新字符串用,连接

Digits Multiplication

给你一个正整数,请你写一个函数来实现:传入正整数的每一位(不包括00)的乘积

例如:给你 123405, 你应该这样处理 1*2*3*4*5=120(别忘了把0丢掉)

输入: 一个正整数.

输出: 正整数的每一位的乘积

def checkio(number: int) -> int:
    result = 1
    for i in str(number):
        if i != '0':
            result *= int(i)
    return result
Number Base

你是否还记得数学课上学过的底数(对数)和 计数系统(进制)? 让我们来重温练习一下吧。

给你一个字符串格式的正数和一个小于37大于1的整数型底数,用你写出来的方法来把他们转换为底数为10(十进制)的形式。 任务使用数字和‘A-Z’来作为字符串格式的正数。

注意数字无法转换的情况。 例如:“1A”不能用基数9进行转换。对于这些情况,你的函数应该返回-1。

输入: 两个参数,一个字符串参数的正数和一个整数参数底数。

输出: 一个被转换完的十进制整数。

def checkio(str_number: str, radix: int) -> int:
    try:#这里使用try是因为int容易引发一个ValueError使程序终止
        return int(str_number, radix)#python的int函数可以转换进制,第一位输入要转换的数字,第二位输入要转换的进制
    except ValueError:
        return -1
Absolute sorting

Let's try some sorting. Here is an array with the specific rules.

The array (a tuple) has various numbers. You should sort it, but sort it by absolute value in ascending order. For example, the sequence (-20, -5, 10, 15) will be sorted like so: (-5, 10, 15, -20). Your function should return the sorted list or tuple.

Precondition: The numbers in the array are unique by their absolute values.

Input: An array of numbers , a tuple..

Output: The list or tuple (but not a generator) sorted by absolute values in ascending order.

Addition: The results of your function will be shown as a list in the tests explanation panel.

def checkio(numbers_array: tuple) -> list:
    return sorted(numbers_array, key=abs)#题目要求将元组按照数的绝对值排序,巧用sorted函数key,key=后接一个函数abs,表示按照绝对值排序
The Most Frequent

你有一系列字符串,你要从中找出出现频率最高的字符串。

输入: 一个字符串组成的列表

输出: 一个字符串.

def most_frequent(data: list) -> str:
    """
        determines the most frequently occurring string in the sequence.
    """
    # your code here
    '''
        for i in data:
    '''
    return max(data, key=data.count)#巧用max函数,用key对数据进行处理指向data.count所有字符串出现次数,再用max判断出最大次数
Easy Unpack

在这里你的任务是创建得到一个元组,并返回一个包含三个元素(第一,第三和倒数第二的给定元组)的元组与的功能。

输入: 一个不少于三个元素的元组

输出: 一个元组.

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



你可能感兴趣的:(python)