hackerrank中python题目的套路

使用getattr

很多题目都是需要执行类似于这样的操作:

insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print

忽略print,里面的第一个参数与list对象的中的方法一致,但是后面的参数数量有差异:0-2个,所以对于题目:https://www.hackerrank.com/challenges/python-lists/problem

可以使用这样的逻辑:

if __name__ == '__main__':
    N = int(input())
    res = list()
    for _ in range(N):
        inp = input().split()
        if inp[0] == 'print':
            print(res)
            continue
        getattr(res, inp[0])(*map(int, inp[1:]) if len(inp) > 1 else [])
    # print(*[item for item in d])

输出一个列表中的全部元素, 比如说:

In [149]: polar(s)
Out[149]: (5.0990195135927845, -1.7681918866447774)
print(*polar(s))

想要用两个不同的类

如果同时想要用 Counter 和 OrderedDict,可以写一个空的类,然后直接同时实例化:

from collections import Counter, OrderedDict

    class OrderedCounter(Counter, OrderedDict):
        pass
    [print(*c) for c in OrderedCounter(sorted(input())).most_common(3)]
```'

# itertools.product的问题

这个问题:https://www.hackerrank.com/challenges/maximize-it/problem

本来绝大多数人第一反应都是用product解决,看到一位老爷子,非常优雅的用lambda表达式解决了。

```python
from itertools import product
K, M = map(int,input().split())
data = [map(int,input().split()[1:]) for _ in range(K)]

F = lambda x: x**2               
S = lambda x: sum(map(F, x)) % M

print(max(map(S, product(*data))))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这是16年5月份编辑的一份比较杂乱适合自己观看的学习记录文档,今天18年5月份再次想写文章,发现简书还为我保存起的...
    Jenaral阅读 2,860评论 2 9
  • 写在前面的话 代码中的# > 表示的是输出结果 输入 使用input()函数 用法 注意input函数输出的均是字...
    FlyingLittlePG阅读 2,943评论 0 8
  • 男人世界 夏季风情 你光膀我赤膊 闪转腾挪打乒乓 弹丸一枚 魅力无穷 你我心相印 谁人不跃动 哼哈声 跺地声 不比...
    瀛洲居士阅读 1,071评论 0 1
  • 吸日月之精华,吸天地之精神,开得绚烂夺目,美得无与伦比。一瓣是风,一瓣是雨,一瓣是你,一瓣是我。总在回眸,...
    冰夫阅读 303评论 0 0
  • 投机像山丘一样古老,人只要尝到一点点投机的滋味,就再也不愿意去劳动。 然而真正的价值,是由劳动创造的。 ...
    snow海思阅读 412评论 0 0