栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python分解

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python分解

好吧,不仅您有3个循环,而且如果您有3个以上的因素,这种方法将无效:)

一种可能的方式:

def genfactors(fdict):        factors = set([1])    for factor, count in fdict.iteritems():        for ignore in range(count): factors.update([n*factor for n in factors]) # that line could also be: # factors.update(map(lambda e: e*factor, factors))    return factorsfactors = {2:3, 3:2, 5:1}for factor in genfactors(factors):    print factor

此外,您还可以避免在内部循环中重复某些工作:如果您的工作集为(1,3),并且想应用到2 ^ 3个因子,那么我们正在做:

  • (1,3) U (1,3)*2 = (1,2,3,6)
  • (1,2,3,6) U (1,2,3,6)*2 = (1,2,3,4,6,12)
  • (1,2,3,4,6,12) U (1,2,3,4,6,12)*2 = (1,2,3,4,6,8,12,24)

看看第二组中有多少个重复项?

但是我们可以改为:

  • (1,3) + (1,3)*2 = (1,2,3,6)
  • (1,2,3,6) + ((1,3)*2)*2 = (1,2,3,4,6,12)
  • (1,2,3,4,6,12) + (((1,3)*2)*2)*2 = (1,2,3,4,6,8,12,24)

没有设置,解决方案看起来更好:

def genfactors(fdict):    factors = [1]    for factor, count in fdict.iteritems():        newfactors = factors        for ignore in range(count): newfactors = map(lambda e: e*factor, newfactors) factors += newfactors    return factors


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/669340.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号