用字符串Python

时间:2018-09-16 22:16:38

标签: python list

我正在使用Python进行代码分配,并且正在努力理解为什么我的代码无法正常工作。

在Python中编写一个名为“ BooHoo”的函数,该函数接受一个整数n,并将所有从1到n的整数存储在列表中。但是,如果列表中的整数可被3整除,则列表应改为包含“ Boo”。如果整数可以被5整除,则列表应改为包含“ Hoo”。如果该整数可以被3和5整除,则列表应改为包含“ BooHoo”。

def BooHoo(n):
'''
A function which returns a list of integers, and replaces integers divisible by 3 with "Boo" and integers
divisible by 5 with "Hoo" and integers divisible by 3 and 5 with "BooHoo"


Parameters
-------
n: an integer


Returns
--------

final_list: a Python list

'''

main_list = []
for x in range(n):
    main_list.append(x)


for idx, j in enumerate(main_list):
    if not (idx % 3) and not (idx % 5):
        main_list.pop(idx)
        main_list.insert(idx, 'BooHoo')
    elif not (idx % 3):
            main_list.pop(idx)
            main_list.insert(idx, 'Boo')
    elif not (idx % 5):
            main_list.pop(idx)
            main_list.insert(idx, 'Hoo')
    else:
        continue

final_list = [main_list]

return final_list

3 个答案:

答案 0 :(得分:1)

关于列表的索引和实际元素存在一些逻辑错误。我已经通过评论#突出显示了修改/添加的行。主要是,您需要将idx替换为j,因为idx是一个索引,而j是一个实际的元素。如果您以range(n)开始,则没关系,因为索引与j相同。但是由于您在问题中提到过,您想要存储从1n的数字,因此需要使用range(1, n+1)

def BooHoo(n):
    main_list = []
    for x in range(1,n+1): # replaced range(n) to start from 1
        main_list.append(x)

    for idx, j in enumerate(main_list):
        if not (j % 3) and not (j % 5): # replaced idx by j
            main_list.pop(idx)
            main_list.insert(idx, 'BooHoo')
        elif not (j % 3): # replaced idx by j
                main_list.pop(idx)
                main_list.insert(idx, 'Boo')
        elif not (j % 5): # replaced idx by j
                main_list.pop(idx)
                main_list.insert(idx, 'Hoo')
        else:
            continue

    return main_list # Removed unnecessary second list

# Call the function
print (BooHoo(15))

输出

[1, 2, 'Boo', 4, 'Hoo', 'Boo', 7, 8, 'Boo', 'Hoo', 11, 'Boo', 13, 14, 'BooHoo']

答案 1 :(得分:0)

解决问题的更好方法是从一开始就构建正确的列表(使用循环或列表理解),而不是修改数字顺序列表。

def BooHoo(n):
    return ['BooHoo' if not (i % 5 or i % 3) else 
               'Hoo' if not i % 5 else 
               'Boo' if not i % 3 else 
                   i for i in range(1,n+1)]

基于乐趣的是基于字典的解决方案,而不是出于实用性考虑

def BooHoo(n):
    words = {(1,1): 'BooHoo', (1,0): 'Boo', (0,1): 'Hoo'}
    return [words.get((i % 3 == 0, i % 5 == 0), i) for i in range(1, n+1)]

答案 2 :(得分:0)

为什么要这么麻烦地进行附加和弹出操作,这没必要

pod 'EstimoteProximitySDK', '= 1.1.0-swift4.2'

输出

def BooHoo(n):

    for index, item in enumerate(list(range(1, (n+1))):
        if not item % 5 and not item % 3:
            lista[index] = "BooHoo"
        elif not item % 3:
            lista[index] = "Boo"
        elif not item % 5:
            lista[index] = "Hoo"
        else:
            pass

    return lista 

print(BooHoo(25))
相关问题