小编use*_*505的帖子

递归计算字符

def count_m_recursive(sentence):
    s = len(sentence) 
    if s == 0:
        return 0
    elif sentence[0] == 'm':
        return 1
    else:
        return count_m_recursive(sentence[1:s-1]
Run Code Online (Sandbox Code Playgroud)

这是我的代码.所以,如果count_m_recursive('my oh my')我得到2

代码有什么问题?

python recursion

9
推荐指数
3
解决办法
3397
查看次数

找到列表中的对数

假设lst = [7,1,5,4,2,3,6],(7, 2), (5, 4), (6, 3)是一些对和总有6个对,加起来 9

(i)一对中的数字顺序很重要.例如,(7,2)和(2,7)是两对不同的对.(ii)数字不能与自身配对.(iii)清单中没有重复的要素

def find_pairs(lst, key):
    count = 0
    if sum(lst[count:count+1]) == key:
        count += 1
        return count
    else:
        return find_pairs(lst[1:],key)  
Run Code Online (Sandbox Code Playgroud)

这是我的代码.怎么了 ??我得到一个错误的输入find_pairs([7,1,5,4,2,3,6], 9)给予6

find_pairs(list(range(1, 100, 2)), 55) #0
find_pairs(list(range(1, 100, 2)), 56) #28
Run Code Online (Sandbox Code Playgroud)

python

4
推荐指数
1
解决办法
7624
查看次数

转置列表

假设我有一个嵌套列表m = [[2, 3], [4, 7]]并且我想转置它以便我得到[[2, 4], [3, 7]] OR如果m可以[[1,2,3],[4,5,6],[7,8,9]]然后通过转置函数后我应该得到[[1,4,7],[2,5,8],[3,6,9]] 它应该也适用于[[1,2,3],[4,5,6]]哪个返回[[1,4],[2,5],[5,6]]

def transpose(m):
    t = make_copy(m)  ##[[2, 3], [4, 7]]
    if len(t) == 1:  ## if [[1]]
        return t  ##[[1]]
    i = 0
    while i <= len(t): #0 <= 2
        t[0][i] = t[i][0] #t[0][0] = t[0]t[0] ## t[0][1] = t[1][0] so now 3 = 4
        i += 1  #1
        return t
Run Code Online (Sandbox Code Playgroud)

我认为这应该有效,但它没有给我我想要的答案.怎么了 ?

python

1
推荐指数
1
解决办法
107
查看次数

Tuplify一些

def tuplify(number):
    x = str(number)
    if len(x) <= 0:
        return 0
    lst = []
    for i in range(0,10):
        if i == x[len(x)-1]:
            lst.append(i)
        return tuple(lst)
Run Code Online (Sandbox Code Playgroud)

这是我的代码,我无法得到我想要的输出.

tuplify(102486) 这应该给我 (1, 0, 2, 4, 8, 6)

python

1
推荐指数
1
解决办法
450
查看次数

面向对象的编程错误

class Ammo(Thing):

    # constructor here
    def __init__(self,name,weapon,quantity):
        self.name = name
        self.weapon = weapon
        self.quantity = quantity

    # definition of weapon_type here
    def weapon_type(self):
        return self.weapon
Run Code Online (Sandbox Code Playgroud)

这是我的代码,当我尝试检索weapon_type为string 这里是我的输入

bow = Weapon('bow', 10, 20)
arrows = Ammo('arrow', bow, 5)
print(arrows.weapon_type())   ## bow 
Run Code Online (Sandbox Code Playgroud)

bow相反,我没有得到<__main__.Weapon object at 0x0211DCB0>

python

0
推荐指数
1
解决办法
104
查看次数

不使用 set() 删除元组中的重复项

x = (1,1,-13,8,5,0,4,-1,-4)

a = filter(lambda i,j: i == j, x)

print(tuple(a))
Run Code Online (Sandbox Code Playgroud)

我收到错误而不是正确答案(1,-13,8,5,0,4,-1,-4)。我的错误是什么?

python tuples set duplicates

0
推荐指数
1
解决办法
4014
查看次数

标签 统计

python ×6

duplicates ×1

recursion ×1

set ×1

tuples ×1