繁体   English   中英

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

[英]I want to swap a number divisible by 2 with the next number divisible by 5 in a list

示例 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)

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

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

我会以不同的方式解决这个问题:

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

让我知道这是否适合您:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM