gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:04:37 25 4
gpt4 key购买 nike

示例 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 代替 5m (其中 m、n 属于自然数),而不仅仅是一种方式。

我被困住了。我尝试了很多方法并选择了这个,因为这是我能做到的。任何帮助将不胜感激。

最佳答案

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

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

关于python - 我想将列表中一个能被 2 整除的数字与下一个能被 5 整除的数字交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60591907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com