python - 数字因式分解
问题描述
任务是编写将数字折叠成素数的函数。通过给定数字“n”,此函数应返回元组列表p_i,c^i,例如,如果输入为 100,则输出为 (2,2),(5,2)。所以,这是我尝试编写它的方式:
def factor(n):
c = 1
pre_ans = list()
temp_n=n
for i in range(2,temp_n+1):
if (is_prime(i) == True) and (temp_n % i == 0):
for j in range (2,temp_n+1):
if (temp_n % (i ** j) == 0):
pre_ans.append((i,j))
temp_n /= (i **j)
pre_ans.append((i,c))
temp_n /= i
print(pre_ans)
它工作错了,但我找不到错误:(
解决方案
你的总体思路没问题。但是,您的代码的以下部分存在一些小问题:
for j in range (2,temp_n+1):
if (temp_n % (i ** j) == 0):
pre_ans.append((i,j))
temp_n /= (i **j)
pre_ans.append((i,c))
temp_n /= i
事实上,主要问题是您需要在此语句的另一个方向上进行迭代for j in range (2,temp_n+1)
。如果你像这样重写它
def factor(n):
c = 1
pre_ans = list()
temp_n=n
for i in range(2,temp_n+1):
if (is_prime(i) == True) and (temp_n % i == 0):
for j in range (temp_n+1, 0,-1):
if (temp_n % (i ** j) == 0):
pre_ans.append((i,j))
temp_n /= (i **j)
print(pre_ans)
它会起作用的。整个代码也可以写得更短一些:
from collections import Counter
def factor(n):
lst = []
for i in range(2, n+1):
while n % i == 0:
lst.append(i)
n = n / i
return Counter(lst).items()
print(factor(100))
推荐阅读
- javascript - Ruby on rails Bootstrap Modal 不工作
- javascript - 如何在不使用 blob 和数据方案 url 的情况下在新选项卡中显示来自服务器的文件
- c# - 哪个更适合子查询,使用实体分配的 var 或直接访问实体?
- javascript - 如何调整图像的方向以显示正确的图像预览?
- python - 理解机器学习、NLP:使用 scikit-learn、python 和 NLTK 进行文本分类
- apache-kafka - Kafka 设计问题 - Kafka Connect 与自己的消费者/生产者
- android - 如何等到用户权限,才能在 Geolocator 中获取位置坐标以加载 Google 地图?
- javascript - 如何从快速后端服务器获取和显示图像到 React Native 前端?
- java - Creating a JAR archive without Java/OpenJDK
- java - 如何从 Java 中不断更新的 Gzip 文件中读取?