为什么这似乎是一个无限循环?

时间:2015-03-23 01:22:31

标签: python

#This (python code) program will find the hcf of a given list of numbers.
A = [10, 15, 25, 35, 90]     #creates and initializes the list of numbers

def greatest_common_devisor(a):
  factor_list = []         #creates a blank list that will be used to store all common factors
  factor = 1               #creates and initializes the number that will be used to check if it
                          #is a factor of the numbers in the list
  counter = 0          #initializes a counter variable to control the while loop

  while counter <= len(a):    #Begining of while loop with number of iterations = length of array
    if a[counter] % factor == 0:  #checking to see if the variable factor is a factor of the number inside list a
      counter += 1           #incrementing counter to move to the next element/number within list a
      if counter == len(a):   #if the variable factor is a factor, and we have reached the end of the array,
                              #that means the variable factor is a factor of all the numbers in list a
        factor_list.append(factor) #if variable factor is a factor of all the numbers in list a
                                    # we then add it to the new array will be used to stor all common factors
    counter = 0 #Setting back counter to 0 so we can go back to the begining of the array
                 #to restart the process of checking the next value of variable factor
    factor += 1  #incrementing to check the next consecutive number

  print factor_list  #when i get this to work i will loop through factor_list and print the biggest number, i.e. the hcf

greatest_common_devisor(A)

2 个答案:

答案 0 :(得分:2)

您在每个循环中将counter设置为0,因此if counter == len(a)while counter <= len(a)将在每个循环中评估相同的内容,从而使其无限。

答案 1 :(得分:0)

#This program will find the hcf of a given list of numbers.

A = [65, 20, 100, 85, 125]     #creates and initializes the list of numbers

def greatest_common_devisor(_A):
  iterator = 1
  factor = 1
  a_length = len(_A)
  largest = 99999

#get the largest number
for number in _A: #iterate through array
  if number < largest: #if current not the highest number
    largest = number #set to highest

while iterator <= largest: #iterate from 1 ... largest number
for index in range(0, a_length): #loop through array
  if _A[index] % iterator != 0: #if the element is not equally divisible by 0
    break #stop and go to next element
  if index == (a_length - 1): #if we reach the last element of array
    factor = iterator #it means that all of them are divisibe by 0
iterator += 1 #let's increment to check if array divisible by next iterator
#print the factor
print factor

print "The highest common factor of: ",
for element in A:
  print element,
print " is: ",
greatest_common_devisor(A)