[英]I want to swap a number divisible by 2 with the next number divisible by 5 in a list
資料來源: [2, 4, 2, 4, 5, 10]
預期: [5, 10, 2, 4, 2, 4]
獲得: [5, 10, 2, 4, 2, 4]
我的代碼為我提供了這種組合的准確結果。
資料來源: [2, 2, 5, 5, 4, 5, 5, 6, 5]
預期: [5, 5, 2, 2, 5, 4, 5, 6]
獲得: [5, 5, 5, 5, 5, 2, 2, 6, 4]
我的代碼沒有在這里提供所需的結果。
資料來源: [2, 4, 5, 7, 10, 13, 17, 19, 15]
預期: [5, 10, 2, 7, 4, 13, 17, 19, 15]
獲得: [5, 10, 15, 7, 4, 13, 17, 19, 2]
如果號碼切換一次,應該不受干擾(我對python的了解非常初級......我前幾天開始) 。
a = []
b = a.copy()
for div_by_2 in a:
#print('entering for loop to check divisibility by 2 for the number ' , div_by_2 , ' in the list')
if div_by_2 % 2 == 0:
#print('entering if in for loop of checking divisibility by 2 as ' , div_by_2 , 'is divisible by 2')
#print(a.index(div_by_2) , ' is the index of the number divisible by 2')
#print(('begining of value of check five for loop is ' ,a.index(div_by_2)))
for check_five in range (a.index(div_by_2),len(a)):
#print('entering for loop to check five')
#print(check_five , 'is index of number being checked for divisibility by 5')
#print(a[check_five], ' is the numerical value of number divisible by 5 ')
if a[check_five] % 5 == 0:
#print('entering if in check 5 for loop')
div_by_5 = a[check_five]
#print(div_by_5, ' is divisible by 5')
#print(('index being replaced is ', a.index(div_by_2)) , ' with value' , a[check_five])
#print('the number divisible by 5 is being replaced with , ' ,a[div_by_2])
a[a.index(div_by_2)] , a[check_five] =a[check_five] , div_by_2
#print(' list updated! as ' , a)
break
print('the original list was' , b)
print('the final list is' , a)
它還應該用 2n (其中 m,n 屬於自然數)代替 5m,而不僅僅是一種方法。
我被困住了。 我已經嘗試了很多方法並采用了這個方法,因為這是我所能做的。 任何幫助,將不勝感激。
我會以不同的方式解決這個問題:
讓我知道這是否適合您:
a = [2,2,5,5,4,5,5,6,5]
lis=a.copy()
b = [i%5 for i in a]
c = [i%2 for i in a]
parsed = []
for i in range(len(a)):
if i not in parsed:
if c[i]==0:
if 0 in b:
parsed.append(b.index(0))
a[i],a[b.index(0)]=a[b.index(0)],a[i]
b[b.index(0)]=1
elif b[i]==0:
b[i]=1
print('Original list:',lis)
print('Final list',a)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.