python——例题学习

1. 生成一个大文件ips.txt,要求1200行,每行随机为172.25.254.0/24段的ip;
2. 读取ips.txt文件统计这个文件中ip出现频率排前10的ip;

import random


def file(filename):
    ips = ['172.25.254.' + str(i) for i in range(1, 255)]
    print(ips)
    with open(filename, 'a+') as f:
        for j in range(1200):
            print(random.sample(ips, 1))
            f.write(random.sample(ips, 1)[0] + '\n')


def sort_file(filename,count=10):
    dict_ip = dict()
    with open(filename) as f:
        for ip in f:
            if ip in dict_ip:
                dict_ip[ip] += 1
            else:
                dict_ip[ip] = 1
    sorted_ip = sorted(dict_ip.items(), key=lambda x: x[1],reverse=True)[:count]
    return sorted_ip
print(sort_file('jjj.txt'))

在这里插入图片描述

给定一个仅包含数字 2-9 的字符串, 返回所有它能表示的字母组合。 给出数字到字母的映射如下 (与电话按键相同)。注意 1
不对应任何字母 输入:”23” 输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”,
“cf”]. 说明:尽管上面的答案是按字典序排列的, 但是你可以任意选择答案输出的顺序

def phpneLetter(digits):
    if not digits:
        return []
    keyboard = {
       "2":'abc',
        '3':'def',
        '4':'ghi',
        '5':'jkl',
        '6':'mno',
        '7':'pqrs',
        '8':'tuv',
        '9':'wxyz'
    }
    res = []
    if len(digits) == 0:
        return []
    if len(digits) == 1:
        return keyboard[digits]
    restult = phpneLetter(digits[1:]) ##取出‘4’
    for i in restult:
        for j in keyboard[digits[0]]: ##取出字典中的3
            res.append((j+i))

    return res

print(phpneLetter('34'))
发布了64 篇原创文章 · 获赞 0 · 访问量 443

猜你喜欢

转载自blog.csdn.net/qq_42024433/article/details/103939733
今日推荐