标签归档:python

RSS feed of python

Python Requests实现短网址还原

利用python-requests(http://www.python-requests.org/),只需数行代码即可实现短网址还原。

通过HTTP HEAD请求,从返回响应的头信息(headers)中取出Location字段即为短网址对应的原始网址。

Python代码:

import requests
def revertShortLink(url):
    res = requests.head(url)
    return res.headers.get('location')

代码测试:

print revertShortLink('http://t.cn/RVMAn7W')

返回结果:

https://bookshadow.com/weblog/2016/10/15/leetcode-maximum-xor-of-two-numbers-in-an-array/#0-tsina-1-85154-397232819ff9a47a7b7e80a40613cfe1

Python计算约数个数

方法I 从1到n枚举,判断是否可以整除

时间复杂度 O(n)

Python代码:

def countDivisors(num):
    return sum(num % i == 0 for i in range(1, num + 1))

方法II 从1到sqrt(n)枚举,判断是否可以整除

时间复杂度 O( sqrt(n) )

Python代码:

def countDivisors(num):
    cnt = 0
    sqrt = int(num ** 0.5)
    for x in ...

继续阅读

递归计算Ramanujan无穷根式

拉马努金无穷根式是印度数学家拉马努金(Srinivasa Ramanujan)于20世纪初提出的。

f(x) = sqrt(1 + (x + 1) * f(x + 1))

上面的函数是一个递归式,下面用Python编程计算该函数的值。

Python代码:

import math
class Ramanujan(object):
    def sum(self, d, md):
        if d > md:
            return 0
        return math.sqrt(1 + (d + 1) * self.sum(d + 1, ...

继续阅读

Python实现图像与字符串互转

在存储或者传输图像时,我们经常需要将图像转换成字符串。

与其他编程语言一样(比如Java),Python也可以实现将图像用字符串进行表示。

使用Python进行转换非常的简单,关键部分就是使用“base64”模块,它提供了标准的数据编码解码方法。

图像转换成字符串

Python代码:

import base64
 
with open("t.png", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    print str

输出:

iVBORw0KGgoAAAANSUhEUgAAAuAAAACFCAIAAACVGtqeAAAAA3
NCSVQICAjb4U/gAAAAGXRFWHRTb2Z0d2FyZQBnbm9tZS1zY3Jl
ZW5zaG907wO/PgAAIABJREFUeJzsnXc81d8fx9+fe695rYwIaa
...

字符串转换成图像

Python代码:

fh = open("imageToSave.png", "wb")
fh.write(str.decode('base64'))
fh.close()

原文标题:Python: Convert Image to String, Convert String to Image

原文地址:http://www.programcreek.com/2013/09/convert-image-to-string-in-python/

安装numpy提示Unable to find vcvarsall.bat懒人解决方案

在Windows命令提示符下使用pip安装numpy时,提示错误:error: Unable to find vcvarsall.bat

操作系统:Windows 7 x32

Python版本:Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32

懒人解决方案:

前置条件:安装pip(https://pypi.python.org/pypi/pip)

从链接http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy下载numpy的whl文件到本地

例如将numpy-1.9.2+mkl-cp27-none-win32.whl下载到路径F:\python\

然后在cmd中cd F:\python\

执行命令pip install "numpy-1.9.2+mkl-cp27-none-win32.whl"即可。