下面是做CHECKIO的題目,Elementary的題目,題目很基礎,可以熟悉語言特性。關鍵看看別人怎麼寫。更好的部分很好。有很多可以學習的東西。
Even the last
http://www.checkio.org/mission/even-last/
def checkio(array):
"""
sums even-indexes elements and multiply at the last
"""
if len(array) == 0: return 0
return sum(array[0::2]) * array[-1]
#這裏array[0::2]表示取序號爲0,2,4,6....的元素,切片插座,2的參數表示步進
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, "Empty"
Monkey Typing
http://www.checkio.org/mission/monkey-typing/
def count_words(text, words):
result = 0
#無論單詞是否連在一起都可以直接判斷,字符串操作好方便
for w in words:
if w in text.lower():
result = result +1
#print w
return result
if __name__ == '__main__':
assert count_words(u"How aresjfhdskfhskd you?", {u"how", u"are", u"you", u"hello"}) == 3, "Example"
assert count_words(u"Bananas, give me bananas!!!", {u"banana", u"bananas"}) == 2, "BANANAS!"
assert count_words(u"Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
{u"sum", u"hamlet", u"infinity", u"anything"}) == 1, "Weird text"
Three words
http://www.checkio.org/mission/three-words/
判斷是否有連續的三個單詞,有輸出TRUE,否則FALSE
def checkio(words):
cout = 3
flag = 0
word = words.split()
for w in word:
if w.isalpha() and cout:
cout -= 1
flag = 1
if cout == 0:
return True
else:
cout = 3
if not flag :
return False
return False
if __name__ == '__main__':
assert checkio(u"Hello World hello") == True, "Hello"
assert checkio(u"He is 123 man") == False, "123 man"
assert checkio(u"1 2 3 4") == False, "Digits"
assert checkio(u"bla bla bla bla") == True, "Bla Bla"
assert checkio(u"Hi") == False, "Hi"
更好的:
def checkio(words):
succ = 0
for word in words.split():
succ = (succ + 1)*word.isalpha()
if succ == 3: return True
else: return False
Secret Message
http://www.checkio.org/mission/secret-message/
輸出給定字符串的所有大寫字母
def find_message(text):
"""Find a secret message"""
#lis =[]
l = "" #字符串型初始化
lis = list(text)
flag=0
#逐個遍歷字符串字符的簡單方法
for w in text:
#print w
if w.isupper():
flag =1
l += w
if flag == 0:
return ''
else:
return l
return 0
if __name__ == '__main__':
assert find_message(u"How are you? Eh, ok. Low or Lower? Ohhh.") == "HELLO", "hello"
assert find_message(u"hello world!") == "", "Nothing"
assert find_message(u"HELLO WORLD!!!") == "HELLOWORLD", "Capitals"
更好的:
find_message = lambda text: ''.join(filter(str.isupper, text))
#filter是內建函數,過濾器。用法filter(條件,對象),滿足條件的返回該值,即filter返回由seq隊列中使條件返回值爲真的元素組成的隊列。
import re
find_message = lambda text: re.sub(r'[a-z]|[^\w]|[\d]','',text)
def find_message(text):
return ''.join(c for c in text if c.isupper())
The Most Numbers
http://www.checkio.org/mission/most-numbers/
返回列表中最大最小數的差值,列表空返回0
def checkio(*args):
if not args:
return 0
return max(args) - min(args)
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"
def checkio(*args):
if not args: return 0
argslist = sorted( args )
return argslist[-1] - argslist[0]
Boolean Algebra
http://www.checkio.org/mission/boolean-algebra/
位運算
OPERATION_NAMES = ("conjunction", "disjunction", "implication", "exclusive", "equivalence")
def boolean(x, y, operation):
if(operation == 'conjunction'):
return (x and y)
if(operation == 'disjunction'):
return (x or y)
if(operation == 'implication'):
return (not x or y)
if(operation == 'exclusive'):
return (x ^ y)
if(operation == 'equivalence'):
return (not (x^y))
return
if __name__ == '__main__':
assert boolean(1, 0, u"conjunction") == 0, "and"
assert boolean(1, 0, u"disjunction") == 1, "or"
assert boolean(1, 1, u"implication") == 1, "material"
assert boolean(0, 1, u"exclusive") == 1, "xor"
assert boolean(0, 1, u"equivalence") == 0, "same?"
更好地:
def boolean(x, y, operation):
if operation == "conjunction": return x & y
if operation == "disjunction": return x | y
if operation == "implication": return (1 ^ x) | y
if operation == "exclusive": return x ^ y
if operation == "equivalence": return x ^ y ^ 1
return 0
def boolean(x, y, operation):
mapp = {"conjunction": lambda a, b: a and b,
"disjunction": lambda a, b: a or b,
"implication": lambda a, b: not a or b,
"exclusive": lambda a, b: a ^ b,
"equivalence": lambda a, b: not(a ^ b)}
return mapp[operation](x, y)
Right to Left
http://www.checkio.org/mission/right-to-left/
字符串替換,將right替換位left
def left_join(phrases):
s =",".join(phrases)
st = s.replace("right","left")
return st
if __name__ == '__main__':
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"
更好地:
def left_join(phrases):
return (",".join(phrases)).replace("right","left")
Digits Multiplication
http://www.checkio.org/mission/digits-multiplication/
輸出給定數字每個位相乘結果,忽略0
def checkio(number):
num = 1
for x in str(number):
if x != '0':
num *= int(x)
return num
if __name__ == '__main__':
assert checkio(123405) == 120
assert checkio(999) == 729
assert checkio(1000) == 1
assert checkio(1111) == 1
更好地:
def checkio(number):
total = 1
for i in str(number).replace('0', '1'):
total *= int(i)
return total
Count Inversions
http://www.checkio.org/mission/count-inversions/
統計多少個逆序數不在自己的順序上
def count_inversion(sequence):
"""
Count inversions in a sequence of numbers
"""
count = 0
for i in range(len(sequence)):
for j in range(i+1,len(sequence)):
if sequence[i] > sequence[j]:
count += 1
return count
if __name__ == '__main__':
assert count_inversion((1, 2, 5, 3, 4, 7, 6)) == 3, "Example"
assert count_inversion((0, 1, 2, 3)) == 0, "Sorted"
assert count_inversion((99, -99)) == 1, "Two numbers"
assert count_inversion((5, 3, 2, 1, 0)) == 10, "Reversed"
更好地:
def count_inversion(sequence):
count = 0
for i, x in enumerate(sequence[:-1]):
for y in sequence[i+1:]:
if x > y: count += 1
return count
The end of other
http://www.checkio.org/mission/end-of-other/
練習十二:
判斷給定多個字符串,是否有後綴
def checkio(words_set):
w = words_set
for a in w:
for b in w:
if a == b:
continue
elif a.endswith(b):
return True
return False
if __name__ == '__main__':
assert checkio({u"hello", u"lo", u"he"}) == True, "helLO"
assert checkio({u"hello", u"la", u"hellow", u"cow"}) == False, "hellow la cow"
assert checkio({u"walk", u"duckwalk"}) == True, "duck to walk"
assert checkio({u"one"}) == False, "Only One"
assert checkio({u"helicopter", u"li", u"he"}) == False, "Only end"
更巧妙:
def checkio(s):
return any(map(lambda x: any(map(x.endswith,s-set([x]))),s))
Days Between
http://www.checkio.org/mission/days-diff/
#計算日期差
#日期初始化實例:
from datetime import date
t = (2010, 2, 3) #元組形式 調用date函數轉換
date(t[0], t[1], t[2])
# or
date(*t)
#程序主體:
import time
from datetime import date
def days_diff(date1, date2):
"""
Find absolute diff in days between dates
"""
f = date(*date1)
e = date(*date2)
ans = abs((f-e).days)
return ans
if __name__ == '__main__':
assert days_diff((1982, 4, 19), (1982, 4, 22)) == 3
assert days_diff((2014, 1, 1), (2014, 8, 27)) == 238
assert days_diff((2014, 8, 27), (2014, 1, 1)) == 238
更好地:
from datetime import datetime
def days_diff(date1, date2):
return abs((datetime(*date1)-datetime(*date2)).days)
Binary count
http://www.checkio.org/mission/binary-count/
#把數字變成二進制,並且計算1的有多少位
def checkio(number):
return bin(number).count('1')
if __name__ == '__main__':
assert checkio(4) == 1
assert checkio(15) == 4
assert checkio(1) == 1
assert checkio(1022) == 9
Number Base
http://www.checkio.org/mission/number-radix/
#給定一個數字(字符串)和進制,輸出他的int
def checkio(str_number, radix):
try:
return int(str_number,radix)
except ValueError:
return -1
if __name__ == '__main__':
assert checkio(u"AF", 16) == 175, "Hex"
assert checkio(u"101", 2) == 5, "Bin"
assert checkio(u"101", 5) == 26, "5 base"
assert checkio(u"Z", 36) == 35, "Z base"
assert checkio(u"AB", 10) == -1, "B > A > 10"
更好地:
def checkio(*a):
try: return int(*a)
except ValueError: return -1
Common-words
http://www.checkio.org/mission/common-words/
找出兩個字符串中相同的字符串,並排序輸出
體會set用法,
def checkio(first, second):
a = set(first.split(','))
b = set(second.split(','))
x = a.intersection(b) # 這個要轉換爲set直接返回a,b相同的元素列表
x = sorted(x)
return ','.join(x)
if __name__ == '__main__':
assert checkio(u"hello,world", u"hello,earth") == "hello", "Hello"
assert checkio(u"one,two,three", u"four,five,six") == "", "Too different"
assert checkio(u"one,two,three", u"four,five,one,two,six,three") == "one,three,two", "1 2 3"
更好地:
def checkio(first, second):
"""
set data type has useful methods.
"""
first_set, second_set = set(first.split(",")), set(second.split(","))
common = first_set.intersection(second_set)
return ",".join(sorted(common))
def checkio(first, second):
first_set = set(first.split(","))
second_set = set(second.split(","))
return ",".join(sorted(first_set & second_set))
“`