timtiian / think_python Goto Github PK
View Code? Open in Web Editor NEWpractice of Think_python
practice of Think_python
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
方法一:
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# check that linked lists l1 and l2 are not empty
if not l1:
return l2
if not l2:
return l1
x1 = x2 = ''
# extracting number x1 from linked list l1
curr_node = l1
while curr_node:
x1 += str(curr_node.val)
curr_node = curr_node.next
# extracting number x2 from linked list l2
curr_node = l2
while curr_node:
x2 += str(curr_node.val)
curr_node = curr_node.next
# Add Two Numbers: y = x1 + x2
y = int(x1[::-1]) + int(x2[::-1])
y = str(y)[::-1]
# make result
head = new_node = ListNode(y[0])
for i in range(1, len(y)):
new_node.next = ListNode(y[i])
new_node = new_node.next
return head
方法二:
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l1_str = ""
l2_str = ""
while l1 :
l1_str += str(l1.val)
l1 = l1.next
while l2:
l2_str += str(l2.val)
l2 = l2.next
return [int(x) for x in str(int(l1_str[::-1]) + int(l2_str[::-1]))][::-1]
背景:
Automate the boring stuff with python(Written by Al Sweigart.)一书的Chapter 3 – Functions关于函数的论述中,末尾有一个计算Collatz序列的实践项目,具体要求为:
输入一个整数n,提供一个函数collatz(n)对n进行计算,规则为:
若n是一个偶数则计算n//2(n整除2)的结果
若是奇数则计算3*n+1作为结果
每次计算的结果再拿来视为n重新做collatz(n)计算,直到计算结果为1为止。把每次计算的结果显示出来,这就是所谓的Collatz序列。
while True:
try:
print('Enter an integer number:')
n = int(input())
break
except:
print('You gave a noninteger string.')
def collatz(number):
r = number % 2
if r == 0:
return number // 2
else:
return 3 * number + 1
while n !=1:
print(collatz(n))
n = collatz(n)
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
import numpy as np
class Solution:
def longestPalindrome(self, s):
l = len(s)
p = np.zeros([l,l])
max_l = 0
max_i = 0
max_j = 0
for j in range(l):
for i in range(j,-1,-1):
if( j-i <= 2 and s[i] == s[j]):
p[i,j] = 1
if j-i > max_l:
max_l = j - i
max_i = i
max_j = j
if(j-i>2 and s[i] == s[j] and p[i+1][j-1] == 1):
p[i,j] = 1
if j-i > max_l:
max_l = j - i
max_i = i
max_j = j
return(s[max_i:max_j+1])
题目描述
LeetCode 8 String to Integer (atoi)
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Requirements for atoi
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
题目大意
实现atoi函数将字符串转换为整数。
提示:仔细考虑所有输入用例。如果想给自己挑战,请不要看下面的内容并询问自己所有可能的输入用例。
注意:这道题有意描述地比较含糊(亦即,没有给出输入用例)。你需要自己发掘所有的输入要求。
atoi的要求:
函数首先尽可能多的丢弃空白字符,直到发现第一个非空字符位为止。 接着从这个字符开始,读入一个可选的正负号,然后尽可能多的读入数字,最后将它们解析成数值。
字符串中在合法数字后可以包含额外的非法字符,对于这些字符只需丢弃即可。
如果字符串的非空字符不是一个有效的整数,或者,当字符串为空或者只包含空白字符时,不需要执行转换。
如果不能够执行有效的转换则返回0。如果得到的数值超出了整数范围,返回INT_MAX (2147483647) 或者 INT_MIN (-2147483648)。
要点分析
Input Edge Case
How to catch exceptions and corner case?往往一个函数或者程序的输入是有很多Edge Case的,为了程序的robustness,我们需要处理这些异常的Case。
Tips
1 用max和min减少if else
max(min_value, min(res, max_value))
2 str.strip([chars])
[可指定移除字符串头尾的任意字符](默认为空格)
chars -- 移除字符串头尾指定的字符
3 isdigit()
方法检测字符串是否只由数字组成(单个字符和字符串都可以)
4 ord()
ord() 函数是 chr() 函数(对于ord() 函 8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数
它以一个字符(长度为1的字符串)作为参数,
返回对应的 ASCII 数值,或者 Unicode 数值,
如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。
ord(char) - ord('0')
Python 学习体系
第一部分: 一些要求
1.学历
格式: 计算机及相关专业本科及以上学历.....
不解释,不说明
毕业后很少再看学历了,更多的是看能力吧(我会告诉你第一年周围都是硕士博士海龟么,俺学历最低,自卑啊)
见过数学系、物理系、信息自动化系的跑过来当码农,唯一遗憾的是还没有见到中文系的.....
2.经验
格式:拥有X年以上经验,至少独立负责过X个项目
很蛋疼的东西,见过一年经验用N年的,也见过一年拥有N年经验的
受环境影响,但更多的是取决于个人
听过一句话:人和人的唯一区别,就是有木有主观能动性(略有些偏激,但是有道理)
3.基础素质
格式:具有良好的XXXX
编码规范/风格
文档书写习惯
沟通与表达能力,逻辑思维清晰
团队合作
动手能力/独立工作能力
进取心,求知欲,工作热情
善于学习,乐于分享,快速学习能力
能承受较大的工作压力
执行力
责任感
英文阅读能力
创新精神
对新技术敏感
独立分析、设计、解决问题的能力
这些都相对比较“虚”,不怎么好考察,面试+试用可以相对客观了解是否符合
个人认为,责任感+执行力,这两点足够了,其他一般不会差。
自我驱动的人,永远会get things done.所以会不断去弥补自己的短板,其他对应能力即使不足,也能很快弥补
4.加分项
格式:XXXX优先
使用*nix系统
vim/Emacs编辑器
对开源技术有强烈兴趣和爱好,参与提交bug/patch
各种技术/经验(前端/hadoop/机器学习/数据挖掘/函数式编程)
为毛不是osx系统(╯‵□′)╯︵┻━┻
从一些侧面,查看一个人的特质吧
5.提供
格式: XXXX账号/地址
博客地址
github/bitbucket
stackoverflow
知乎
微博
搞技术的,很有必要建立自己的领地,搞一些东西
分享,更重要的是积累
第二部分:干货
关于Python后端开发要求
1.对Python有兴趣,熟悉Python(标准库)
最好阅读过源码
了解Python的优化(熟悉pypy更佳)
2.至少至少一门语言(不说“精通”)
起码熟悉其他基本语言
C/C++ Lisp Haskell Scheme golang erlang Java R Ruby Node.js PHP Perl Lua
我选了Java(曾经擅长)/Golang/Lisp/Ruby/C/C++
3.数据结构和算法
数据结构和算法基础扎实
4.Python框架
Django/Tornado/Flask/Gevent/Web.py/Bottle/Celery/Twisted/NumPy
5.熟悉Linux
基本操作和命令
会Shell
版本Git/Svn
部署相关: Nginx/Gunicorn/Fabric/Virtualenv
6.数据库
熟悉Mysql等关系数据库使用
熟悉数据库设计
熟悉数据库调优/优化
有NoSQL使用经验 Redis/MongoDB等
7.后端技术相关
Redis
Memcached
RabbitMQ/ZeroMQ
8.网络编程基础
熟悉tcp/ip协议,熟悉网络编程
了解常见的网络模型
多线程
9.前端相关
熟悉Web开发相关知识
熟悉HTML/CSS/Javascript/JQuery
熟悉AngularJS
10.其他
数据抓取,爬虫
beautifulsoup/scrapy
机器学习/数据挖掘/自然语言处理(推荐算法)
TDD
高并发系统
大容量存储系统
消息系统
Linux系统编程/网络编程
基于此,去构建自己的技能体系,然后针对各项逐渐深入
就这些,*年,努力练级去吧
wklken
2013-12-21
版权声明:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0
"""This module contains a code example related to
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
Copyright 2015 Allen Downey
License: http://creativecommons.org/licenses/by/4.0/
"""
from future import print_function, division
import math
def factorial(n):
"""Computes factorial of n recursively."""
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result
def estimate_pi():
"""Computes an estimate of pi.
Algorithm due to Srinivasa Ramanujan, from
http://en.wikipedia.org/wiki/Pi
"""
total = 0
k = 0
factor = 2 * math.sqrt(2) / 9801
while True:
num = factorial(4*k) * (1103 + 26390*k)
den = factorial(k)**4 * 396**(4*k)
term = factor * num / den
total += term
if abs(term) < 1e-15:
break
k += 1
return 1 / total
print(estimate_pi())
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.