Checkio--题目之Elementary(上)
来源:互联网 发布:spss有mac版吗 编辑:程序博客网 时间:2024/06/09 03:30
下面是做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 resultif __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 Falseif __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 0if __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 refind_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/
返回列表中最大最小数的差值,列表空返回0def 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 0def 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替换位leftdef left_join(phrases): s =",".join(phrases) st = s.replace("right","left") return stif __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/
输出给定数字每个位相乘结果,忽略0def checkio(number): num = 1 for x in str(number): if x != '0': num *= int(x) return numif __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 countif __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 Falseif __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 datet = (2010, 2, 3) #元组形式 调用date函数转换date(t[0], t[1], t[2])# ordate(*t)#程序主体:import timefrom datetime import datedef days_diff(date1, date2): """ Find absolute diff in days between dates """ f = date(*date1) e = date(*date2) ans = abs((f-e).days) return ansif __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 datetimedef 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/
#给定一个数字(字符串)和进制,输出他的intdef checkio(str_number, radix): try: return int(str_number,radix) except ValueError: return -1if __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))
“`
- Checkio--题目之Elementary(上)
- CHECKIO-题目之Elementary(下)
- checkio (Numbers Factory)
- checkio (数独)
- checkio--
- Elementary体验之安装Elementary OS
- SymPy学习之Elementary
- checkio (tic-tac-toe)
- CheckIO题解:OLD LIBRAY 里的部分题目
- Checkio - What does the cow say? 题目和答案
- 【checkio】House Password(初学正则表达式)
- 编程之美上的一些题目
- checkio (Brackets)
- Python Checkio
- Checkio--Friends
- checkio-medium
- CheckIO 中位数
- Java Puzzlers 之Puzzle 4: It's Elementary
- Struts+Spring注解名词解释
- LPC1768菜鸟学习之GPIO和外部中断
- 尚硅谷 hibernate4 总结
- IO流
- 由“单独搭建Mybatis”到“Mybatis与Spring的整合/集成”
- Checkio--题目之Elementary(上)
- 2-18
- Webview动态注入js脚本
- Android 开发 单元测试
- 条款07:为多态基类声明virtual析构函数
- IOS网络编程:HTTP
- mysql 不能启动 并 没有报错 原因
- 构建一个二叉堆实例
- 谈谈Fragment的构造函数、重新创建(recreate)及相关