Re: how to exit from a nested loop in python

2019-02-08 Thread Peter Otten
Kaka wrote:

> for i  in range(len(A.hp)):
> 
> for j in range(len(run_parameters.bits_Mod)):
>  req_slots[j] = math.ceil((A.T[i])
> 
>  for g in Temp[i]["Available_ranges"][j]:
>   for s in range(g[0], g[-1]):
>   if (s+req_slots[j]-1) <= g[-1]:
>  if (Temp[i]['cost'][j] <= (run_parameters.PSD):  --
>  When this condition is true i want to break the nested
>  loop and start from the begining
>served_count +=1
>A.T[i]["First_index"]= s
>A.T[i]["Last_index"]= s+req_slots[j]-1
>A.T[i]["Status"]= 1
>A.T[i]["Selected_MOD"] = j
>break

Thou shalt indent four spaces. One shalt thou not indent excepting that thou 
then proceed to four.
 
> I have this code. When the last "if" condition is satisfied, i want to
> break all the loops and start the nested loop for next i. else, the loop
> should continue.
> 
> can anyone help me?

Option 1: Collaps your inner loops into a generator:

gen(a):
for b in ...:
for c in ...:
yield a, b, c

for a in ...:
for b, c in gen(a):
if f(a, b, c):
...
break


Option 2: If your code is too messy for option 1, use a helper function:

def process(a):
for b in ...:
for c in ...:
if f(a, b, c):
...
return

for a in ...:
process(a)

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The sum of ten numbers inserted from the user

2019-02-08 Thread ^Bart

x = 0
for jnk in range(10):
x += int(input("Enter a number: ")
print(x)


It works, there's a missed )

A colleague did:

total=0
for n in range(10):

n= int(input("Enter a number: "))
total=total+n

print(total)

I understood your code is more clean!

^Bart


--
https://mail.python.org/mailman/listinfo/python-list


Re: Loop with else clause

2019-02-08 Thread Adriaan Renting


Wow, you dug deep.

My example was the reverse of the "toy example"'s you mention as I find
that often code becomes much clearer if you order it such that
specific cases, sanity checking and exceptions go first, and then the
default case at the end.

So my general suggestion would be to handle your empty list/no valid
candidates cases first,
and then do the for loop at the end.

If you style this with if/elif/else, or put return statements in
certain places, I have no opinion about and will depend on the specific
problem.

Cheers,

Adriaan Renting.

>>> On 7-2-2019 at 9:42, DL Neil 
wrote: 
> Further to our discussion of how to improve a code review's discovery
of 
> the mistaken handling of a for...else... construct:-
> 
> 
> Yesterday was a national holiday, but today gave some opportunity to

> research. Way back in 2009 there was spirited discussion over on the

> Python Ideas list (warning, even the mailing list's index covers 
> multiple screen-lengths):
> 
> - this confusion is not new by any measure, herewith a list of
previous 
> occasions "fists were raised concerning for..else."
>
https://mail.python.org/pipermail/python-ideas/2009-October/006164.html
> 
> - an excellent summary of the 2009 debate which offers no less than
six 
> ways to 'improve' for... else...
>
https://mail.python.org/pipermail/python-ideas/2009-October/006155.html
> 
> - (as mentioned earlier) the BDFL weighed-in a couple of times. His 
> regret is: "That's a flaw, and I don't quite know what to do about
it. 
> It's about 20 years too late to remove or rename it. But we probably

> should not do more of these. That's a lesson."
> (OK, so make that thirty years - older than the coder who the 
> code-review noticed falling into this coding 'gotcha'!)
>
https://mail.python.org/pipermail/python-ideas/2009-October/006083.html
> 
> - herewith a (rather complicated) suggestion, and critique
>
https://mail.python.org/pipermail/python-ideas/2009-October/006054.html
> 
> - one rather hopeful option (actual words to be used
notwithstanding)
>   for i in SEQ:
> A
>   except:
> B
>   else:
> C
> appears here:
>
https://mail.python.org/pipermail/python-ideas/2009-October/006044.html
> 
> 
> Somewhat related, PEP 548 proposed an "More Flexible Loop Control".
This 
> was addressing the confusion caused by break within a loop. It was
rejected.
> 
> 
> Each of the above addresses issues 'within', that is to say
happenings 
> during iteration - whether the entire loop or iteration cut-short by
a 
> break (and thus the idea that "else" might be re-worded to indicate 
> 'after a break').
> 
> However, as mentioned by one contributor, the specific use-case our
team 
> faced was an issue that arises prior to the loop.
Alternately-expressed: 
> that according to Python's logic, prevents even a single iteration of

> that loop. Thus, any 'solution' would reside outside of for and while

> statements because they only consider if a loop should continue or 
> terminate - not handling the question of whether it should start at
all!
> 
> PEP 315 is the only discussion (I've found) which looks 'outside' or

> 'before' the loop itself. It proposed an "Enhanced While Loop", 
> attempting to separate 'setup' or loop control from loop content. It
was 
> rejected.
> 
> 
> So, reading-around brought nothing much useful. Back to the
code-face...
> 
> Thank you to the several folk who responded with ideas to
express/improve:
> 
>  if list:
>  process_list() #the heading and for-loop, as above
>  else:
>  print( "Sorry...
> 
> NB this is a constructed 'toy example' attempting to be the shortest

> illustration of use-cases and invented purely to communicate the need

> and structure. It was expected to be interpreted as
pseudo-python-code. 
> (you'd not use/allow "process_list" as the name of a function, would
you?)
> 
> (With apologies as necessary) one of the dangers of 'toy examples' is

> the reader taking them at face value, instead of as (over-)simplified

> illustrations. In 'real life' the loop code and the no-loop exception

> are both considerably longer than a single line. Accordingly, using a

> function would be a good way to summarise and self-document the 
> activity, ie the if statement's two code-blocks would make the whole

> statement very/too-long (readability)!
> 
> The "if list:" expression is overly-simplistic. The recommendation of

> "if len(list):" is absolutely sound, for reasons of polymorphism.
> 
> In-lieu of a Python construct, there are definitely situations when
use 
> of a sentinel makes better sense. However, given their risk, in many

> ways Python tries to avoid using such, eg consuming iterators until a

> StopIteration exception is returned. (includes files, is subsumed by

> ContextManagers...), thus "pythonic". That said, the classic use of 
> for... else... is in searching for a particular element within an 
> iterable which has all the hallmarks of a "sentinel

Re: timezones

2019-02-08 Thread Jaap van Wingerde
The blog of Paul Gansele [1] made me trying an other approach.

#!/usr/bin/env python3
# -*- coding: utf_8 -*-
### tested with python3.5
from datetime import datetime, timedelta, timezone
from dateutil import tz
amsterdam = tz.gettz('Europe/Amsterdam')
utc = tz.gettz('utc')
amsterdam_datetime = datetime(2018, 12, 17, 11, 31, 26,
tzinfo=amsterdam) print(amsterdam_datetime)
tuple = amsterdam_datetime.utctimetuple()
utc_datetime = datetime(tuple[0], tuple[1], tuple[2], tuple[3],
tuple[4], tuple[5]) print(utc_datetime)
amsterdam_datetime = datetime(2018, 6, 17, 11, 31, 26, tzinfo=amsterdam)
print(amsterdam_datetime)
tuple = amsterdam_datetime.utctimetuple()
utc_datetime = datetime(tuple[0], tuple[1], tuple[2], tuple[3],
tuple[4], tuple[5]) print(utc_datetime)

Output:
2018-12-17 11:31:26+01:00
2018-12-17 10:31:26
2018-06-17 11:31:26+02:00
2018-06-17 09:31:26

[1]
pytz: The Fastest Footgun in the West
2018-03-19
https://blog.ganssle.io/articles/2018/03/pytz-fastest-footgun.html


Op 2019-02-07T17:56:21+ schreef David Raymond
 in bericht
,
inzake:  het volgende.

> I'd say if the documentation mentions it, but doesn't say why, then
> we're not gonna be able to do much better for you as far as "why"
> goes.
> 
> http://pytz.sourceforge.net/
> 
> "Unfortunately using the tzinfo argument of the standard datetime
> constructors "does not work" with pytz for many timezones."
> 
> But it looks like they suggest something along the lines of...
> 
> timezone('Europe/Amsterdam').localize(datetime(2018, 12, 17, 11, 31,
> 26))
> 
> 
> From the examples on
> http://pytz.sourceforge.net/#problems-with-localtime ...
> 
> >>> eastern = timezone('US/Eastern')
> >>> fmt = '%Y-%m-%d %H:%M:%S %Z%z'
> >>> loc_dt = datetime(2002, 10, 27, 1, 30, 00)
> >>> est_dt = eastern.localize(loc_dt, is_dst=True)
> >>> edt_dt = eastern.localize(loc_dt, is_dst=False)
> >>> print(est_dt.strftime(fmt) + ' / ' + edt_dt.strftime(fmt))  
> 2002-10-27 01:30:00 EDT-0400 / 2002-10-27 01:30:00 EST-0500
> 
> 
> Browse through their examples and see if you can find something
> similar that works for you.
> 
> 
> -Original Message-
> From: Python-list
> [mailto:python-list-bounces+david.raymond=tomtom@python.org] On
> Behalf Of Jaap van Wingerde Sent: Wednesday, February 06, 2019 9:27
> AM To: python-list@python.org Subject: timezones
> 
> I made a small script to practise with timezones:
> 
> #!/usr/bin/env python3
> # -*- coding: utf_8 -*-
> from datetime import datetime, timedelta
> from pytz import timezone
> import pytz
> amsterdam_datetime = datetime(2018, 12, 17, 11, 31, 26,
> tzinfo=timezone('Europe/Amsterdam'))
> print(amsterdam_datetime)
> utc_datetime = amsterdam_datetime.astimezone(pytz.utc)
> print(utc_datetime)
> amsterdam_datetime = datetime(2018, 6, 17, 11, 31, 26,
> tzinfo=timezone('Europe/Amsterdam'))
> print(amsterdam_datetime)
> utc_datetime = amsterdam_datetime.astimezone(pytz.utc)
> print(utc_datetime)
> 
> The output of the script is:
> 2018-12-17 11:31:26+00:20
> 2018-12-17 11:11:26+00:00
> 2018-06-17 11:31:26+00:20
> 2018-06-17 11:11:26+00:00
> 
> I respected:
> 2018-12-17 11:31:26+01:00
> 2018-12-17 10:31:26+00:00
> 2018-06-17 11:31:26+02:00
> 2018-06-17 09:31:26+00:00
> 
> I need this functionality for adjusting wrong timestamps in Android
> JPG-images as the 'Exif.GPSInfo.GPSTimeStamp' and
> 'Exif.GPSInfo.GPSDateStamp' are missing.
> 
> Why I get this unrespected results?
> 
> Kind regards,
> Jaap.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python program to phone?

2019-02-08 Thread Mario R. Osorio
You will need to have java. BeeWare's VOC tool, a transpiler from python to
java, will do all the work for you so you don't even have know anything
about java, except installing and setting it up for your environment

Dtb/Gby
===
Mario R. Osorio
B.A.S. of Information Technology
A.S. of Computer Programming and Analysis
Web page: *http;//mario.osorio.solutions
*
Email: *mario@osorio.solutions* 
*Just Choose Python!* 

“If I had asked people what they wanted, they would have said faster
horses.”
 ― Henry Ford








On Thu, Feb 7, 2019 at 11:00 PM Steve  wrote:

> BeeWare looks as if it requires Java, does it?
> Is it exclusively java?
>
> =
> Footnote:
> Zamboni locks up after running into large patch of loose teeth.
>
> -Original Message-
> From: Python-list  On
> Behalf Of Mario R. Osorio
> Sent: Tuesday, February 5, 2019 8:58 AM
> To: python-list@python.org
> Subject: Re: Python program to phone?
>
>
> Hi there Steve. Did you check BeeWare? (https://pybee.org/)
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python program to phone?

2019-02-08 Thread Mario R. Osorio
I am not an expert in BeeWare (I've never used it) but I've read a good
portion of their documentation and find it very interesting to say
the least. I am looking forward using it in the very near future.

On Fri, Feb 8, 2019 at 11:06 AM Mario R. Osorio 
wrote:

> You will need to have java. BeeWare's VOC tool, a transpiler from python
> to java, will do all the work for you so you don't even have know anything
> about java, except installing and setting it up for your environment
>
> Dtb/Gby
> ===
> Mario R. Osorio
> B.A.S. of Information Technology
> A.S. of Computer Programming and Analysis
> Web page: *http;//mario.osorio.solutions
> *
> Email: *mario@osorio.solutions* 
> *Just Choose Python!* 
>
> “If I had asked people what they wanted, they would have said faster
> horses.”
>  ― Henry Ford
>
>
>
>
> 
> 
>
>
> On Thu, Feb 7, 2019 at 11:00 PM Steve  wrote:
>
>> BeeWare looks as if it requires Java, does it?
>> Is it exclusively java?
>>
>> =
>> Footnote:
>> Zamboni locks up after running into large patch of loose teeth.
>>
>> -Original Message-
>> From: Python-list  On
>> Behalf Of Mario R. Osorio
>> Sent: Tuesday, February 5, 2019 8:58 AM
>> To: python-list@python.org
>> Subject: Re: Python program to phone?
>>
>>
>> Hi there Steve. Did you check BeeWare? (https://pybee.org/)
>>
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to exit from a nested loop in python

2019-02-08 Thread Rurpy via Python-list
On Thursday, February 7, 2019 at 11:45:23 PM UTC-7, Kaka wrote:
> for i  in range(len(A.hp)):
> 
> for j in range(len(run_parameters.bits_Mod)):
>  req_slots[j] = math.ceil((A.T[i])
> 
>  for g in Temp[i]["Available_ranges"][j]:
>   for s in range(g[0], g[-1]):
>   if (s+req_slots[j]-1) <= g[-1]:
>  if (Temp[i]['cost'][j] <= (run_parameters.PSD):  -- When 
> this condition is true i want to break the nested loop and start from the 
> begining
>served_count +=1
>A.T[i]["First_index"]= s
>A.T[i]["Last_index"]= s+req_slots[j]-1
>A.T[i]["Status"]= 1
>A.T[i]["Selected_MOD"] = j
>break
> 
> I have this code. When the last "if" condition is satisfied, i want to break 
> all the loops and start the nested loop for next i. else, the loop should 
> continue.  
> 
> can anyone help me?

In addition to the two methods Peter posted there is also
the obvious way of using a flag (but perhaps this is what 
you were trying to avoid?)

  for i in (1,2,3):
  nexti = False
  for g in (1,2,3):
  for s in (1,2,3):
  print (i,g,s)
  if (g,s) == (2,2):
  nexti = True
  break
  if nexti: break

You can also use exceptions to do a multi-level break:

  class Next_i (Exception): pass
  for i in (1,2,3):
  try:
  for g in (1,2,3):
  for s in (1,2,3):
  print (i,g,s)
  if (g,s) == (2,2):
  raise Next_i
  except Next_i: continue

-- 
https://mail.python.org/mailman/listinfo/python-list