我想将一个可被 2 整除的数字与列表中的下一个可被 5 整除的数字交换

Eli*_*hed 2 python

示例 1

来源: [2, 4, 2, 4, 5, 10]

预期:[5, 10, 2, 4, 2, 4]
获得:[5, 10, 2, 4, 2, 4]

我的代码为我提供了这种组合的准确结果。

示例 2

来源: [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]

我的代码没有在这里提供所需的结果。

示例 3

来源: [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)
Run Code Online (Sandbox Code Playgroud)

它还应该用 2n (其中 m,n 属于自然数)代替 5m ,而不仅仅是一种方法。

我被困住了。我已经尝试了很多方法并采用了这个方法,因为这是我所能做的。任何帮助,将不胜感激。

Tom*_*šek 5

I'd go about the problem differently:

  • iterate over the list
  • 如果数字不能被 2 整除 -> 将数字推送到 first_list
  • 如果数字可被 2 整除 -> 将其分配给 divisible_by_2 变量
    • 继续迭代
    • 如果不能被 5 整除 -> 将数字推送到 second_list
    • 如果可以被 5 整除 -> 将数字推送到 first_list
      • 将 second_list 连接到 first_list
      • 将 divisible_by_2 变量推入 first_list
      • 继续迭代并将所有后续数字推送到 first_list