小编Ram*_*mya的帖子

二进制搜索中的无限循环

我正在尝试使用以下函数实现二进制搜索:

def buggy_binary_search(input, key):
    low = 0
    high = len(input)-1
    mid = (low + high)/2
    while low <= high:
        if input[mid] == key:
            return mid
        if input[mid] > key:
            high = mid - 1
        else:
            low = mid
    return -1
Run Code Online (Sandbox Code Playgroud)

运行时的上述函数进入无限循环.我怎么能纠正这个?

python binary-search infinite-loop

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

在python中反转链表

我被要求反转a以head为参数,其中head是一个链表,例如:1 - > 2 - > 3,它是从已定义的函数返回的,我试图用这种方式实现函数reverse_linked_list:

def reverse_linked_list(head):
temp = head
head = None
temp1 = temp.next
temp2 = temp1.next
temp1.next = None
temp2.next = temp1
temp1.next = temp
return temp2
pass

class Node(object):
    def __init__(self,value=None):
        self.value = value
        self.next = None

def to_linked_list(plist):
head = None
prev = None
for element in plist:
    node = Node(element)
    if not head:
        head = node
    else:
        prev.next = node
    prev = node
return head

def from_linked_list(head):
result = []
counter = …
Run Code Online (Sandbox Code Playgroud)

python linked-list

4
推荐指数
4
解决办法
3万
查看次数

如何在Python中将数字转换为其数字的链表

我被要求将一个数字转换为其数字的链接列表:例如:head = number_to_list(120)number_to_list 是我应该编写的函数,它应该返回其数字列表,listutils.from_linked_list(head) == [1,2,0]而不使用列表和字典等数据结构。我尝试以这种方式编写:

def number_to_list(number):        
    head,tail = None,None
    for x in number:
        node = Node(x)
        if head:
           tail.next = node
        else:
           head = node
           tail = node
    second = head.next
    third = second.next
    fourth = third.next
Run Code Online (Sandbox Code Playgroud)

但我知道我完全错了,因为在 for 循环中,我应该以这样的方式编写代码:它转到数字的第一位数字并创建它的节点。我在这里被阻止了。请帮助我这。

python

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