编程题
求1~100各数的因数:
程序编写要求:要求使字典保存各数的因数,键为各数,值为各数的因数。输出如下图所示:
{1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 2, 4], 5: [1, 5], 6: [1, 2, 3, 6], ...}
编程思路
主要考察函数的定义,列表及字典的创建及添加等知识点。编程思路如下:
1、将求因数过程定义为函数,输入数值,返回该数值的因数列表;
2、通过循环创建字典,数值为字典的键,函数返回的因数列表作为字典的值。
编程实现#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author : 青松
# @Time : 2020/4/9 8:31
# @Site : www.itclub16.com
def fun_factor(n):
'''
求因数函数
:param n: 输入参数n
:return: 返回n对应的因数列表
'''
list_factor=[]
for i in range(1,n+1):
if(n%i==0):
list_factor.append(i) #将因数添加列表元素
return list_factor
dict_factor={}
for num in range(1,101):
#字典元素的添加,Key为num,Value为对应的因数列表
dict_factor[num]=fun_factor(num) #调用因数函数
print(dict_factor)
运行结果