Check iO:初学Python
The end of other
For language training our Robots want to learn about suffixes.
In this task, you are given a set of words in lower case. Check whether there is a pair of words, such that one word is the end of another (a suffix of another). For example: {"hi", "hello", "lo"} -- "lo" is the end of "hello", so the result is True.
Hints: For this task you should know how to iterate through set types and string data type functions. Read more about set type hereand string functions here.
Input: Words as a set of strings.
Output: True or False, as a boolean.
题目大义:给出一个含有单词的集合(set),如果某个单词是另一个单词的后缀,如"lo"是"hello"的后缀,则返回True,如果不存在则返回False。
一开始认为set可以使用index,就像数组般使用,可惜了,set并不支持。想想也合理,c++中的set也是不支持[]索引的,于是乎想到了for xx in xx形式,加上提示:str.endswith(suffix[, start[, end]]),恍然大悟,给出拙劣的Python代码
def checkio(words_set):
for words in words_set:
for other_words in words_set:
if other_words != words and other_words.endswith(words):
return True return False
Common Words
Let's continue examining words. You are given two string with words separated by commas. Try to find what is common between these strings. The words are not repeated in the same string.
Your function should find all of the words that appear in both strings. The result must be represented as a string of words separated by commas in alphabetic order.
Tips: You can easily solve this task with several useful functions:str.split, str.join and sorted. Also try using the built-in type -- set.
Input: Two arguments as strings.
Output: The common words as a string.
题目大义:给出两个字符串,找出在两个字符串中同时出现的单词,并按字典序输出
当然使用了str.split方法,然后想到set有in方法,于是乎得到这么一段代码
def checkio(first, second):
first_str = first.split(',')
words_set = set(first_str) second_str = second.split(',') result = [] for each in second_str:
if each in words_set:
result.append(each)
else:
words_set.add(each) result.sort() return ','.join(result);
接下来看了别人的解答,发现其实可以把两个字符串split后,转化为set,再使用set的intersection方法即可得到相同单词
Absolute sort
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.
Hints: This task can be easily solved using these functions: sorted andabs. You should try to use the key parameter for sorting.
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.
题目大义:按绝对值排序
还是C语言的思路,sorted中传入cmp函数,如果x < y返回负值,x > y返回正值,x = y返回0
def cmp(numberA, numberB):
return abs(numberA) - abs(numberB) def checkio(numbers_array):
return sorted(numbers_array, cmp)
不过既然用了Python如此高大上的语言,自然要显摆下,sorted还有一个参数为key,实际上sorted(number_array, key=abs)即可
Non-unique Elements
You are given a non-empty list of integers (X). For this task, you should return a list consisting of only the non-unique elements in this list. To do so you will need to remove all unique elements (elements which are contained in a given list only once). When solving this task, do not change the order of the list. Example: [1, 2, 3, 1, 3] 1 and 3 non-unique elements and result will be [1, 3, 1, 3].
题目大义:将数组中唯一的元素清除
还是C语言的思想,直接粗暴,首先是遍历求出唯一的元素,再使用数组的remove方法
def checkio(data): only = [] for each in data:
count = 0
for other in data:
if each == other:
count += 1 if count == 1:
only.append(each) for each in only:
data.remove(each) return data
当然我们有更高级的方法list = [x for x in data if x.count > 1],简单明了,使用了数组的另一种构造方法,使用了数组count方法
def checkio(data):
list = [x for x in data if data.count(x) > 1]
return list
新技能get
The Most Wanted Letter
You are given a text, which contains different english letters and punctuation symbols. You should find the most frequent letter in the text. The letter returned must be in lower case.
While checking for the most wanted letter, casing does not matter, so for the purpose of your search, "A" == "a". Make sure you do not count punctuation symbols, digits and whitespaces, only letters.
If you have two or more letters with the same frequency, then return the letter which comes first in the latin alphabet. For example -- "one" contains "o", "n", "e" only once for each, thus we choose "e".
Input: A text for analysis as a string (unicode for py2.7).
Output: The most frequent letter in lower case as a string.
题目大义:找出出现次数最多的字母,不区分大小写,如果出现次数相同,则取字典序最小的输出
一开始想需要诸如'a' : 0,即字母到数字的对应,于是想到dict;查阅str手册后,发现str.lower方法,将字符串转换为小写;最后是对dict的排序,需要先按字母排序,再按出现次序排序(ps:python中的排序是稳定的)
def checkio(text):
lower_text = text.lower() appear_time = {} for each in lower_text:
if each.islower():
if each not in appear_time:
appear_time[each] = 0
else:
appear_time[each] += 1 array = appear_time.items();
array.sort(key=lambda x:x[0])
array.sort(key=lambda x:x[1], reverse=True) return array[0][0]
不过呢,这是笨方法,没有充分利用Python的丰富资源,给出大神bryukh的解答
import string def checkio(text):
"""
We iterate through latyn alphabet and count each letter in the text.
Then 'max' selects the most frequent letter.
For the case when we have several equal letter,
'max' selects the first from they.
"""
text = text.lower()
return max(string.ascii_lowercase, key=text.count)
学艺不精,现在想来key的意思是每个元素的顺序由key决定吧,max的第一参数是ascii码的小写字母,相当于把26个字母算了个遍
Xs and Os Referee
def checkio(game_result):
winner = 'D' for row in game_result:
if row[0] == row[1] == row[2] and row[0] != '.':
winner = row[0] for col in range(0, 3):
if game_result[0][col] == game_result[1][col] == game_result[2][col] and game_result[0][col] != '.':
winner = game_result[0][col] if game_result[0][0] == game_result[1][1] == game_result[2][2] and game_result[0][0] != '.':
winner = game_result[0][0] if game_result[0][2] == game_result[1][1] == game_result[2][0] and game_result[0][2] != '.':
winner = game_result[0][2] return winner
此题的结论是python支持形如此等模式的判断: row[0] == row[1] == row[2], 即支持连等
再来看看大神代码
def checkio(result):
rows = result
cols = map(''.join, zip(*rows))
diags = map(''.join, zip(*[(r[i], r[2 - i]) for i, r in enumerate(rows)]))
lines = rows + list(cols) + list(diags) return 'X' if ('XXX' in lines) else 'O' if ('OOO' in lines) else 'D'
zip函数可将两个数组柔和在一起,如学生姓名name = ['bob', 'jenny'], 成绩grade = [80, 90], zip(name, grade) = [('bob', 80), ('jenny', 90)], 在函数调用中使用*list/tuple的方式表示将list/tuple分开,作为位置参数传递给对应函数(前提是对应函数支持不定个数的位置参数), 如test = ["XXX", "OOO", "..."], zip(*test) = [('X', 'O', '.'), ('X', 'O', '.'), ('X', 'O', '.')]
map函数接受两个参数, 第一个为函数名, 第二个为可迭代对象, 如array = [1, 2, 3], map(str, array) = ['1', '2', '3'], 即对第二个对象应用第一函数
Speech Module
FIRST_TEN = ["one", "two", "three", "four", "five", "six", "seven",
"eight", "nine"]
SECOND_TEN = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
OTHER_TENS = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy",
"eighty", "ninety"]
HUNDRED = "hundred" def checkio(number):
spoken = [] hundred_bit = number / 100 if hundred_bit > 0:
spoken.append(FIRST_TEN[hundred_bit - 1])
spoken.append(HUNDRED) remain = number % 100 if remain >= 10 and remain <= 19:
spoken.append(SECOND_TEN[remain % 10])
else:
decade = remain / 10
if decade > 0:
spoken.append(OTHER_TENS[decade - 2]) unit = remain % 10
if unit > 0:
spoken.append(FIRST_TEN[unit - 1]) return ' '.join(spoken)
python有个divmod函数, 即可返回商又可返回余数h, number
=
divmod
(number,
100
)
可以如此构造字符串
final_string
=
"%s%s%s"
%
(hundred_s, decade_s, unit_s)
使用strip去除字符,lstrip, rstrip; rstrip()去除右边空格
The Flat Dictionary
原来的代码没处理dict为空的情况
def flatten(dictionary):
#[] is a list
#() is a tuple
stack = [((), dictionary)] result = {} #result is a dict while stack:
path, current = stack.pop() #get a tuple for k, v in current.items(): #dict::items return key and values tuple
if isinstance(v, dict): #is a instance of dict
stack.append((path + (k,), v)) #add key to tuple such as (xxx, yyy, zzz) and the element in stack is like ((xxx, yyy, zzz), value)
else:
result["/".join((path + (k,)))] = v if len(current) == 0: #when the dict is empty
result["/".join(path)] = "" return result
(k,)一个元素的tuple
Pawn Brotherhood
alpha_table = "abcdefgh" def safe_pawns(pawns):
safe_count = 0 for spawn in pawns:
if spawn[1] == '':
continue pos = alpha_table.find(spawn[0])
str_row = str(int(spawn[1]) - 1) if pos == 0:
if (alpha_table[1] + str_row) in pawns:
safe_count += 1
continue if pos == 7:
if (alpha_table[6] + str_row) in pawns:
safe_count += 1
continue if (alpha_table[pos - 1] + str_row) in pawns or (alpha_table[pos + 1] + str_row) in pawns:
safe_count += 1 return safe_count
自定义了一个小写字母表, 找出某字母的前后字母, 如b的(a, c)
另外可以使用chr
(
ord
(pawn[
0
])
+
1
),
chr
(
ord
(pawn[
0
])
-
1
)获得前后字母, ord相当于获得字母的数码(如ascii码), chr是逆过程
How to find friends
思路简单,编码不易
def check_connection(network, first, second):
link_dictionary = dict() for link in network:
drones = link.split('-') link_dictionary.setdefault(drones[0], []).append(drones[1])
link_dictionary.setdefault(drones[1], []).append(drones[0]) future = []
visited = []
future.append(first) while future:
current = future.pop()
visited.append(current) extend = link_dictionary[current] if second in extend:
return True for each in extend:
if each not in visited:
future.append(each) return False
使用dict存储每个人的直接关系, 如{lyly : [lala, gege]}; 使用两个list, 其中一个表示已遍历过的人, 另一个表示即将遍历的人;
另外python中的二维数组可以这么定义: connection = [[False for col in range(5)] for row in range(5)], 即一个5*5的数组, 原先尝试过这么定义error = [[False] * 5] * 5, 发现只要修改了
error[0][0], 那么error[1][0], error[2][0] ...都修改了, 因为[False] * 5产生了一个一维数组, 而外面的*5只是产生了5个引用因此, 无论修改哪一个其余的均会改变.
观摩下大神的代码
def check_connection(network, first, second):
setlist = []
for connection in network:
s = ab = set(connection.split('-'))
# unify all set related to a, b
for t in setlist[:]: # we need to use copy
if t & ab: # check t include a, b
s |= t
setlist.remove(t)
setlist.append(s) # only s include a, b return any(set([first, second]) <= s for s in setlist)
将每条关系作为set, 若关系间交集不为空, 则求关系间的并集, 即关系圈;
最后查看first与second是否在某个关系圈中;
充分利用了set的操作, &交, |并, <=子集;
还有第12行的语法特性
Roman numerals
罗马数字的题目, 注意几个关键的数字即可: (100, 400, 500, 900) -> ('C', 'CD', 'D', 'CM'); (10, 40, 50, 90)->('X', 'XL', 'L', 'XC')
def checkio(data):
rel = '' thonsand = data / 1000
rel += thonsand * 'M' data %= 1000 table = [['C', 'CD', 'D', 'CM'], ['X', 'XL', 'L', 'XC']] pos = 100 for i in range(0, 2):
bit = data / pos
if bit > 0:
if bit < 4:
rel += bit * table[i][0]
elif bit == 4:
rel += table[i][1]
elif bit == 5:
rel += table[i][2]
elif bit == 9:
rel += table[i][3]
else:
rel += (table[i][2] + table[i][0] * (bit - 5)) data %= pos
pos /= 10 if data > 0:
unit = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X']
rel += unit[data - 1] #replace this for solution
return rel
另外还需注意没有个位数的情况, 即第30行所示
观摩JulianNicholls的代码
elements = { 1000 : 'M', 900 : 'CM', 500 : 'D', 400 : 'CD',
100 : 'C', 90 : 'XC', 50 : 'L', 40: 'XL',
10 : 'X', 9 : 'IX', 5 : 'V', 4: 'IV', 1 : 'I' } def checkio(data):
roman = '' for n in sorted(elements.keys(), reverse=True):
while data >= n:
roman += elements[n]
data -= n return roman
sorted(elements.keys(), reverse=True), 按key从大到小排列; 思路不错, 比数位对应的值大, 即加上该数位对应的字母, 并减去对应的数值, 直到data为0
Min and Max
需要处理不同数据类型; 另外*args, 表示的是位置参数, *kwargs表示的是key参数, args的类型为tuple类型, 参数为min(3, 2)时, args为(3, 2), 参数为min([3, 2])时, args为([3, 2], );
列表解析为[i for i in range(0, 1)], 而(i for i in range(0, 1))为generator, 通过.next()属性获取下一个元素, 它不像列表解析一次性生成所有元素, 每次调用next生成一个元素;
def min(*args, **kwargs):
key = kwargs.get("key", None) sort_source = args if len(args) > 1 else args[0] #tuple comprehension if isinstance(sort_source, set):
rel = sort_source.pop()
elif type(sort_source) == type((i for i in range(0, 1))):
rel = sort_source.next()
else:
rel = sort_source[0] if key != None:
for each in sort_source:
if key(each) < key(rel):
rel = each
else:
for each in sort_source:
if each < rel:
rel = each return rel
观摩Cjkjvfnby的代码
def get_first_from_sorted(args, key, reverse):
if len(args) == 1:
args = iter(args[0])
return sorted(args, key=key, reverse=reverse)[0] def min(*args, key=None):
return get_first_from_sorted(args, key, False) def max(*args, key=None):
return get_first_from_sorted(args, key, True)
无他, 在len(arg) == 1的情况, 仍然需要提取出实际的对象, 如([1, 2], )中的[1, 2]; 高明的地方在于使用了sorted, 省去了自己判断类型
Check iO:初学Python的更多相关文章
- Understanding Asynchronous IO With Python 3.4's Asyncio And Node.js
[转自]http://sahandsaba.com/understanding-asyncio-node-js-python-3-4.html Introduction I spent this su ...
- 初学Python
初学Python 1.Python初识 life is short you need python--龟叔名言 Python是一种简洁优美语法接近自然语言的一种全栈开发语言,由"龟叔&quo ...
- 无开发经验,初学python
1.无开发经验,初学python 如果你不会其他语言,python是你的第一门语言: A Byte of Python (简明python教程,这个有中文版简明 Python 教程)是非常好的入门 ...
- 初学 Python(十五)——装饰器
初学 Python(十五)--装饰器 初学 Python,主要整理一些学习到的知识点,这次是生成器. #-*- coding:utf-8 -*- import functools def curren ...
- 初学 Python(十四)——生成器
初学 Python(十四)--生成器 初学 Python,主要整理一些学习到的知识点,这次是生成器. # -*- coding:utf-8 -*- ''''' 生成式的作用: 减少内存占有,不用一次性 ...
- 初学 Python(十三)——匿名函数
初学 Python(十三)--匿名函数 初学 Python,主要整理一些学习到的知识点,这次是匿名函数. # -*- coding:utf-8 -*- #关键字lambda定义的函数都是匿名函数 #做 ...
- 初学 Python(十二)——高阶函数
初学 Python(十二)--高阶函数 初学 Python,主要整理一些学习到的知识点,这次是高阶函数. #-*- coding:utf-8 -*- ''''' 话说高阶函数: 能用函数作为参数的函数 ...
- 初学 Python(十一)——切片
初学 Python(十一)--切片 初学 Python,主要整理一些学习到的知识点,这次是切片. #-*- coding:utf-8 -*- ''''' 切片 ''' L = ['name','age ...
- 初学Python(十)——列表生成式
初学Python(十)--列表生成式 初学Python,主要整理一些学习到的知识点,这次是列表生成式. # -*- coding:utf-8 -*- ''''' 列表生成式 ''' #一行代码表达所有 ...
- 初学Python(九)——函数
初学Python(九)--函数 初学Python,主要整理一些学习到的知识点,这次是函数. 函数定义: # -*- coding:utf-8 -*- #函数的定义 def my_function(x) ...
随机推荐
- [转]ubuntu14.04安装好用的google拼音输入法
原文网址:http://jingyan.baidu.com/article/219f4bf7d4a183de442d38f2.html 装了ubuntu14.04后感觉自带的拼音输入法不好用的有没有, ...
- NOI2012 骑行川藏
http://www.lydsy.com/JudgeOnline/problem.php?id=2876 表示完全不会...... 还是跪拜大神吧 http://www.cnblogs.com/Ger ...
- Linux中部署JAVA程序
JAVA程序在开发完成后,需要部署到服务器,如果是WEB项目,需要部署到WEB服务器,否则部署到应用服务器. JAVA是跨平台的编程语言,服务器的操作系统可以是Windows.Linux或者其它,下面 ...
- poj1011 Sticks(dfs+剪枝)
Sticks Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 110416 Accepted: 25331 Descrip ...
- Python字典的操作与使用
字典的描述 字典是一种key-value的数据类型,使用就像我们上学用的字典,通过拼音(key)来查对应字的详细内容(value). 字典的特性 1.字典是无序的(不像列表一样有下标,它通过key来获 ...
- javaweb文件下载
最近搞了一下struts文件上传下载了,一个是通过struts自带的类实现的下载方法,一个是通用的下载方法: struts实现: FileDownloadAction.java package com ...
- mysql 1449 : The user specified as a definer ('root'@'%') does not exist 解决方法
权限问题,授权 给 root 全部sql 权限 mysql> grant all privileges on *.* to root@"%" identified by & ...
- LeetCode 58 Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For ...
- java后台訪问url连接——HttpClients
java后台訪问url,并传递数据--通过httpclient方式 须要的包,包可能多几个额外的,假设无用或者冲突删除就可以.httpclient是使用的是4.4.1的版本号:http://downl ...
- Filter过滤器实现登录检查
主要利用filter过滤掉未经登录而直接跳转到非登录访问页面.代码而言的话并不难,只是有几点问题需要注意一下. 1.使用filter需要配置web.xml,如果是/*那么在拦截后的页面会连带jsp页面 ...