• python常用算法题


    一:
    #计算平均数,中位数和众数
    #coding:utf-8
    #计算平均数,中位数和众数
    import random

    lst = [random.randint(0,10) for i in range(11)]

    s = sum(lst)

    length = len(lst)

    average = s*1.0 / length

    print "The average is:",average

    lst.sort()
    print "From small to bigger,",lst

    middle = lst[length/2]
    print "middle",middle

    #众数 method1
    m = {}
    for i in lst:
    if i in m:
    m[i] +=1
    else:
    m[i] = 1
    print m

    max_number = max(m.values())
    print max_number

    for k,v in m.items():
    if v == max_number:
    print "mode is:",k

    #众数method2
    t = set(lst)
    d = {}
    for i in t:
    d[i] = lst.count(i)
    print d
    for k,v in m.items():
    if v == max_number:
    print "mode is:",k

    二:
    一列表由若干个整数组成,现要将偶数放到前面,奇数放在后面
    #coding:utf-8
    #一列表由若干个整数组成,现要将偶数放到前面,奇数放在后面
    import random
    lst = [random.randint(0,100) for i in range(90)]

    print lst

    odd = []
    even = []
    for i in lst:
    if i%2 ==0:
    even.append(i)
    else:
    odd.append(i)

    print even
    print odd

    even.extend(odd)
    print "result:",even

    三:
    列表中的字符串按照指定字符顺序排序
    #coding:utf-8

    #对列表中的字符串按照指定字符顺序排序

    by_string = ["a","e","i","o","u"]
    words = ["suzhou","shanghai","hangzhou","nanjing","beijing"]

    result = {}
    for word in words:
    n = []
    for i in word:
    if i in by_string:
    n.append(by_string.index(i))
    else:
    n.append(9)

    result[word] = n
    print result
    vs = result.values()
    vs.sort()
    print vs

    sorted_word = []
    for i in vs:
    for k,v in result.items():
    if v == i:
    sorted_word.append(k)

    print sorted_word



  • 相关阅读:
    C#修饰符
    Exploring jQuery .live() and .die()
    ASP.NET Session丢失问题原因及解决方案
    5个 PHP 安全措施(转)
    jQuery方法click() bind() live() delegate()区别
    高性能网站的十四条黄金法则(雅虎14条)
    计算机科学概论读书笔记系列——绪论
    进程、线程、应用程序域、托管代码、元数据等。
    互联网协议入门(转)
    js跨域访问问题
  • 原文地址:https://www.cnblogs.com/klsw/p/7528924.html
Copyright © 2020-2023  润新知