python学习笔记
1.判断是否是整数:
is_integer;x%1==0;
2.平方:
x**2;pow(x,2)
3.集合添加元素用add;list列表添加元素用append;
4.字符变大写:x.upper();字符变小写:x.lower()
5.字符串和列表都可以用count()函数,用来计算出现频率
6.Counter:A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.也就是说使用counter可以直接将对象里的元素和出现的频率作为键值对储存起来。
7.iteritems()主要用于dict
Return an iterator over the dictionary’s (key, value) pairs. See the note for dict.items().
8.for i in range(len(something));
9.li=list();根据下表索引:li[i]
10.list初始化为空:re=[]
11.None
The sole value of types.NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function.
def unique_in_order(iterable):
result = []
prev = None
for char in iterable[0:]:
if char != prev:
result.append(char)
prev = char
return result
11.itertools.groupby(iterable[, key])
Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.
[k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
12.python中允许用负数来索引;那么-1即是最后一个元素:
def unique_in_order(iterable):
k = []
for i in iterable:
if k == []:
k.append(i)
elif k[-1] != i:
k.append(i)
return k
3.所有的完全平方数,相邻之差是一个等差数列,公差为2
def find_next_square(sq):
# Return the next square if sq is a square, -1 otherwise
i = 1
temp = sq
while temp > 0: # a perfect square must be a sum of a arithmetic sequence by 2
temp -= i
i +=2
if temp == 0:
return sq + i
else:
return -1