Re: on perhaps unloading modules?

2021-08-28 Thread Hope Rouselle
"Peter J. Holzer"  writes:

> On 2021-08-22 16:28:12 -0300, Hope Rouselle wrote:
>> I have a certain distaste for syntax too.  For instance, I would much
>> rather write and read ``first(ls)'' than ``ls[0]''.
>
> Would you also prefer `twothousandthreehundredandtwentythird(ls)` over
> `ls[2322]`?

Omg, I'm afraid you are serious! :-D  We could use something like

  list_get(ls, 2322).

Of course that ls[2322] is perfect fine.
-- 
https://mail.python.org/mailman/listinfo/python-list


on writing a while loop for rolling two dice

2021-08-28 Thread Hope Rouselle
How should I write this?  I'd like to roll two six-sided dice until I
get the same number on both.  I'd like to get the number of times I
tried.  Here's a primitive I'm using:

--8<---cut here---start->8---
>>> x, y = roll()
>>> x
6
>>> y
6 # lucky

>>> x, y = roll()
>>> x
4
>>> y
1 # unlucky
--8<---cut here---end--->8---

Here's my solution:

--8<---cut here---start->8---
def how_many_times():
  x, y = 0, 1
  c = 0
  while x != y:
c = c + 1
x, y = roll()
  return c, (x, y)
--8<---cut here---end--->8---

Why am I unhappy?  I'm wish I could confine x, y to the while loop.  The
introduction of ``x, y = 0, 1'' must feel like a trick to a novice.  How
would you write this?  Thank you!
-- 
https://mail.python.org/mailman/listinfo/python-list


on the popularity of loops while and for

2021-08-28 Thread Hope Rouselle
I'd like get a statistic of how often each loop is used in practice.  

I was trying to take a look at the Python's standard libraries --- those
included in a standard installation of Python 3.9.6, say --- to see
which loops are more often used among while and for loops.  Of course,
since English use the preposition ``for'' a lot, that makes my life
harder.  Removing comments is easy, but removing strings is harder.  So
I don't know yet what I'll do.

Have you guys ever measured something like that in a casual or serious
way?  I'd love to know.  Thank you!
-- 
https://mail.python.org/mailman/listinfo/python-list


PEP Idea: Real private attribute

2021-08-28 Thread Mehrzad Saremi
Python currently uses name mangling for double-underscore attributes. Name
mangling is not an ideal method to avoid name conflicting. There are
various normal programming patterns that can simply cause name conflicting
in double-underscore members. A typical example is when a class is
re-decorated using the same decorator. The decorator can not take
double-underscore members without name conflicts. For example:

```
@custom_decorator("a")
@custom_decorator("b")
class C:
pass
```

The `@custom_decorator` wrapper may need to hold private members, but
Python's current name conflict resolution does not provide any solution and
the decorator cannot hold private members without applying tricky
programming methods.

Another example is when a class inherits from a base class of the same name.

```
class View:
"""A class representing a view of an object; similar to
numpy.ndarray.view"""
pass

class Object:
class View(View):
"""A view class costumized for objects of type Object"""
pass
```

Again, in this example, class `Object.View` can't take double-underscore
names without conflicting with `View`'s.

My idea is to introduce real private members (by which I do not mean to be
inaccessible from outside the class, but to be guaranteed not to conflict
with other private members of the same object). These private members are
started with triple underscores and are stored in a separate dictionary
named `__privs__`. Unlike `__dict__` that takes 'str' keys, `__privs__`
will be a double layer dictionary that takes 'type' keys in the first
level, and 'str' keys in the second level.

For example, assume that the user runs the following code:
```
class C:
def __init__(self, value):
self.___member = value

c = C("my value")
```

On the last line, Python's attribute setter creates a new entry in the
dictionary with key `C`, adds the value "my value" to a new entry with the
key 'member'.

The user can then retrieve `c.___member` by invoking the `__privs__`
dictionary:

```
print(c.__privs__[C]['member'])  # prints 'my value'
```

Note that, unlike class names, class objects are unique and there will not
be any conflicts. Python classes are hashable and can be dictionary keys.
Personally, I do not see any disadvantage of using __privs__ over name
mangling/double-underscores. While name mangling does not truly guarantee
conflict resolution, __privs__ does.

Please discuss the idea, let me know what you think about it, whether there
are possible disadvantages, and if you think it will be approved as a PEP.

Thanks,
Mehrzad Saremi

AI M.Sc. grad. from AUT
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: on writing a while loop for rolling two dice

2021-08-28 Thread Hope Rouselle
[email protected] (Stefan Ram) writes:

> Hope Rouselle  writes:
>>Wait, I'm surprised ``outcome'' is still a valid name at the
>>return-statement.  Wasn't it defined inside the while?  Shouldn't its
>>scope be restricted to the while block?  I had no idea.  I should learn
>>some Python.
>
>   In Python, local names can be introduced by an assignment
>   and have function scope. There is no block scope in Python.
>
>   Below, "name" /is/ a local name already, but is being 
>   used before being assigned to.
>
> def function():
> if False:
> name = 0
> return name
>
> function()
>
> # return name
> # UnboundLocalError: local variable 'name' referenced before assignment

I appreciated the example.  I had no idea.  (I had looked up the rules
and it was pretty simple to understand, but an example is always nice.)
Thank you so much.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: on writing a while loop for rolling two dice

2021-08-28 Thread Chris Angelico
On Sun, Aug 29, 2021 at 7:37 AM Hope Rouselle  wrote:
>
> How should I write this?  I'd like to roll two six-sided dice until I
> get the same number on both.  I'd like to get the number of times I
> tried.  Here's a primitive I'm using:
>
> --8<---cut here---start->8---
> >>> x, y = roll()
> >>> x
> 6
> >>> y
> 6 # lucky
>
> >>> x, y = roll()
> >>> x
> 4
> >>> y
> 1 # unlucky
> --8<---cut here---end--->8---
>
> Here's my solution:
>
> --8<---cut here---start->8---
> def how_many_times():
>   x, y = 0, 1
>   c = 0
>   while x != y:
> c = c + 1
> x, y = roll()
>   return c, (x, y)
> --8<---cut here---end--->8---
>
> Why am I unhappy?  I'm wish I could confine x, y to the while loop.  The
> introduction of ``x, y = 0, 1'' must feel like a trick to a novice.  How
> would you write this?  Thank you!

Your loop, fundamentally, is just counting. So let's just count.

def how_many_times():
for c in itertools.count():
...

Inside that loop, you can do whatever you like, including returning
immediately if you have what you want. I'll let you figure out the
details. :)

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


Re: on writing a while loop for rolling two dice

2021-08-28 Thread Hope Rouselle
[email protected] (Stefan Ram) writes:

> Hope Rouselle  writes:
>>How would you write this?
>
> """Rolls two dice until both yield the same value.
> Returns the number of times the two dice were rolled
> and the final value yielded."""
> roll_count = 0
> while True:
> outcome = roll_two_dice()
> roll_count += 1
> if outcome[ 0 ]== outcome[ 1 ]: break
> return roll_count, outcome[ 0 ]

You totally convinced me.  Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: on the popularity of loops while and for

2021-08-28 Thread Chris Angelico
On Sun, Aug 29, 2021 at 7:40 AM Hope Rouselle  wrote:
>
> I'd like get a statistic of how often each loop is used in practice.
>
> I was trying to take a look at the Python's standard libraries --- those
> included in a standard installation of Python 3.9.6, say --- to see
> which loops are more often used among while and for loops.  Of course,
> since English use the preposition ``for'' a lot, that makes my life
> harder.  Removing comments is easy, but removing strings is harder.  So
> I don't know yet what I'll do.
>
> Have you guys ever measured something like that in a casual or serious
> way?  I'd love to know.  Thank you!

For analysis like this, I recommend using the Abstract Syntax Tree:

https://docs.python.org/3/library/ast.html

You can take a Python source file, parse it to the AST, and then walk
that tree to see what it's using. That will avoid any false positives
from the word "for" coming up in the wrong places.

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


Re: on writing a while loop for rolling two dice

2021-08-28 Thread Hope Rouselle
Hope Rouselle  writes:

> [email protected] (Stefan Ram) writes:
>
>> Hope Rouselle  writes:
>>>How would you write this?
>>
>> """Rolls two dice until both yield the same value.
>> Returns the number of times the two dice were rolled
>> and the final value yielded."""
>> roll_count = 0
>> while True:
>> outcome = roll_two_dice()
>> roll_count += 1
>> if outcome[ 0 ]== outcome[ 1 ]: break
>> return roll_count, outcome[ 0 ]
>
> You totally convinced me.  Thanks.

Wait, I'm surprised ``outcome'' is still a valid name at the
return-statement.  Wasn't it defined inside the while?  Shouldn't its
scope be restricted to the while block?  I had no idea.  I should learn
some Python.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: on the popularity of loops while and for

2021-08-28 Thread Hope Rouselle
[email protected] (Stefan Ram) writes:

> Hope Rouselle  writes:
>>Have you guys ever measured something like that in a casual or serious
>
> import ast
> import pathlib
> rootname=r''
> rootpath=pathlib.Path(rootname)
> rootiterable=rootpath.glob('**/*.py')
> first = True
> WhileCount = 0
> ForCount = 0
> for filepath in rootiterable:
> try:
> with filepath.open(encoding="utf-8") as file:
> source=file.read()
> parse=ast.parse(source, filename=str(file))
> for entry in ast.walk(parse):
> if isinstance(entry, ast.While):
> WhileCount+=1
> print( f"{ForCount=}, {WhileCount=}" )
> elif isinstance(entry, ast.For):
> ForCount+=1
> print( f"{ForCount=}, {WhileCount=}" )
> except SyntaxError as inst:
>if first:
>print( f"{sys.exc_info()[ 0 ] =}" )
>print( f"{type( inst ) =}" )
>print( f"{inst.args =}" )
>print( f"{inst =}" )
>print( f"skipping {filepath}." )
> first=False

You are so wonderful!  Thanks quite a lot.  Here's what I got:

  ForCount=18703, WhileCount=2505

I have pretty much just the standard libraries and a couple more ---
sympy and some xlsxwriter library.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PEP Idea: Real private attribute

2021-08-28 Thread Chris Angelico
On Sun, Aug 29, 2021 at 7:40 AM Mehrzad Saremi  wrote:
>
> Python currently uses name mangling for double-underscore attributes. Name
> mangling is not an ideal method to avoid name conflicting. There are
> various normal programming patterns that can simply cause name conflicting
> in double-underscore members. A typical example is when a class is
> re-decorated using the same decorator. The decorator can not take
> double-underscore members without name conflicts. For example:
>
> ```
> @custom_decorator("a")
> @custom_decorator("b")
> class C:
> pass
> ```
>
> The `@custom_decorator` wrapper may need to hold private members, but
> Python's current name conflict resolution does not provide any solution and
> the decorator cannot hold private members without applying tricky
> programming methods.
>
> Another example is when a class inherits from a base class of the same name.
>
> ```
> class View:
> """A class representing a view of an object; similar to
> numpy.ndarray.view"""
> pass
>
> class Object:
> class View(View):
> """A view class costumized for objects of type Object"""
> pass
> ```
>
> Again, in this example, class `Object.View` can't take double-underscore
> names without conflicting with `View`'s.
>
> My idea is to introduce real private members (by which I do not mean to be
> inaccessible from outside the class, but to be guaranteed not to conflict
> with other private members of the same object). These private members are
> started with triple underscores and are stored in a separate dictionary
> named `__privs__`. Unlike `__dict__` that takes 'str' keys, `__privs__`
> will be a double layer dictionary that takes 'type' keys in the first
> level, and 'str' keys in the second level.
>
> For example, assume that the user runs the following code:
> ```
> class C:
> def __init__(self, value):
> self.___member = value
>
> c = C("my value")
> ```
>
> On the last line, Python's attribute setter creates a new entry in the
> dictionary with key `C`, adds the value "my value" to a new entry with the
> key 'member'.
>
> The user can then retrieve `c.___member` by invoking the `__privs__`
> dictionary:
>
> ```
> print(c.__privs__[C]['member'])  # prints 'my value'
> ```
>
> Note that, unlike class names, class objects are unique and there will not
> be any conflicts. Python classes are hashable and can be dictionary keys.
> Personally, I do not see any disadvantage of using __privs__ over name
> mangling/double-underscores. While name mangling does not truly guarantee
> conflict resolution, __privs__ does.

Not entirely sure how it would know the right type to use (subclassing
makes that tricky), but whatever your definition is, there's nothing
stopping you from doing it yourself. Don't forget that you have
__class__ available if you need to refer to "the class that I'm
lexically inside" (that's how the zero-arg super() function works), so
you might do something like self.__privs__[__class__, "foo"] to refer
to a thing.

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


Re: on the popularity of loops while and for

2021-08-28 Thread Stestagg
If you're doing this analysis, I'd be pretty interested in how many of
those while loops where 'while True:'

I'd wager 75%. But may be completely off

Steve


On Sat, 28 Aug 2021 at 23:03, Hope Rouselle  wrote:

> [email protected] (Stefan Ram) writes:
>
> > Hope Rouselle  writes:
> >>Have you guys ever measured something like that in a casual or serious
> >
> > import ast
> > import pathlib
> > rootname=r''
> > rootpath=pathlib.Path(rootname)
> > rootiterable=rootpath.glob('**/*.py')
> > first = True
> > WhileCount = 0
> > ForCount = 0
> > for filepath in rootiterable:
> > try:
> > with filepath.open(encoding="utf-8") as file:
> > source=file.read()
> > parse=ast.parse(source, filename=str(file))
> > for entry in ast.walk(parse):
> > if isinstance(entry, ast.While):
> > WhileCount+=1
> > print( f"{ForCount=}, {WhileCount=}" )
> > elif isinstance(entry, ast.For):
> > ForCount+=1
> > print( f"{ForCount=}, {WhileCount=}" )
> > except SyntaxError as inst:
> >if first:
> >print( f"{sys.exc_info()[ 0 ] =}" )
> >print( f"{type( inst ) =}" )
> >print( f"{inst.args =}" )
> >print( f"{inst =}" )
> >print( f"skipping {filepath}." )
> > first=False
>
> You are so wonderful!  Thanks quite a lot.  Here's what I got:
>
>   ForCount=18703, WhileCount=2505
>
> I have pretty much just the standard libraries and a couple more ---
> sympy and some xlsxwriter library.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: on writing a while loop for rolling two dice

2021-08-28 Thread dn via Python-list
On 29/08/2021 08.46, Hope Rouselle wrote:
> Here's my solution:
> 
> --8<---cut here---start->8---
> def how_many_times():
>   x, y = 0, 1
>   c = 0
>   while x != y:
> c = c + 1
> x, y = roll()
>   return c, (x, y)

> 
> Why am I unhappy?  I'm wish I could confine x, y to the while loop.  The
> introduction of ``x, y = 0, 1'' must feel like a trick to a novice.  How
> would you write this?



> [email protected] (Stefan Ram) writes:
>> """Rolls two dice until both yield the same value.
>> Returns the number of times the two dice were rolled
>> and the final value yielded."""
>> roll_count = 0
>> while True:
>> outcome = roll_two_dice()
>> roll_count += 1
>> if outcome[ 0 ]== outcome[ 1 ]: break
>> return roll_count, outcome[ 0 ]
> 
> You totally convinced me.  Thanks.


On the other hand...
whilst you expressed concern about the apparently disconnected 'set up'
necessary before the loop, this solution adds a "True/Forever" and a
"Break" construct, which some may deem not that much better (if at all)

The idea of abrogating the while-condition but then adding another
(disconnected) condition to break, seems to hold equal potential for
confusion. or the type of dissatisfaction which motivated the original
question!

Looking at that from the inside-out, the loop's contents perform two
functions: the rolling and counting (per Statement of Requirements), but
also a loop-controlling element. Thus the reader's question: "what does
this loop do?" is conflated with "how many times does it do it?".


Let's go completely off-the-rails, why not use a never-ending range() to
fuel a for-loop 'counter', and within that loop perform the dice-roll(s)
and decide if it is time to 'break'. The range replaces the "True". The
for-loops index or 'counter' will deliver the desired result.

Neat? No!
Readable? No!
An improvement over the while-True? Definitely not!
Yet, the mechanism is the same AND offers a built-in counter. Hmmm...


Returning to the concern:

x, y = 0, 1
c = 0

The first line is purely to ensure that the loop executes at least once,
ie the two assigned-values are not 'real'. Hence the disquiet!

Initiating the counter is unavoidable (@Chris' suggestion notwithstanding).

However, remember that Python (like decent DBs) has a concept (and an
idiom) of a value to be used when we don't (yet) know what the value
is/should be! Further that Python allows such a value to be used in
comparisons:

>>> None != None
False
>>> None == None
True

Leading to:

c, x, y = 0, None, None
while ...


Which solution reverts to the original loop-contents. which seem more
obvious and thus more readable. (YMMV!)

Simplicity over 'being clever'...
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: on the popularity of loops while and for

2021-08-28 Thread Terry Reedy

On 8/28/2021 9:31 AM, Hope Rouselle wrote:

I'd like get a statistic of how often each loop is used in practice.


My guess is that for loops are at least twice as common as while loops.


I was trying to take a look at the Python's standard libraries --- those
included in a standard installation of Python 3.9.6, say --- to see
which loops are more often used among while and for loops.  Of course,
since English use the preposition ``for'' a lot, that makes my life
harder.  Removing comments is easy, but removing strings is harder.  So
I don't know yet what I'll do.


Try something like

fors = 0
for file in files:
for line in file:
if re.match(r"/s*for .* in ", line):
fors += 1

This excludes comprehensions, which have replaced some for loops.

--
Terry Jan Reedy

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


Re: on writing a while loop for rolling two dice

2021-08-28 Thread Terry Reedy

On 8/28/2021 8:00 AM, Hope Rouselle wrote:

How should I write this?  I'd like to roll two six-sided dice until I
get the same number on both.  I'd like to get the number of times I
tried.  Here's a primitive I'm using:

--8<---cut here---start->8---

x, y = roll()
x

6

y

6 # lucky


x, y = roll()
x

4

y

1 # unlucky
--8<---cut here---end--->8---

Here's my solution:

--8<---cut here---start->8---
def how_many_times():
   x, y = 0, 1
   c = 0
   while x != y:
 c = c + 1
 x, y = roll()
   return c, (x, y)
--8<---cut here---end--->8---

Why am I unhappy?  I'm wish I could confine x, y to the while loop.  The
introduction of ``x, y = 0, 1'' must feel like a trick to a novice.  How
would you write this?  Thank you!


Something like (untested)

c = 0
while True:
c += 1
x, y = roll()
if x == y:
return c, (x,y)

or even better to me, as it will not loop forever if you mess up the 
condition


for i in range(1, 100):
x, y = roll()
if x == y:
return i, (x,y)
# return "The universe ends as the essentially impossible happened"


--
Terry Jan Reedy

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


Re: on writing a while loop for rolling two dice

2021-08-28 Thread Alan Gauld via Python-list
On 28/08/2021 21:50, Hope Rouselle wrote:

>>> roll_count = 0
>>> while True:
>>> outcome = roll_two_dice()
>>> roll_count += 1
>>> if outcome[ 0 ]== outcome[ 1 ]: break
>>> return roll_count, outcome[ 0 ]
>>
> 
> Wait, I'm surprised ``outcome'' is still a valid name at the
> return-statement.  Wasn't it defined inside the while?  

If that really bugs you just replace the break with the return.


>>> if outcome[ 0 ]== outcome[ 1 ]:
>>>return roll_count, outcome[ 0 ]

Now its all inside the loop.

But remember readable code is better than  cute code every time.
And personally I'd just declare the x,y up front. Easier to
understand and debug IMHO.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: on the popularity of loops while and for

2021-08-28 Thread Stestagg
On Sun, 29 Aug 2021 at 00:04, Stefan Ram  wrote:

> Stestagg  writes:
> >If you're doing this analysis, I'd be pretty interested in how many of
> >those while loops where 'while True:'
>
>   Here, about 40 %.



Thanks!  That's an interesting stat.  I might have to look more into how
while loops are actually used in other people's code.


>
>   Below is a new version that is supposed to also count "if True:"
>   and "if 1:" and also removes a bug with the exception handling
>   (missing "import sys" and missing "UnicodeDecodeError"). I'm not
>   experienced in using the AST module, so there might still be bugs
>   in the program!
>
> import ast
> import pathlib
> import sys
> rootname=r'''PATH TO SOURCE DIR (WITHOUT A BACKQUOTE AT THE END)'''
> rootpath=pathlib.Path(rootname)
> rootiterable=rootpath.glob('**/*.py')
> WhileCount = 0
> TrueCount = 0
> ForCount = 0
> for filepath in rootiterable:
> try:
> with filepath.open(encoding="utf-8") as file:
> source=file.read()
> parse=ast.parse(source, filename=str(file))
> for entry in ast.walk(parse):
> if isinstance(entry, ast.While):
> WhileCount+=1
> if ( isinstance( entry.test, ast.Constant ) and
>   hasattr( entry.test, "value") and
>   ( isinstance( entry.test.value, bool )
> and entry.test.value == True or
> isinstance( entry.test.value, int )
> and entry.test.value != 0 )):
> TrueCount+=1
> print( f"{ForCount=}, {WhileCount=}, {TrueCount=}" )
> elif isinstance(entry, ast.For):
> ForCount+=1
> print( f"{ForCount=}, {WhileCount=}" )
> except ( SyntaxError, UnicodeDecodeError )as inst:
>print( f"skipping {filepath}." )
>print( f"{sys.exc_info()[ 0 ] =}" )
>print( f"{type( inst ) =}" )
>print( f"{inst.args =}" )
>print( f"{inst =}\n" )
> print( f"{ForCount=}, {WhileCount=}, {TrueCount=}" )
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: matplotlib questions

2021-08-28 Thread MRAB

On 2021-08-28 04:39, Steve wrote:

I would like to know how the data is placed on the Y-axis and at the tops of
the bars.
The data is not being shown properly.  With some exceptions, it looks as if
the data is getting sorted independently from the dates.


OK, here is the code:
==
# https://matplotlib.org/stable/gallery/index.html
import matplotlib.pyplot as plt
import numpy as np

width = 12 #Width of the graph
height = 6  #Height of the graph

plt.rcParams["figure.figsize"] = (width,height)
plt.rcParams["font.size"] = (9.0)


Count = 0
datesList = []   # Each date showing end of bottle use
hoursList = []   # Number of hours
# daysList = []  # Number of days calculated from hours/24
countList = []   # simple tally

with open("__Insulin_Tracker.txt", 'r') as infile:
 for lineEQN in infile:
   insulinHours = lineEQN[47:52].strip()
   print("Hours = " + insulinHours)
   hoursList.append(insulinHours)
   
   insulinDates = lineEQN[20:30].strip()

   datesList.append(insulinDates)
   
   #insulinDays= lineEQN[57:62].strip()

   #daysList.append(insulinDays)
   
   Count += 1

   countList.append(str(Count))
  # print("" + str(Count) + "  " + insulinDates + " Hours: " +
insulinHours)
x = Count
count = str(Count)

# Each date indicated the date on which a bottle of insulin has been
depleted
# The bar is to show the number of hours that the bottle has been in use.

Labels = datesList
Xdata= hoursList

Title = ("Bottle List   Number of entries: " + count)
x = np.arange(len(Labels))  # the label locations

width = 0.35  # the width of the bars
margin = 0

fig, ax = plt.subplots()
fig.tight_layout(pad=10) # Sets the size of the graph

rects1 = ax.bar(x - width/2, Xdata, width, label='Hours') #Populates the x
axis

# Add some text for labels, title and custom x-axis tick labels, etc.
# fontsize = 20

ax.set_ylabel('Hours of use for each bottle')
ax.set_title(Title)
ax.set_xticks(x)
ax.set_xticklabels((datesList), rotation = 90) #Dates at bottom of the graph
ax.legend()
ax.bar_label(rects1, padding=0,rotation = 90)

plt.show()


[snip]

You're passing ax.bar the contents of Xdata.

What does Xdata contain?

A list of _strings_.

If you want the length of the bars to represent the number of hours, 
then they should be numbers.

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


RE: on writing a while loop for rolling two dice

2021-08-28 Thread Avi Gross via Python-list
And there is the ever popular recursive version you call with no while loop
in sight. And, oddly, no variable declared in your main body:

# CODE START ---
import random

def roll2():
return random.randint(1,6), random.randint(1,6)

def roll_equal(counter):
first, second = roll2()
encountered = counter + 1
if (first == second):
return(encountered)
else:
return(roll_equal(encountered))

#--- CODE END ---

Since the result is usually a single digit of iterations, no biggie. Here is
some output:

>>> roll_equal(0)
6
>>> roll_equal(0)
7
>>> roll_equal(0)
1
>>> roll_equal(0)
7
>>> roll_equal(0)
6
>>> [ roll_equal(0) for n in range(10)]
[3, 4, 2, 5, 8, 1, 1, 2, 3, 9]
>>> [ roll_equal(0) for n in range(10)]
[3, 3, 7, 19, 7, 2, 1, 3, 8, 4]
>>> [ roll_equal(0) for n in range(10)]
[1, 3, 1, 13, 11, 4, 3, 5, 2, 4]

And the code can be a tad shorter, LOL!

But obviously then you have more overhead than an iterative solution or one
using a generator ...

-Original Message-
From: Python-list  On
Behalf Of Alan Gauld via Python-list
Sent: Saturday, August 28, 2021 6:52 PM
To: [email protected]
Subject: Re: on writing a while loop for rolling two dice

On 28/08/2021 21:50, Hope Rouselle wrote:

>>> roll_count = 0
>>> while True:
>>> outcome = roll_two_dice()
>>> roll_count += 1
>>> if outcome[ 0 ]== outcome[ 1 ]: break return roll_count, 
>>> outcome[ 0 ]
>>
> 
> Wait, I'm surprised ``outcome'' is still a valid name at the 
> return-statement.  Wasn't it defined inside the while?

If that really bugs you just replace the break with the return.


>>> if outcome[ 0 ]== outcome[ 1 ]:
>>>return roll_count, outcome[ 0 ]

Now its all inside the loop.

But remember readable code is better than  cute code every time.
And personally I'd just declare the x,y up front. Easier to understand and
debug IMHO.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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

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