Help improve Python code with List Comprehensions

I am writing small Python programs to learn more about the language. The very last feature I tried to understand was List Comprehensions. I created a little script that evaluates when my car needs the next oil change, depending on how often I got oil changed in the past. The code snippet below oil_changesis a list of the miles on which I received the butter.

# Compute a list of the mileage differences between each oil change.
diffs = [j - i for i, j in zip(oil_changes[:-1], oil_changes[1:])]

# Use the average difference between oil changes to estimate the next change.
next_oil = oil_changes[-1] + sum(diffs) / len(diffs)

The code gives the correct answer (performed a mathematical check manually), but so far it does not feel pretty Pythonic. Am I doing a lot of unnecessary copying of the source list in the first line? I feel that there is a much better way to do this, but I don’t know what it is.

+3
source share
5 answers

As pointed out in other answers, you really don't need to worry if your list is oil_changestoo long. However, as a fan of "streaming" computing, I am interested to note that it itertoolsoffers all the tools necessary to calculate your value next_oilin O (1) space (and O (N) time of course! -) no matter how big N, i.e. e. len(next_oil)gets.

izip , , O (N). O (1) - izip tee - , O (N) , , ! -). :

  it = iter(oil_changes)
  a, b = itertools.tee(it)
  b.next()
  thesum = 0
  for thelen, (i, j) in enumerate(itertools.izip(a, b)):
    thesum += j - i
  last_one = j
  next_oil = last_one + thesum / (thelen + 1)

, , , .. ( ) b. tee O (x), x - ; 1, O (1).

izip "" -, enumerate, , , .. , ( +1 , enumerate 0! -). +=, (sum , ! -).

last_one = a.next(), , a - izip iterables , a b ! -). , Python - j - , , b , izip ( , thelen , enumerate). last_one , j , .

, , !) - , , . - "Impara l'Arte, e mettila da parte!"... " , " - , , : , - , , - , , , ! -)

+9

:

assert len(oil_changes) >= 2
sum_of_diffs = oil_changes[-1] - oil_changes[0]
number_of_diffs = len(oil_changes) - 1
average_diff = sum_of_diffs / float(number_of_diffs)
+9

itertools . , izip zip .

average, diffs :

from itertools import izip

def average(items):
    sum, count = 0, 0

    for item in items:
        sum   += item
        count += 1

    return sum / count

diffs = (j - i for i, j in izip(oil_changes[:-1], oil_changes[1:])
next_oil = oil_changes[-1] + average(diffs)

diffs :

diffs = [oil_changes[i] - oil_changes[i-1] for i in xrange(1, len(oil_changes))]

, . , .

+3

, . ( , , ). , , itertools.islice itertools.izip, ( izip) . , . ? ? , , ?

+2

?

, . , . , . zip izip, ( python 3.0, zip izip).

Knuth .

( oil_changes[:-1] oil_changes, zip() )

+2

Source: https://habr.com/ru/post/1712161/


All Articles