python - Return the "valid" numbers -


i need write function in python, returns valid measurements list of numbers. measure invalid, if closest other measurement less 0.1 second away. also, output list should same length length of input list.

thus:

[5.1, 5.6, 6.0, 10.34, 10.37, 10.45, 12.5] should return [true, true, true, false, false, false, true]

i have approached problem in following fashion:

list = [5.1, 5.6, 6.0, 10.34, 10.37, 10.45, 12.5] newlist = []  i, j in zip(list, list[1:]):     if j - >= .1:         newlist.append(true)     else:         newlist.append(false) 

the problem returns following list: [true, true, true, false, false, true] 1 false measurement missing.

how can write code differently?

your assumption incorrect. there's 2 false measurements. 1 @ 10.37 , 1 @ 10.45. measurement @ 10.34 ok since happens several seconds after previous one.

your result has 1 less value input list because you're comparing values 2 2.

it's typical "intervals & values" problem. there's 1 less interval values.

write test better performance (list comprehension):

measures = [5.1, 5.6, 6.0, 10.34, 10.37, 10.45, 12.5] print([abs(measures[i+1]-measures[i])>0.1 in range(len(measures)-1)])  [true, true, true, false, false, true] 

(your code creates lot of useless temporary lists. avoid using list variable)

however, if want invalidate all measurements close, no fancy stuff, sliding window:

measures = [5.1, 5.6, 6.0, 10.34, 10.37, 10.45, 12.5] result = [true] * len(measures)  in range(len(measures)-1):     validity = abs(measures[i+1]-measures[i])>0.1     if result[i]:  # don't overwrite invalidated value         result[i] = validity     result[i+1] = validity  print(result)  [true, true, true, false, false, false, true] 

details:

  • creates result array of size of input array (* operator, nice)
  • iterates through elements of list last one
  • compares current value , "next" value compute validity flag (true or false)
  • if current result false, means previous iteration invalidated it, leave as-is, else set validity
  • set "next" result validity (i+1 index)

no temporary list creation, should fast enough.


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -