一)爲什麼這個循環無法正常工作?
作爲@聖何塞-裏卡多-Bustos的-m表示,所述x
不是引用,是一個本地副本到陣列a
的每個元素,並且不能修改陣列中的for循環。您可以使用,而不是:
a=[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
for i,x in enumerate(a): #used to provide a value, and an index
if(x%2==0):
a[i]=x/2
B)誰能告訴我,我該怎麼辦呢?
你可以嘗試使用三元如果運營商和列表理解:
a = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
b = [x/2 if x%2==0 else x for x in a]
C)時,我的算法正常工作
你要跟蹤的數字您已經使用,而且您可能需要多次劃分相同的數字。但是,如果你這樣做,並繼續分割相同的數字_直到結果列表等於前一個,然後移動到下一個,你可以稍後乘以所有使用的數字,乘以列表的其餘部分(但如果你去到列表中的最大數量,剩下的列表將只包含1)。
def f(l,n): # divides items in a which are divisible by n, or leaves them
return [x/n if x%n==0 else x for x in l]
lcm = 1
a=[2,3,4,5,6,7]
# we go from the smallest to the largest number in your list
for i in range(2,max(a)+1):
repeat_next_time = True
while repeat_next_time:
b = f(a,i)
if a != b:
print('Using %s as a factor' % i)
a = b
lcm *= i
# print(a) # to get the status of the a list
else:
repeat_next_time = False
# finally, for numbers which might have not been divided yet,
# multiply the lcm by all of the remaining items
lcm *= reduce(lambda x,y: x*y, a)
即使在列表中有共同的因子或重複的數字,它也能正常工作。例如,嘗試使用a = [2,2,2]
或a = [2,3,6]
或a = [8,7,4,7]
。
你預期的產量是多少? – Kasramvd
@ kasra-他只是整個項目的一部分。我打算通過素數分解得到20個數字中的1cm。 – kpks
本質上你不需要素因子分解,但是你必須注意計算因子的次數,只需要考慮它們的次數(參見下面的答案)。 – juandesant