博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Checkio代码闯关小计
阅读量:6590 次
发布时间:2019-06-24

本文共 12915 字,大约阅读时间需要 43 分钟。

首字母大写并增加标点关卡(Correct Sentence):

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 text[-1]!='.':    text=text+"."return textreturn text

if name == 'main':

print("Example:")
print(correct_sentence("greetings, friends"))

# These "asserts" are used for self-checking and not for an auto-testingassert 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."print("Coding complete? Click 'Check' to earn cool rewards!")

截取第一个单词(First Word)

import re
def first_word(text: str) -> str:
"""
returns the first word in a given text.
"""

your code here

a = re.compile(r".*?([a-zA-Z']+)")return a.match(text).group(1)

if name == 'main':

print("Example:")
print(first_word("Hello world"))

# These "asserts" are used for self-checking and not for an auto-testingassert first_word("Hello world") == "Hello"assert first_word(" a word ") == "a"assert first_word("don't touch it") == "don't"assert first_word("greetings, friends") == "greetings"assert first_word("... and so on ...") == "and"assert first_word("hi") == "hi"print("Coding complete? Click 'Check' to earn cool rewards!")

第二个相同字符引索(Second Index)

def second_index(text: str, symbol: str):
"""
returns the second index of a symbol in a given text
"""

your code here

a=text.find(symbol, text.find(symbol) + 1)#find函数的嵌套使用查询第二个字符if a==-1:    a=Nonereturn a

if name == 'main':

print('Example:')
print(second_index("sims", "s"))

# These "asserts" are used for self-checking and not for an auto-testingassert second_index("sims", "s") == 3, "First"assert second_index("find the river", "e") == 12, "Second"assert second_index("hi", " ") is None, "Third"assert second_index("hi mayor", " ") is None, "Fourth"assert second_index("hi mr Mayor", " ") == 5, "Fifth"print('You are awesome! All tests are done! Go Check it!')

最大值的键输出(Best Stock)

def best_stock(data):

your code here

new_dict = {v: k for k, v in data.items()}#将键与值反转存入新的字典return new_dict[ max(data.values())]#输出最大data的值并作为新的字典的键输出值

if name == 'main':

print("Example:")
print(best_stock({
'CAC': 10.0,
'ATX': 390.2,
'WIG': 1.2
}))

# These "asserts" are used for self-checking and not for an auto-testingassert best_stock({    'CAC': 10.0,    'ATX': 390.2,    'WIG': 1.2}) == 'ATX', "First"assert best_stock({    'CAC': 91.1,    'ATX': 1.01,    'TASI': 120.9}) == 'TASI', "Second"print("Coding complete? Click 'Check' to earn cool rewards!")

字符出现频率(Popular Words)

import re
def popular_words(text, words):

your code here

dic1={}for k in range(len(words)):    i = 0    a= re.finditer(words[k],text.lower())#返回全部相匹配字符串    for match in a:        i=i+1    dic1[words[k]] = i#存入字典以及i(字符频率)    k +=1return dic1

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

# These "asserts" are used for self-checking and not for an auto-testingassert popular_words('''

When I was One,

I had just begun.
When I was Two,
I was nearly new.
''', ['i', 'was', 'three']) == {
'i': 4,
'was': 3,
'three': 0
}
print("Coding complete? Click 'Check' to earn cool rewards!")
最贵商品排名(Bigger Price)
def bigger_price(limit, data):
"""
TOP most expensive goods
"""

your code here

list=[]def dic_key(data):        return data['price']#字典输出值while (limit>0):    limit-=1#排名的递归    list.append(max(data, key=dic_key))#最大值的字典存入列表    data.remove(max(data, key=dic_key))#移除最大值的字典return list

if name == 'main':

from pprint import pprint
print('Example:')
pprint(bigger_price(2, [
{"name": "bread", "price": 100},
{"name": "wine", "price": 138},
{"name": "meat", "price": 15},
{"name": "water", "price": 1}
]))

# These "asserts" using for self-checking and not for auto-testingassert bigger_price(2, [    {"name": "bread", "price": 100},    {"name": "wine", "price": 138},    {"name": "meat", "price": 15},    {"name": "water", "price": 1}]) == [    {"name": "wine", "price": 138},    {"name": "bread", "price": 100}], "First"assert bigger_price(1, [    {"name": "pen", "price": 5},    {"name": "whiteboard", "price": 170}]) == [{"name": "whiteboard", "price": 170}], "Second"print('Done! Looks like it is fine. Go and check it')

能整除后输出(Fizz buzz)

#Your optional code here
#You can import some modules or create additional functions

def checkio(number):

#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 solutiona = ''if number % 3 == 0:    a += 'Fizz'if number % 5 == 0:    a += ' Buzz'if number % 3 != 0 and  number % 5 != 0:    a=str(number)return a.strip(' ')

#Some hints:

#Convert a number in the string with str(n)

#These "asserts" using only for self-checking and not necessary for auto-testing

if name == 'main':
assert checkio(15) == "Fizz Buzz", "15 is divisible by 3 and 5"
assert checkio(6) == "Fizz", "6 is divisible by 3"
assert checkio(5) == "Buzz", "5 is divisible by 5"
assert checkio(7) == "7", "7 is not divisible by 3 or 5"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
最大值减最小值(The Most Numbers)
def checkio(*args):
if not args: return 0

argslist = sorted( args )#排序存入列表return argslist[-1] - argslist[0]#相减

#These "asserts" using only for self-checking and not necessary for auto-testing

if name == 'main':
def almost_equal(checked, correct, significant_digits):
precision = 0.1 ** significant_digits
return correct - precision < checked < correct + precision

assert almost_equal(checkio(1, 2, 3), 2, 3), "3-1=2"assert almost_equal(checkio(5, -5), 10, 3), "5-(-5)=10"assert almost_equal(checkio(10.2, -2.2, 0, 1.1, 0.5), 12.4, 3), "10.2-(-2.2)=12.4"assert almost_equal(checkio(), 0, 3), "Empty"print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

第0,2,4相加乘最后一位(Even the last)

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

#These "asserts" using only for self-checking and not necessary for auto-testing

if name == 'main':
assert checkio([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)5=30"
assert checkio([1, 3, 5]) == 30, "(1+5)
5=30"
assert checkio([6]) == 36, "(6)*6=36"
assert checkio([]) == 0, "An empty array = 0"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
大写字母获取( Secret Message Secret Message )
import re
def find_message(text):
"""Find a secret message"""
b=''
result=re.compile(r'[A-Z]+')
for a in result.findall(text):
b+=a
return b

if name == 'main':

#These "asserts" using only for self-checking and not necessary for auto-testing
assert find_message("How are you? Eh, ok. Low or Lower? Ohhh.") == "HELLO", "hello"
assert find_message("hello world!") == "", "Nothing"
assert find_message("HELLO WORLD!!!") == "HELLOWORLD", "Capitals"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
连续三个单词(Three Words)
def checkio(words):
b=0
a=words.split(' ')
for i in range(len(a)):#分隔
if a[i].isalpha():#判断字母
if b>=2:

return True            b+=1    else:b=0return False

#These "asserts" using only for self-checking and not necessary for auto-testing

if name == 'main':
assert checkio("Hello World hello") == True, "Hello"
assert checkio("He is 123 man") == False, "123 man"
assert checkio("1 2 3 4") == False, "Digits"
assert checkio("bla bla bla bla") == True, "Bla Bla"
assert checkio("Hi") == False, "Hi"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
N位置的N次方(index_power)
def index_power(array, n):
"""
Find Nth power of the element with index N.
"""
if n>=len(array):
return -1
else: return array[n]**n

if name == 'main':

#These "asserts" using only for self-checking and not necessary for auto-testing
assert index_power([1, 2, 3, 4], 2) == 9, "Square"
assert index_power([1, 3, 10, 100], 3) == 1000000, "Cube"
assert index_power([0, 1], 0) == 1, "Zero power"
assert index_power([1, 2], 3) == -1, "IndexError"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
右替换为左(left_join)
def left_join(phrases):
"""
Join strings and replace "right" to "left"
"""
b=''
for a in phrases :
b+=a+','#放在一个字符串中

return b.replace('right','left')[:-1]#替换

if name == 'main':

#These "asserts" using only for self-checking and not necessary for auto-testing
assert left_join(("left", "right", "left", "stop")) == "left,left,left,stop", "All to left"
assert left_join(("bright aright", "ok")) == "bleft aleft,ok", "Bright Left"
assert left_join(("brightness wright",)) == "bleftness wleft", "One phrase"
assert left_join(("enough", "jokes")) == "enough,jokes", "Nothing to replace"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
字符乘积(Digits Multiplication)
def checkio(number):
a = 1
for b in range(len(str(number))):
if str(number)[b]=='0':
a=a1
else:a=a
int(str(number)[b])
return a

#These "asserts" using only for self-checking and not necessary for auto-testing

if name == 'main':
assert checkio(123405) == 120
assert checkio(999) == 729
assert checkio(1000) == 1
assert checkio(1111) == 1
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
进制转换(Number Base)
def checkio(str_number, radix):

dict={}sum=0for i in range(0,10):#将数字和字母存入字典    dict[str(i)]=ia=len(str_number)-1for i in range(65,91):    dict[chr(i)]=i-55for i in str_number:#进制超出输出-1否则计算进制    if dict[i]>=radix:        return -1    else:            sum+=dict[i]*radix**a    a-=1return sum

#These "asserts" using only for self-checking and not necessary for auto-testing

if name == 'main':
assert checkio("AF", 16) == 175, "Hex"
assert checkio("101", 2) == 5, "Bin"
assert checkio("101", 5) == 26, "5 base"
assert checkio("Z", 36) == 35, "Z base"
assert checkio("AB", 10) == -1, "B > A = 10"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
绝对值排序(Absolute sorting)
def checkio(numbers_array):
dict={}
list=[]
for a in numbers_array:
dict[abs(a)]=a
list.append(abs(a))
list.sort()
for a in range(len(list)):
list[a]=dict[list[a]]
return list

#These "asserts" using only for self-checking and not necessary for auto-testing

if name == 'main':
def check_it(array):
if not isinstance(array, (list, tuple)):
raise TypeError("The result should be a list or tuple.")
return list(array)

assert check_it(checkio((-20, -5, 10, 15))) == [-5, 10, 15, -20], "Example"  # or (-5, 10, 15, -20)assert check_it(checkio((1, 2, 3, 0))) == [0, 1, 2, 3], "Positive numbers"assert check_it(checkio((-1, -2, -3, 0))) == [0, -1, -2, -3], "Negative numbers"print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

高频率字符(The Most Frequent)

def most_frequent(data):
"""
determines the most frequently occurring string in the sequence.
"""

your code here

b=''c=0for a in data:   if data.count(a)>c:        b=a   else:continuereturn b

if name == 'main':

#These "asserts" using only for self-checking and not necessary for auto-testing
print('Example:')
print(most_frequent([
'a', 'b', 'c',
'a', 'b',
'a'
]))

assert most_frequent([    'a', 'b', 'c',     'a', 'b',    'a']) == 'a'assert most_frequent(['a', 'a', 'bi', 'bi', 'bi']) == 'bi'print('Done')

元组(Easy Unpack)

def easy_unpack(elements):
"""
returns a tuple with 3 elements - first, third and second to the last
"""

your code here

a =(elements[0],elements[2],elements[-2])return a

if name == 'main':

#These "asserts" using only for self-checking and not necessary for auto-testing
assert easy_unpack((1, 2, 3, 4, 5, 6, 7, 9)) == (1, 3, 7)
assert easy_unpack((1, 1, 1, 1)) == (1, 1, 1)
assert easy_unpack((6, 3, 7)) == (6, 7, 3)
print('Done! Go Check!')
时间(date_time)
def date_time(time):
#replace this for solution
dict={'01':'January','02':'February','03':'March','04':'April','05':'May','06':'June','07':'July','08':
'August','09':'September','10':'October','11':'November','12':'December'}
a = int(time[0:2])
b= int(time[11:13])
c= int(time[14:16])
if c==1 and b==1:
time= str(a)+' '+dict[time[3:5]]+' '+time[6:10]+' year '+str(b)+' hour '+str(c)+' minute'
return time
else:
time= str(a)+' '+dict[time[3:5]]+' '+time[6:10]+' year '+str(b)+' hours '+str(c)+' minutes'
return time

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

转载于:https://blog.51cto.com/12903345/2104119

你可能感兴趣的文章
关于C语言的问卷调查
查看>>
Eclipse rap 富客户端开发总结(12) :Rap 优化之组件的销毁
查看>>
uwsgi+django 配置
查看>>
理解session 和 cookie 哦
查看>>
angular components
查看>>
《Javascript高级程序设计》读书笔记之bind函数详解
查看>>
C盘压缩,电脑无法正常启动的解决方法?
查看>>
移动web性能优化笔记
查看>>
()-servlet.xml中剥离出的hibernate.cfg.xml
查看>>
WindowsServer2008配置MySql Proxy
查看>>
使用canvas输出base64_url
查看>>
真机调试DDMS无法访问Data
查看>>
LeetCode算法题-Average of Levels in Binary Tree(Java实现)
查看>>
LeetCode算法题-Unique Morse Code Words(Java实现)
查看>>
Hudson + SVN + Maven 持续集成实现自动化编译、打包、部署(over SSH 和 Deploy war/ear to a container 两种部署方式)...
查看>>
常用正则
查看>>
会议1.8
查看>>
HDU 5988 费用流 16青岛银牌题?
查看>>
SQLSERVER 维护计划无法删除
查看>>
python-迭代器模式
查看>>