[英]How can I change this function call and algorithm to find the string with the smallest value in a list of size n. w/o the min function
How can I change this function call and algorithm to find the string with the smallest value in a list with size n. 如何更改此函数调用和算法,以在大小为n的列表中找到值最小的字符串。 Also I am aware of the built-in min function, I am simply trying to understand the mechanics.
我也知道内置的min函数,我只是想了解机制。 Let me also preface this by saying I am a first semester CS student, so I apologize in advance for my ignorance.
首先,我还说自己是CS的第一学期学生,因此我为自己的无知向您道歉。
def main():
strOne = 'stack'
strTwo = 'over'
strThree = 'flow'
strFour = 'please'
strFive = 'help'
first = alphabetical(strOne, strTwo, strThree, strFour, strFive)
print(first)
def alphabetical(one, two, three, four, five):
low = one
if two < low:
low = two
if three < low:
low = three
if four < low:
low = four
if five < low:
low = five
return low
main()
###################################################################
# str_list = ['stack', 'over', 'flow', 'please', 'help'] ?? #
# for i in str_list: ?? perhaps on the right track with this idea.#
# first = alphabetical(i) ?? maybe #
###################################################################
Using sort does too many comparisons. 使用sort进行的比较过多。 To emulate what min does, you should make just a single pass over the data, updating the best (lowest) value seen so far.
为了模拟min的作用,您应该对数据进行一次传递,以更新迄今为止看到的最佳(最低)值。
>>> def lowest(sequence):
'Find the lowest value in a sequence in just one-pass'
best = sequence[0]
for i in range(1, len(sequence)):
if sequence[i] < best:
best = sequence[i]
return best
>>> lowest(['stack', 'over', 'flow', 'please', 'help'])
'flow'
list.sort()
will sort a list in-place. list.sort()
将对列表进行排序。 Element [0]
is first element in a list. 元素
[0]
是列表中的第一个元素。 This should be everything needed to accomplish what you're doing, without a fixed-parameter function. 这应该是完成您的工作所需的一切,而没有固定参数的功能。
Playing around in the python interactive shell: 在python交互式shell中玩:
>>> l = ['stack', 'over', 'flow']
>>>
>>> l.sort()
>>>
>>> l
['flow', 'over', 'stack']
>>> l[0]
'flow'
A program 一个程序
def main():
str_list = ['stack', 'over', 'flow', 'please', 'help']
str_list.sort() # Doesn't return anything; sorts the list in-place.
print 'First string:', str_list[0]
if __name__ == '__main__':
main()
You can use the built-in function min: 您可以使用内置函数min:
>>> min('stack', 'over', 'flow', 'please', 'help')
'flow'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.