【问题标题】:Finding all numbers that evenly divide a number查找所有能整除一个数的数
【发布时间】:2017-06-24 03:41:17
【问题描述】:

所以我正在尝试编写一个程序,当我输入一个数字时,它会给我所有的因素(12->1,2,3,4,6,12)。我最近才开始编程,所以可能会有一些非常明显的事情。但这是我的代码

numbers = [1]
newnum = 1
chosen = int(input("Enter what you want the factors of: "))
def factors(numbers,newnum,chosen): 
    lastnum = numbers[-1]
    if (chosen == lastnum):
        for number in numbers:
            if (number % 1 != 0):
                numbers.remove(number)
                print (numbers)
            else:
                factors(numbers,newnum,chosen)
    else:
        newnum = numbers[-1] + 1
        numbers.append(newnum)
        print (numbers)
        factors(numbers,newnum,chosen)

factors(numbers,newnum,chosen)  

好的,所以我真的不需要解决冗余问题,但如果您发现某些内容会完全阻止程序运行,请指出。对不起,我为此打扰了大家,但我不知道还能做什么。

【问题讨论】:

  • edit您的问题标题实际上包含有关您遇到的问题或您要询问的问题的信息。标题应该足够清晰和具有描述性,以便对在一组搜索结果中看到它的未来读者有用。您当前的标题不包含任何有用或描述性内容。 我不知道怎么回事是浪费空间;显然,如果你确实知道出了什么问题,你就不需要在这里发帖了。

标签: python python-3.x math helpers


【解决方案1】:
    # Two Pointer Approach

     ans = []
     
     
     def divisor(val):
         result = []
     
         for i in range(1, val + 1):
             ans.append(i)
     
         i = 0
         j = len(ans) - 1
     
         while i < j:
     
             if ans[i] * ans[j] == ans[-1]:
                 result.append(ans[i])
                 result.append(ans[j])
                 i += 1
             else:
                 j -= 1
     
         return sorted(result)
     
     
     print(divisor(12))


# Output

>>> [1, 2, 3, 4, 6, 12]

【讨论】:

  • 欢迎来到 StackOverflow。虽然这段代码可以解决问题,including an explanation 解决问题的方式和原因确实有助于提高帖子的质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提出问题的人。请编辑您的答案以添加解释并说明适用的限制和假设。
【解决方案2】:

有很多问题:

  • 每个整数模 1 为零,因为每个整数都可以被 1 整除而没有余数。

  • 您从正在迭代的列表中删除项目,如果您不小心操作,肯定会给出错误的结果!

  • 您尝试执行递归,但未返回递归调用的结果。这是可能的,因为您在一个可变列表上进行操作,但它通常不是很好的样式

  • 您没有任何内联 cmets 来解释该行应该做什么,因此很难就如何改进代码给出任何合理的指导。

如果您想要找到所有因素的代码,请考虑以下内容:

chosen = int(input("Enter what you want the factors of: "))

def factors(chosen, currentnum=None, numbers=None): 
    # Recursion start, always append 1 and start with 2
    if numbers is None:
        numbers = [1]
        currentnum = 2
    # We're at the last value, it's always divisible by itself so
    # append it and return
    if currentnum == chosen:
        numbers.append(currentnum)
        return numbers
    else:
        # Check if the chosen item is divisible by the current number
        if chosen % currentnum == 0:
            numbers.append(currentnum)
        # Always continue with the next number:
        currentnum += 1
        return factors(chosen, currentnum, numbers)


>>> factors(chosen)
Enter what you want the factors of: 12
[1, 2, 3, 4, 6, 12]

这不是最佳解决方案,但它使用递归并给出了正确的结果。只是不要在开头输入负值或在函数中捕获这种情况!

【讨论】:

  • 哇,谢谢伙计。抱歉给您添麻烦了,我认为您不必从第一步开始重新制作整个程序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多