1 年半 android 经验, 初次接触 python, 学了几天, 相见恨晚, 迫不及待的写了这篇记录下. python 新手, 请多见谅.
其实也不是最近才接触 Python, 大四上有一门计算机性能相关的课各种算法, 工具要求用 python 写, 不过当时太懒了, 全用 java 写的. 导致毕业一年多了, 现在每天忙碌的工作之余, 晚上这个点左右挤时间出来学, 算是 "自我救赎" 吧, 哈哈.
其实第一感觉 python 只是简单, 没有那么吸引人, 照着书写了个自动压缩文件脚本, 觉得挺有意思的. 但是还没足够吸引我.
但是当我看到数据结构的时候, 被 python 简单操作复杂数据结构的强大功能吸引了.
举个例子吧:
打印出 list 除开最后两个的元素.
如果是 java, 要么是 for 循环遍历, 然后用指针控制打印逻辑; 要么 copy 一个副本, remove 掉最后两个; 而且 java 的输入输出 scaner,system.out 也挺麻烦的;
换做 python 直接 list(:-1)
我曹... 简直 6666, 当时我就被震惊了. list 可以倒着数, 而且取一个 subString 超级方便.
还是不够直观? 来一个具体的实用例子吧
刷过 onlineJudge 的, 应该都用过 leetCode https://leetcode.com/ 吧
选最熟悉的第一题, 找出数组里面两数, 和为特定值.
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
- Example:
- Given nums = [2, 7, 11, 15], target = 9,
- Because nums[0] + nums[1] = 2 + 7 = 9,
- return [0, 1].
都采用 Map 键值对记录 index 和 value 的思路
java 解法
- class Solution {
- public int[] twoSum(int[] nums, int target) {
- HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
- int result[] = new int[2];
- for (int i = 0; i < nums.length; i++){
- int num = target - nums[i];
- if(map.containsKey(num)){
- result[0] = map.get(num);
- result[1] = i;
- return result;
- }
- map.put(nums[i], i);
- }
- return result;
- }
- }
python 解法
- class Solution:
- def twoSum(self, nums, target):
- dict = {}
- for i in range(len(nums)):
- x = nums[i]
- if target-x in dict:
- return (dict[target-x], i)
- dict[x] = i
怎么样, 这下子够直观了吧;
后记:
对 python 的学习才刚刚开始, 学习的直接目标是 android 的自动打包脚本. 然后是看看自己适不适合搞 ai tensorfolw 啥的, 不适合就算了, 也对 android 有帮助. 多一门技能, 也多一些选择 .
来源: http://www.jianshu.com/p/346e006bc98e