簡體   English   中英

為什么這似乎是一個無限循環?

[英]why does this seem to be an infinite loop?

#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)

您在每個循環中將counter設置為0 ,因此, if counter == len(a) while counter <= len(a)將在每個循環中求值相同,則使其無限。

#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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM