IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> CheckiO Python编程 INITIATION -> 正文阅读

[Python知识库]CheckiO Python编程 INITIATION

Split Pairs

Split the string into pairs of two characters. If the string contains an odd number of characters, then the missing second character of the final pair should be replaced with an underscore (’’).
将字符串分割为两个字符对。如果字符串包含奇数个字符,那么最后一对中缺失的第二个字符应该用下划线(’
’)替换。

Input: A string.

Output: An iterable of strings.

Example:

split_pairs(‘abcd’) == [‘ab’, ‘cd’]
split_pairs(‘abc’) == [‘ab’, ‘c_’]

Precondition: 0<=len(str)<=100

def split_pairs(a):
    res = []
    num = len(a)//2
    for i in range(num):
        res.append(a[0:2])
        a = a[2:]
    if a != '':
        res.append(a+'_')
    return res

if __name__ == '__main__':
    print("Example:")
    print(list(split_pairs('abcd')))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert list(split_pairs('abcd')) == ['ab', 'cd']
    assert list(split_pairs('abc')) == ['ab', 'c_']
    assert list(split_pairs('abcdf')) == ['ab', 'cd', 'f_']
    assert list(split_pairs('a')) == ['a_']
    assert list(split_pairs('')) == []
    print("Coding complete? Click 'Check' to earn cool rewards!")
def split_pairs(a):
    a += '_' if len(a) % 2 else ''
    return [a[i:i + 2] for i in range(0, len(a), 2)]

def split_pairs(a):
    return [ch1+ch2 for ch1,ch2 in zip(a[::2],a[1::2]+'_')]

Beginning Zeros

You have a string that consist only of digits. You need to find how many zero digits (“0”) are at the beginning of the given string.
你有一个只由数字组成的字符串。需要找到在给定字符串的开头有多少个零(“0”)。

Input: A string, that consist of digits.

Output: An Int.

Example:

beginning_zeros(‘100’) == 0
beginning_zeros(‘001’) == 2
beginning_zeros(‘100100’) == 0
beginning_zeros(‘001001’) == 2
beginning_zeros(‘012345679’) == 1
beginning_zeros(‘0000’) == 4

Precondition: 0-9

def beginning_zeros(number: str) -> int:
    # your code here
    return len(number)-len(number.lstrip('0'))

if __name__ == '__main__':
    print("Example:")
    print(beginning_zeros('100'))
    # These "asserts" are used for self-checking and not for an auto-testing
    assert beginning_zeros('100') == 0
    assert beginning_zeros('001') == 2
    assert beginning_zeros('100100') == 0
    assert beginning_zeros('001001') == 2
    assert beginning_zeros('012345679') == 1
    assert beginning_zeros('0000') == 4
    print("Coding complete? Click 'Check' to earn cool rewards!")

Nearest Value

Find the nearest value to the given one.
You are given a list of values as set form and a value for which you need to find the nearest one.
For example, we have the following set of numbers: 4, 7, 10, 11, 12, 17, and we need to find the nearest value to the number 9. If we sort this set in the ascending order, then to the left of number 9 will be number 7 and to the right - will be number 10. But 10 is closer than 7, which means that the correct answer is 10.

A few clarifications:

  • If 2 numbers are at the same distance, you need to choose the
    smallest one;
  • The set of numbers is always non-empty, i.e. the size is >=1;
  • The given value can be in this set, which means that it’s the answer;
  • The set can contain both positive and negative numbers, but they are
    always integers;
  • The set isn’t sorted and consists of unique numbers.

Input: Two arguments. A list of values in the set form. The sought value is an int.

Output: Int.

Example:

nearest_value({4, 7, 10, 11, 12, 17}, 9) == 10
nearest_value({4, 7, 10, 11, 12, 17}, 8) == 7

def nearest_value(values: set, one: int) -> int:
    values = sorted(values)
    le = len(values)
    if one < values[0]:
        return values[0]
    if one > values[-1]:
        return values[-1]
    while(1):
        if one <= values[len(values)//2]:
            if one >= values[len(values)//2-1]:
                return values[len(values)//2] if abs(one-values[len(values)//2]) < abs(one-values[len(values)//2-1]) else values[len(values)//2-1]
            else:
                values = values[:len(values)//2]
        else:
            if one <= values[len(values) // 2 + 1]:
                return values[len(values)//2] if abs(one-values[len(values)//2]) <= abs(one-values[len(values)//2+1]) else values[len(values)//2+1]
            else:
                values = values[len(values) // 2:]

if __name__ == '__main__':
    print("Example:")
    print(nearest_value({4, 7, 10, 11, 12, 17}, 9))
    # These "asserts" are used for self-checking and not for an auto-testing
    assert nearest_value({4, 7, 10, 11, 12, 17}, 9) == 10
    assert nearest_value({4, 7, 10, 11, 12, 17}, 8) == 7
    assert nearest_value({4, 8, 10, 11, 12, 17}, 9) == 8
    assert nearest_value({4, 9, 10, 11, 12, 17}, 9) == 9
    assert nearest_value({4, 7, 10, 11, 12, 17}, 0) == 4
    assert nearest_value({4, 7, 10, 11, 12, 17}, 100) == 17
    assert nearest_value({5, 10, 8, 12, 89, 100}, 7) == 8
    assert nearest_value({-1, 2, 3}, 0) == -1
    print("Coding complete? Click 'Check' to earn cool rewards!")
def nearest_value(values: set, one: int) -> int:
    return min(sorted(values), key = lambda i: abs(i - one)) 

Between Markers (simplified)

You are given a string and two markers (the initial one and final). You have to find a substring enclosed between these two markers. But there are a few important conditions.

This is a simplified version of the Between Markers mission.

  • The initial and final markers are always different.
  • The initial and final markers are always 1 char size.
  • The initial and final markers always exist in a string and go one after another.

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

Output: A string.

Example:

between_markers(‘What is >apple<’, ‘>’, ‘<’) == ‘apple’

How it is used: For text parsing.

Precondition: There can’t be more than one final and one initial markers.

def between_markers(text: str, begin: str, end: str) -> str:
    """
        returns substring between two given markers
    """
    return text[text.index(begin)+1:text.index(end)]
    
if __name__ == '__main__':
    print('Example:')
    print(between_markers('What is >apple<', '>', '<'))
    # These "asserts" are used for self-checking and not for testing
    assert between_markers('What is >apple<', '>', '<') == "apple"
    assert between_markers('What is [apple]', '[', ']') == "apple"
    assert between_markers('What is ><', '>', '<') == ""
    assert between_markers('>apple<', '>', '<') == "apple"

Correct Sentence

For the input of your function, you will be given one sentence. You have to return a corrected version, that starts with a capital letter and ends with a period (dot).

Pay attention to the fact that not all of the fixes are necessary. If a sentence already ends with a period (dot), then adding another one will be a mistake.

Input: A string.

Output: A string.

Example:

1 correct_sentence(“greetings, friends”) == “Greetings, friends.”
2 correct_sentence(“Greetings, friends”) == “Greetings, friends.”
3 correct_sentence(“Greetings, friends.”) == “Greetings, friends.”

Precondition: No leading and trailing spaces, text contains only spaces, a-z A-Z , and .

def correct_sentence(text: str) -> str:
    """
        returns a corrected sentence which starts with a capital letter
        and ends with a dot.
    """
    
    return text[0].upper() + text[1:] + ("." if text[-1] != "." else "")

if __name__ == '__main__':
    print("Example:")
    print(correct_sentence("greetings, friends"))
    print(correct_sentence("welcome to New York"))
    
    # These "asserts" are used for self-checking and not for an auto-testing
    assert correct_sentence("greetings, friends") == "Greetings, friends."
    assert correct_sentence("Greetings, friends") == "Greetings, friends."
    assert correct_sentence("Greetings, friends.") == "Greetings, friends."
    assert correct_sentence("hi") == "Hi."
    assert correct_sentence("welcome to New York") == "Welcome to New York."

Is Even

Check if the given number is even or not. Your function should return True if the number is even, and False if the number is odd.

Input: An int.

Output: A bool.

Example:

is_even(2) == True
is_even(5) == False
is_even(0) == True

How it’s used: (math is used everywhere)

Precondition: both given ints should be between -1000 and 1000

def is_even(num: int) -> bool:
    # return not(num%2)
    return num & 1 == 0

if __name__ == '__main__':
    print("Example:")
    print(is_even(2))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert is_even(2) == True
    assert is_even(5) == False
    assert is_even(0) == True
    print("Coding complete? Click 'Check' to earn cool rewards!")
  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2021-12-06 15:12:29  更:2021-12-06 15:13:55 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/16 3:45:49-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码