Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #61314

Re: Eliminate "extra" variable

Path csiph.com!usenet.pasdenom.info!aioe.org!news.stack.nl!newsfeed.xs4all.nl!newsfeed4.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail
Return-Path <python.list@tim.thechases.com>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.000
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; 'else:': 0.03; 'nicely': 0.07; 'none:': 0.07; 'append': 0.09; 'function:': 0.09; 'iterate': 0.09; 'logic': 0.09; 'repeated': 0.09; 'snippet': 0.09; 'subject:extra': 0.09; 'tmp': 0.09; 'def': 0.12; 'times,': 0.14; '-tkc': 0.16; '1):': 0.16; 'called.': 0.16; 'commented': 0.16; 'dictionary.': 0.16; 'from:addr:python.list': 0.16; 'from:addr:tim.thechases.com': 0.16; 'from:name:tim chase': 0.16; 'igor': 0.16; 'iterating': 0.16; 'itertools': 0.16; 'keys.': 0.16; 'n+1,': 0.16; 'okay).': 0.16; 'subject:variable': 0.16; 'tuple': 0.16; 'unneeded': 0.16; 'unpacking': 0.16; 'prevent': 0.16; 'wrote:': 0.18; 'variable': 0.18; 'seems': 0.21; 'import': 0.22; 'handles': 0.22; 'string,': 0.24; 'source': 0.25; 'asking': 0.27; 'header:In-Reply-To:1': 0.27; 'function': 0.29; '(this': 0.29; 'returned': 0.30; 'along': 0.30; '(which': 0.31; 'code': 0.31; 'that.': 0.31; 'gather': 0.31; 'names.': 0.31; 'once,': 0.31; 'yields': 0.31; 'lists': 0.32; 'skip:d 20': 0.34; "i'd": 0.34; 'could': 0.34; 'info': 0.35; 'skip:s 30': 0.35; 'something': 0.35; 'operate': 0.35; 'but': 0.35; 'there': 0.35; 'data,': 0.36; 'dates': 0.36; 'sequence': 0.36; 'yield': 0.36; 'charset:us- ascii': 0.36; 'should': 0.36; 'throughout': 0.37; 'turn': 0.37; 'two': 0.37; 'to:addr:python-list': 0.38; 'rather': 0.38; 'subject:" ': 0.39; 'to:addr:python.org': 0.39; 'either': 0.39; 'called': 0.40; 'days': 0.60; 'even': 0.60; 'results.': 0.60; 'tell': 0.60; 'conversion': 0.61; 'range': 0.61; 'more': 0.64; 'between': 0.67; 'incorporate': 0.68; 'grow': 0.77; 'info)': 0.84; 'received:50.22': 0.84; 'time)': 0.91
Date Sun, 8 Dec 2013 12:58:23 -0600
From Tim Chase <python.list@tim.thechases.com>
To python-list@python.org
Subject Re: Eliminate "extra" variable
In-Reply-To <CA+FnnTwZ3aF++ZzaAJzG0Y98usfLTge0KTzj14LfqDgh1OnsZQ@mail.gmail.com>
References <CA+FnnTzDjRzU65+VWnOwxfVR9FGMDgHLLmLEDOoGE0BMCptzEw@mail.gmail.com> <52A25D94.9040404@islandtraining.com> <CA+FnnTxxJc2J1SF0UHXo1DkZPdN0W5iWhOgBYzfbW1T0GtaSgg@mail.gmail.com> <CA+FnnTzBYp5Fvy1ohCySLitbL21+hHdfur9=oF4TM+Skeu-XJw@mail.gmail.com> <CA+FnnTzkHYNN_rgLaaXwvod9qGhetXRy+3v96+5+wEyhCq0LwA@mail.gmail.com> <CA+FnnTwZ3aF++ZzaAJzG0Y98usfLTge0KTzj14LfqDgh1OnsZQ@mail.gmail.com>
X-Mailer Claws Mail 3.8.1 (GTK+ 2.24.10; x86_64-pc-linux-gnu)
Mime-Version 1.0
Content-Type text/plain; charset=US-ASCII
Content-Transfer-Encoding 7bit
X-AntiAbuse This header was added to track abuse, please include it with any abuse report
X-AntiAbuse Primary Hostname - boston.accountservergroup.com
X-AntiAbuse Original Domain - python.org
X-AntiAbuse Originator/Caller UID/GID - [47 12] / [47 12]
X-AntiAbuse Sender Address Domain - tim.thechases.com
X-Get-Message-Sender-Via boston.accountservergroup.com: authenticated_id: tim@thechases.com
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.15
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <https://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list/>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <https://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.3736.1386529034.18130.python-list@python.org> (permalink)
Lines 132
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1386529034 news.xs4all.nl 2862 [2001:888:2000:d::a6]:58535
X-Complaints-To abuse@xs4all.nl
Xref csiph.com comp.lang.python:61314

Show key headers only | View raw


On 2013-12-07 23:14, Igor Korot wrote:
> def MyFunc(self, originalData):
>      self.dates = []
>       data = {}
>       dateStrs = []
>       for i in xrange(0, len(originalData)):
>             dateStr, freq, source = originalData[i]
>             data[str(dateStr)]  = {source: freq}
>             dateStrs.append(dateStr)
>      for i in xrange(0, len(dateStrs) - 1):
>            currDateStr = str(dateStrs[i])
>            nextDateStr = str(dateStrs[i + 1])
>            self.dates.append(currDateStr)
>            currDate = datetime.datetime.strptime(currDateStr,
> '%Y-%m-%d') nextDate = datetime.datetime.strptime(nextDateStr,
> '%Y-%m-%d') if nextDate - curDate < datetime.timedelta(days=31):
>                d = currDate + datetime.timedelta(days=1)
>                while d < nextDate:
>                    self.dates.append(d.strftime('%Y-%m-%d'))
>                    d = d + datetime.timedelta(days=1)
>      lastDateStr = dateStrs[-1]
>      self.dates.append(str(lastDateStr))
>      return data

It would help to know what you want this function to accomplish:
"MyFunc" isn't exactly descriptive.  From what I gather by reading
it, you want it to do two things:

 - append each date in the range from originalData[0] through
   originalData[-1] to self.dates every time this function is called
   (which means that multiple calls to this will grow self.dates
   every time)

 - if there's less than 31 days between N and N+1, also append all
   the dates in between (this seems weird, but okay).  Again, every
   time this function is called.

 - return a dictionary that maps dates in the input-data to the
   associated source:freq dictionary.

It's hard to tell what you intend to do with these results.  If you
just intend to iterate over them once, asking for associated data,
you could even create a generator that yields the date along with
either None or the associated data.  See below for that.
Alternatively, you can return both the dict-mapping and the date-list
from the function:

  def f(...):
    return (the_dict, the_list)

  a_dict, a_list = f(...)

That would prevent repeated mutation of self.dates

> As you can see there is many conversion going on and there's
> unneeded dateStrs which is used just to loop thru the dictionary
> and get the 2 consecutive keys.

The final snippet of code that I provided handles this pretty nicely
by zipping up the staggered lists and iterating over them while
unpacking them into sensible variable names.  Unless you have a need
to operate on the dates as string, I'd just keep them as dates
throughout the code and only turn them into strings upon output.

> But if you see a better way - please share.

I'd likely incorporate Peter's sliding_window() suggestion and do
something like the following (I commented out using a tuple for the
values, but using a tuple/namedtuple might make more sense)

    import itertools
    def sliding_window(i):
        a, b = itertools.tee(i)
        next(b)
        return itertools.izip(a, b)

    def some_descriptive_function_name(self, original_data):
        # construct these once-per-call rather than every loop
        # or even move them out to module-scope
        ONE_DAY = datetime.timedelta(days=1)
        MONTHISH = datetime.timedelta(days=31)
        for (
                (cur_dt, cur_freq, cur_source),
                (next_dt, next_freq, next_source)
                ) in sliding_window(original_data):
            info = {cur_source: cur_freq}
            # info = (cur_source, cur_freq)
            yield cur_dt, info
            if next_dt - cur_dt < MONTHISH:
                d = cur_dt + ONE_DAY
                while d < next_dt:
                    yield d, None
                    d += ONE_DAY
        info = {next_source: next_freq}
        # info = (next_source, next_freq)
        yield next_dt, info

which can then be used with

  for dt, info in self.some_descriptive_function_name(data):
    # dates should be returned in the same sequence
    # as your original logic
    if info is None:
      do_something_when_no_info(dt)
    else:
      do_something_with_dt_and_info(dt, info)

If you need to iterate over the data multiple times, you can just do

  tmp = list(self.some_descriptive_function_name(data))
  do_first(tmp)
  do_second(tmp)

-tkc

















Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Eliminate "extra" variable Tim Chase <python.list@tim.thechases.com> - 2013-12-08 12:58 -0600

csiph-web