摘要:最近在看算法相关的知识, 顺便复习下python, 就用python来写算法吧, 开始!题目1: 用两个栈实现一个队列, 分别在队列尾部插入节点和在队列头部删除节点解答:#!/usr/bin/python# use two stacks to implement a queueclass MyQueue(object): """docstring for MyQueue""" def __init__(self, arg): super(MyQueue, self).__init__() self.arg = arg self.sta
阅读全文
摘要:python版本的快速排序, 经典算法, 话不多说, 代码搞起:#!/usr/bin/pythonimport randomclass QuickSort(): def Partition(self, A, p, r): x = A[r] i = p - 1 for j in range(p, r): if A[j] <= x: i = i + 1 A[i], A[j] = A[j], A[i] A[i+1], A[r] = A[r], A[i+1] ...
阅读全文
摘要:题目: 实现递归和非递归实现Fibonacci数列解答:#!/usr/bin/pythondef Fibonacci(n): a = [0, 1] if n < 2: return a[n] fibNMinusOne = 1 fibNMinusTwo = 0 for n in range(2,n+1): fibN = fibNMinusTwo + fibNMinusOne fibNMinusTwo = fibNMinusOne fibNMinusOne = fibN return fibN def Fib...
阅读全文
摘要:题目:输入一个整数,求该整数的二进制表达中有多少个1。例如输入10,由于其二进制表示为1010,有两个1,因此输出2解法:#!/usr/bin/pythondef NumberOf1(n): count = 0 while n: if n & 1: count += 1 n = n >> 1 return countdef NunberOf1A(n): count = 0 while n: count += 1 n = (n-1) & n return count# differe...
阅读全文
摘要:题目:给定一组数,给出这组数所有的排列算法:#!/usr/bin/python#coding=gbk'''Created on 2013-03-24@author: songjian'''def quanpailie(test_arr, sub_arr): if len(test_arr) == 1: sub_arr.append(test_arr[0]) print sub_arr sub_arr.pop() else: length = len(test_arr) for i in range(0, leng...
阅读全文
摘要:题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个排好序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3, 4, 5, 1, 2}为{1, 2, 3, 4, 5}的一个旋转,该数组的最小值为1。解答:#!/usr/bin/python#coding=gbk'''Created on 2013-03-25@author: songjian'''def get_min(test_arr): low_index = 0 high_index = len(test_arr) - 1 mid_index = low_in
阅读全文
摘要:题目:解法:维护两个索引,如果第一个指向那个的数字是偶数,第二个指向的数字是奇数,就交换这两个数字#!/usr/bin/python#coding=gbk'''Created on 2013-03-25@author: songjian'''def adjust_seq(test_arr): begin_index = 0 end_index = len(test_arr) - 1 while begin_index < end_index: if test_arr[begin_index] % 2 == 0: while end_inde
阅读全文