且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python-算法语句

更新时间:2023-02-26 20:30:11

 地图(分钟,[NUMS [X:X +窗口]对于x中的xrange(LEN(NUMS) - (窗口-1))])
 

不过,这将创建一个中间表,所以:

  [分钟(NUMS [X:X +窗口])对于x中的xrange(LEN(NUMS) - (窗口+ 1))]
 

实际上是更好的,这是你目前拥有。

有更多的时间有效的方式,但是,这将是更code。一旦你有一个窗口的最小价值,你正在做的是寻找下一个时隙,因此,所有你需要做的是比较最小值从previous(窗口-1)的元素到下一个值。以较小者为准将在结果列表中的下一个数字。重复。

例如,如果你有四个元素的列表,你的窗口尺寸3.在搜索结果列表中的第一个值将是最小的前三个要素,并在搜索结果列表中的第二个值将是最低的最后的三要素。

有两个元素的重叠出现。所以,你可以保存最后一个窗口,1单元的最小值和比较,为下一个值列表中得到最小值为下一个窗口。重复。

对于文件处理,

 开放(文件)作为F1:
    N = INT(f1.readline())
    numbers_list =地图(INT,f1.readline()。斯普利特(''))
 

会更有效。

I want to write a program which does the follows : -

Sample Input:

3
10 4 18 2 6 19 24 1 20

Expected Output:

4 2 2 2 6 1 1

The input will from a file in which the first line will contain the window size N, the second line will contain a stream of numbers separated by space. You need to output the smallest numbers in each window separated by space.

This is what I wrote:-

with open ("file") as f1:
    n = int(f1.readline())
    numbers = f1.readline()

# converting the string of numbers into a list
numbers_list = map(int,numbers[:-1].split(' ')) 

# getting all the sub-lists of size n from the numbers_list and printing their respective minimum elements.
print [min(numbers_list[i:i+n]) for i in xrange(len(numbers_list)-n+1)] 

My o/p

[4, 2, 2, 2, 6, 1, 1]

Is there some better solution than this? Any optimized version of this solution.

map(min, [nums[x:x+window] for x in xrange(len(nums)-(window-1))])

However, this creates an intermediate list, so:

[min(nums[x:x+window]) for x in xrange(len(nums)-(window+1))] 

is actually better, which is what you currently have.

There is a more time efficient way, however, it would be more code. Once you have the min-value for a window, all you're doing is looking at the next slot, so all you need to do is compare the min value from the previous (window-1) elements to the next value. Whichever is smaller will be the next number in your results list. Repeat.

For example, if you have a four element list and your window is size 3. The first value in your results list will be the minimum of the first three elements, and the second value in your results list will be the minimum of the last three elements.

There's a two element overlap there. So you can save the minimum value of the last window-1 elements and compare that to the next value in the list to get the min value for the next window. Repeat.

With respect to the file handling,

with open ("file") as f1:
    n = int(f1.readline())
    numbers_list = map(int, f1.readline().split(' ')) 

is slightly more efficient.