Python链表最小值 [英] Python Linked list minimum value

查看:105
本文介绍了Python链表最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在列表中找到最小值,而不必使用min函数,而只是通过比较列表中的第一个和下一个元素. 这是我的尝试:

I am trying to find the minimum value in the list without having to use the min function and just by comparing the first and the next element through the list. This is my attempt:

def min(self):
    node = self.head               #1st element 
    Min = 0                        #node.next_node is the next element
    while node:
        if node.value > node.next_node.value:
            Min = node.next_node.value
        else:
            Min = node.value

我只是比较第一个和第二个元素.我如何遍历整个列表

i am just comparing the first and the second element. how do i traverse through the entire list

推荐答案

在不知道您的节点实现细节的情况下,特别地回答此问题将很困难,并且因为这几乎肯定是一项家庭作业问题,因此无论如何也不会出现这种情况.

Answering this specifically would be difficult without knowing the specifics of your node implementation, and as this is almost certainly a homework problem wouldn't be sporting anyway.

您想要做的是遍历列表的每个元素,并将其与您拥有的最小值进行比较.如果更高,则转到下一个元素.如果较低,则将Min设置为该值,然后转到下一个元素.无需直接比较两个元素:只需将所有内容与Min进行比较即可.这种遍历列表并使用单个值变量进行操作的方式非常有用:您还可以将其用于移动平均值之类的事情.

What you want to do is go through each element of the list, and compare it to the Min you have. If it's higher, then just go to the next element. If it's lower, then set Min to the value, and go to the next element. There's no need to compare two elements directly: just compare everything to Min. This style of going through a list and doing something with a single value variable is pretty widely useful: you can also use it for things like moving averages.

最简单的方法是将Min设置为第一个元素的值,即使不是很优雅.这样,您将可以比较一些东西.如果将其设置为其他值,例如0,那么如果所有值都大于0,则永远不会设置Min.另一种选择是将Min设置为足够大的值,但这不如仅将其设置为第一个元素的值安全.

It's easiest, if not amazingly elegant, to start by setting Min to the value of the first element; that way you'll have something to compare to. If you set it to something else, like 0, then if all your values are higher than 0, you'll never set Min. An alternative is to set Min to something sufficiently large, but that's not as safe as just setting it to the first element's value.

如何遍历列表取决于该列表的设计方式.如果节点始终为真,并且列表末尾的node.next_nodeNone,则类似while nodenode = node.next_node的东西可以工作,因为这将在最后停止循环.如果您在最后提出错误,则必须做其他事情.

How you loop through the list is dependent on how this list is designed. Something like while node with node = node.next_node can work, if a node is always true, and node.next_node at the end of the list is None, since this will stop the loop at the end. If you instead raise an error at the end, you'll have to do something else.

这篇关于Python链表最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆