Re: How do Fractions convert to int?

2018-03-13 Thread Robin Koch

Am 13.03.2018 um 12:16 schrieb Steven D'Aprano:


How do Fractions convert to ints when they have no __int__ method?


It uses __trunc__:

| In general, the int() conversion should try __int__() first and if
| it is not found, try 
__trunc__().[https://www.python.org/dev/peps/pep-3141/]


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


Re: Appending data to a json file

2017-04-04 Thread Robin Koch

Am 04.04.2017 um 04:59 schrieb Dave:

I created a python program that gets data from a user, stores the data
as a dictionary in a list of dictionaries.  When the program quits, it
saves the data file.  My desire is to append the new data to the
existing data file as is done with purely text files.  However, I can't
find a way to do that.  The advice I have seen on the web is to load the
data when the program starts, append the new user input to the list,
then re-write the data file.  Is that the best way, or is there a better
way?


As explained by others JSON does not allow text based data appending.

But maybe you take a look at YAML (if it's appropriate for your project).

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


Re: How to sort this without 'cmp=' in python 3?

2016-10-14 Thread Robin Koch

Am 15.10.2016 um 01:33 schrieb 38016226...@gmail.com:

nums=['3','30','34','32','9','5']
I need to sort the list in order to get the largest number string: '953433230'

nums.sort(cmp=lambda a,b: cmp(a+b, b+a), reverse=True)

But how to do this in python 3?


https://docs.python.org/3/library/functools.html#functools.cmp_to_key

| Transform an old-style comparison function to a key function.

--
Robin Koch



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


Re: cropping a random part of an image

2016-08-09 Thread Robin Koch

Am 09.08.2016 um 14:40 schrieb drewes@gmail.com:


I'm new to python and I have 30.000 pictures.
I need to crop, let's say 100, parts of 256x256, randomly out of every picture.


Interessting task. May I ask for the purose of this?


I cant find an answer in the net, would be nice if someone could help me out!


Although I think you should follow Peters advise I have put something 
together, out of curiousity, that should do the trick.


There are several ways to improve it.
First I'm using os.listdir() instead of os.walk().
In my example scenario that's ok. If your files are spread over 
different subfolders, os.walk() is the better way to do it.


You could add a counter (see: enumerate()) to have a better overview 
over the progress.


Also you might have other preferences for the location of the tiles. 
(e.g. one folder per image).


# Cuts random tiles from pictures
#
# This version works with approx. 270 tiles per second on my machine
# (on 13.5MPx images). So 3 million tiles should take about 3 hours.

import random, os, time
from PIL import Image

INPATH = r".../images"
OUTPATH = r".../tiles"

dx = dy = 256
tilesPerImage = 100

files = os.listdir(INPATH)
numOfImages = len(files)

t = time.time()
for file in files:
  with Image.open(os.path.join(INPATH, file)) as im:
for i in range(1, tilesPerImage+1):
  newname = file.replace('.', '_{:03d}.'.format(i))
  w, h = im.size
  x = random.randint(0, w-dx-1)
  y = random.randint(0, h-dy-1)
  print("Cropping {}: {},{} -> {},{}".format(file, x,y, x+dx, y+dy))
  im.crop((x,y, x+dx, y+dy))\
.save(os.path.join(OUTPATH, newname))

t = time.time()-t
print("Done {} images in {:.2f}s".format(numOfImages, t))
print("({:.1f} images per second)".format(numOfImages/t))
print("({:.1f} tiles per second)".format(tilesPerImage*numOfImages/t))



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


Re: Python PygLatin

2016-05-09 Thread Robin Koch

Am 08.05.2016 um 12:21 schrieb Cai Gengyang:

> If one looks at the Forbes List, you will see that there are 4
> programmers amongst the top ten richest people in the world (Bill
> Gates, Mark Zuckerberg, Larry Ellison and Jeff Bezos) , a very large
> percentage.

You might elaborate your knowledge about conditional probability as well.

P("X is programmer" | "X is in Forbes Top 10")

!=

P("X is in Forbes Top 10" | "X is programmer")

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


Re: Stop writing Python 4 incompatible code

2016-01-15 Thread Robin Koch

Am 14.01.2016 um 01:40 schrieb Bernardo Sulzbach:

On Wed, Jan 13, 2016 at 10:10 PM, Steven D'Aprano <st...@pearwood.info> wrote:

  (...) 4.0 (assuming there is one)


Isn't it just a matter of time? Do you think it is even possible not
to have Python 4 eventually?


Not necessarily.
See TeX. :-)

--
Robin Koch

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


Re: Is there a way importing a string object?

2016-01-05 Thread Robin Koch

Am 05.01.2016 um 03:24 schrieb jf...@ms4.hinet.net:


(Please make the body of your message complete. The "Subject"
field should be a summary of your message's subject, and may not be
read as the first line of your message.)


Yes, The "Subject" seems a little strange, read likes a part of the
body. I am bad on composition. Even after your reminder, I still
can't think of a better one:-(


I think the subject is fine.
But you should have extended your message body a little so your question 
is understandable without reading the subject.


--
Robin Koch

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


Re: Trailing zeros of 100!

2016-01-02 Thread Robin Koch

Am 02.01.2016 um 14:14 schrieb yehudak .:


Thank you so much, but...
All that is Chinese for me.
Can you show a 'normal' Python code for me?


How about:

 >>> from math import log
 >>> sum([int(0.2**k*n) for k in range(1, int(log(n, 5))+1)])

}:-)

(That implements my procedure in my other answer.)

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


Re: Trailing zeros of 100!

2016-01-02 Thread Robin Koch

Am 02.01.2016 um 17:09 schrieb Tony van der Hoff:

On 02/01/16 16:57, Robin Koch wrote:

sum([int(0.2**k*n) for k in range(1, int(log(n, 5))+1)])


But did you actually test it?


Yes, should work for n >= 1.

Why do you ask?

--
Robin Koch


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


Re: Trailing zeros of 100!

2016-01-02 Thread Robin Koch

Am 02.01.2016 um 12:49 schrieb katye2...@gmail.com:


I'm trying to write a python program to find how many trailing zeros
are in 100! (factorial of 100). I used factorial from the math
module, but my efforts to continue failed. Please help.


Using not Python, but math:

Every "0" at the end of 100! represents a multiplication by the factor 
10 or the factors 2 and 5.


There are 20 numbers with at least one factor 5.
There are  4 numbers with at least two factors 5 (=25).
There are no numbers with three factors 5 (=125).

There are 50 numbers with at least one factor 2.

So 100! contains 24 factors 5 and even more factors 2.
So 100! contains 24 facotrs 10 and therefore has 24 trailing zeros.

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


Re: Trailing zeros of 100!

2016-01-02 Thread Robin Koch

Am 02.01.2016 um 22:57 schrieb Chris Angelico:

On Sun, Jan 3, 2016 at 3:56 AM, Robin Koch <robin.k...@t-online.de> wrote:

Am 02.01.2016 um 17:09 schrieb Tony van der Hoff:


On 02/01/16 16:57, Robin Koch wrote:


sum([int(0.2**k*n) for k in range(1, int(log(n, 5))+1)])



But did you actually test it?



Yes, should work for n >= 1.

Why do you ask?


Your "should work" does not sound good as a response to "actually
test". Normally I would expect the response to be "Yes, and it worked
for me" (maybe with a log of an interactive session).


Well, honestly, I trusted my math and didn't thought much about the 
technical limitations.


I only tried values from 1 to 100 and then again 12345, I believe, to 
test the algorithm.


> Floating point

can't represent every integer, and above 2**53 you end up able to
represent only those which are multiples of ever-increasing powers of
two; 100! is between 2**524 and 2**525, so any float operations are
going to be rounding off to the nearest 2**471 or thereabouts.
That's... a lot of rounding. That's like trying to calculate whether
pi is rational, but basing your calculations on the approximation
3.14. :)


When I find more time I take a closer look at it. Thank you (and 
Bernardo) for your clarification. I hope everyone who read my article 
reads yours, too and learns from it. ;-)


--
Robin Koch

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


Re: geostationary satellite data

2015-12-16 Thread Robin Koch

Am 16.12.2015 um 18:30 schrieb Peter Pearson:

On Thu, 17 Dec 2015 04:08:02 +1100, Chris Angelico <ros...@gmail.com> wrote:

>>

It could be 16 bits per pixel. Without knowing a lot more about the
source of the image and its format, it's hard to say with any
certainty.


Agreed.  It's annoying when an agency goes to the trouble of making
huge datasets available online, but fails to identify the format.


http://www.cpc.ncep.noaa.gov/products/global_precip/html/README

says (among other things):

| Each record is a 9896 x 3298 Fortran array of IR brightness
| temperatures that have been scaled to fit into 1-byte by subtracting
| "75" from each datum. Therefore it is necessary for the user to add a
| value of "75" to each data value when using the data.

HTH a little,

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


Re: Python variable assigning problems...

2015-12-11 Thread Robin Koch

Am 11.12.2015 um 17:10 schrieb ICT Ezy:

Dear All,
Very Sorry for the my mistake here. I code here with mu question ...

My Question:

A,B=C,D=10,11
print(A,B,C,D)
#(10,11,10,11) --> This is OK!

a=1; b=2
a,b=b,a
print(a,b)
# (1,2) --> This is OK!

x,y=y,x=2,3
print(x,y)
# (3,2) --> Question: How to explain it?
# Not understand this process. Pl explain ...


What else would you expect?

Assigning goes from right to left:

x,y=y,x=2,3

<=>

y, x = 2, 3
x, y = y, x

Otherwise the assignment x, y = y, x would not make any sense, since x 
and y haven't any values yet.


And the execution from right to left is also a good choice, because one 
would like to do something like:


x = y = z = 0

Again, assigning from left to right woud lead to errors.

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


Re: Python variable assigning problems...

2015-12-11 Thread Robin Koch

Am 11.12.2015 um 17:39 schrieb Ian Kelly:

On Fri, Dec 11, 2015 at 9:24 AM, Robin Koch <robin.k...@t-online.de> wrote:

Assigning goes from right to left:

x,y=y,x=2,3

<=>

y, x = 2, 3
x, y = y, x

Otherwise the assignment x, y = y, x would not make any sense, since x and y
haven't any values yet.

And the execution from right to left is also a good choice, because one
would like to do something like:

x = y = z = 0

Again, assigning from left to right woud lead to errors.


No, it actually happens left to right. "x = y = z = 0" means "assign 0
to x, then assign 0 to y, then assign 0 to z." It doesn't mean "assign
0 to z, then assign z to y, etc."


Oh. Ok, then, thanks for this correction.
Although it's consequent to use left-to-right precedence it's a little 
counter intuitive in the sense that the rightmost and leftmost objects 
interact. Especially with a background in mathematics. :-)


> This works:



d = d['foo'] = {}
d

{'foo': {...}}

This doesn't:


del d
d['foo'] = d = {}

Traceback (most recent call last):
   File "", line 1, in 
NameError: name 'd' is not defined


Good to know! Thank you.

--
Robin Koch

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


Re: Help on for loop understanding

2015-12-07 Thread Robin Koch

Am 08.12.2015 um 02:05 schrieb Robert:

Hi,
When I learn for loop with below link:

http://www.shutupandship.com/2012/01/understanding-python-iterables-and.html

it has such explanation:

\
for loop under the hood

First let's look at the for loop under the hood. When Python executes the
  for loop, it first invokes the __iter__() method of the container to get the
  iterator of the container. It then repeatedly calls the next() method
  (__next__() method in Python 3.x) of the iterator until the iterator raises a
  StopIteration exception. Once the exception is raised, the for loop ends.
\

When I follow a list example from the above link, and one example of myself:

//
xx=[1,2,3,4,5]

xx.next
---
AttributeErrorTraceback (most recent call last)
 in ()
> 1 xx.next

AttributeError: 'list' object has no attribute 'next'

xx.__iter__
Out[77]: 

for c in xx: print c
1
2
3
4
5
//

I am puzzled that the list examples have no next method, but it can run as
a for loop. Could you explain it to me the difference?


Lists don't have a next method. Their iterators have:

xx.__iter__().__next__()

or

xxIterator = xx.__iter__()
xxIterator.__next__()
xxIterator.__next__()
xxIterator.__next__()
xxIterator.__next__()
xxIterator.__next__()

That's also what your quoted paragraph states:

| It then repeatedly calls the next() method
| (__next__() method in Python 3.x) of the iterator

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


Re: increment/decrement operators

2015-12-05 Thread Robin Koch

Am 05.12.2015 um 13:40 schrieb Tony van der Hoff:

Hi,

I'm a relative newbie to python, and this NG, but it's certainly growing
on me.

One thing I'm missing is the increment/decrement operator from C, ie
x++, and its ilk. Likewise x += y.

is there any way of doing this in Python?


Quick answer:

x += y works. (Well, it should.)

x++ doesn't.

Long answer:

I'm sure someone more experienced will come up with one shortly. :-)

Until then I found this:
http://stackoverflow.com/a/1485854

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


Re: 'string.join' is wrong in my Python console

2015-12-03 Thread Robin Koch

Am 03.12.2015 um 17:25 schrieb Ian Kelly:

On Thu, Dec 3, 2015 at 9:00 AM, Robin Koch <robin.k...@t-online.de> wrote:

Now *I* am confused.

Shouldn't it be

", ".join(['1', '2', '4', '8', '16'])

instead? Without any importing?


That would be the normal way to write it. The FAQ entry is suggesting
the string module function as an alternative for those who can't
accept it as a string method.


Whoops.
Thanks and sorry. :-)

--
Robin Koch

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


Re: 'string.join' is wrong in my Python console

2015-12-03 Thread Robin Koch

Am 03.12.2015 um 10:02 schrieb Gary Herron:

On 12/02/2015 10:55 PM, Robert wrote:

Hi,

I read the tutorial on "Why is join() a string method instead of a list
  or tuple method?"
at link:
https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls


I have a problem on running the last line:
---
If none of these arguments persuade you, then for the moment you can
  continue to use the join() function from the string module, which
allows
  you to write

string.join(['1', '2', '4', '8', '16'], ", ")
---

My Python console is 2.7. It should be no problem because I see the
tutorial
is 2.7 too.

The console has these display:

string.join(['1', '2', '4', '8', '16'], ", ")
---

NameError Traceback (most recent call
last)
 in ()
> 1 string.join(['1', '2', '4', '8', '16'], ", ")

NameError: name 'string' is not defined


 From the context, I don't see string should be replaced by something
else.

Could you tell me why I have such an error?


You are trying to use the *string* module without importing it, I'd guess.

Try:
 import string
first then you should be able to access string.join without error.


Now *I* am confused.

Shouldn't it be

", ".join(['1', '2', '4', '8', '16'])

instead? Without any importing?

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


Re: 'string.join' is wrong in my Python console

2015-12-03 Thread Robin Koch

Am 03.12.2015 um 18:23 schrieb Terry Reedy:

On 12/3/2015 11:00 AM, Robin Koch wrote:

Am 03.12.2015 um 10:02 schrieb Gary Herron:

On 12/02/2015 10:55 PM, Robert wrote:

Hi,

I read the tutorial on "Why is join() a string method instead of a list
  or tuple method?"
at link:
https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls




I have a problem on running the last line:
---
If none of these arguments persuade you, then for the moment you can
  continue to use the join() function from the string module, which
allows
  you to write

string.join(['1', '2', '4', '8', '16'], ", ")
---

...

You are trying to use the *string* module without importing it, I'd
guess.

Try:
 import string
first then you should be able to access string.join without error.


Now *I* am confused.

Shouldn't it be

", ".join(['1', '2', '4', '8', '16'])

instead? Without any importing?


Yes, that is what one *should* do in late 2.x and indeed must do in 3.x,
where the string module has been stripped of the functions that later
became string methods.  The FAQ entry was written when the join method
was new as a method and some people were upset by the reversal of the
order of the two arguments, an iterable of strings and the joining string.


Thank you.
I figured that out by now. :-)

I just didn't followed the link of the OP.

--
Robin Koch

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


Re: 'string.join' is wrong in my Python console

2015-12-03 Thread Robin Koch

Am 03.12.2015 um 18:42 schrieb Mark Lawrence:

On 03/12/2015 17:01, Robin Koch wrote:

Am 03.12.2015 um 17:25 schrieb Ian Kelly:

On Thu, Dec 3, 2015 at 9:00 AM, Robin Koch <robin.k...@t-online.de>
wrote:

Now *I* am confused.

Shouldn't it be

", ".join(['1', '2', '4', '8', '16'])

instead? Without any importing?


That would be the normal way to write it. The FAQ entry is suggesting
the string module function as an alternative for those who can't
accept it as a string method.


Whoops.
Thanks and sorry. :-)



You might like to note that here
https://docs.python.org/3/faq/design.html#why-is-join-a-string-method-instead-of-a-list-or-tuple-method
the reference to the string module function has been completely removed.


Actually I did. :-)
I tried the line with my Python 3.4 and it didn't work.
Then I sent my initial posting.

After Ians answer I took a look in the 2.x and the 3.x FAQs and found 
exactly that phrase removed. :-)


--
Robin Koch

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


Re: Regular expressions

2015-11-03 Thread Robin Koch

Am 03.11.2015 um 05:23 schrieb ru...@yahoo.com:


Of course there are people who misuse regexes.


/^1?$|^(11+?)\1+$/

There are? 0:-)

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


Re: GoPiGo script

2015-11-02 Thread Robin Koch

Am 02.11.2015 um 15:32 schrieb input/ldompel...@casema.nl:


Thank you for the explanation for it.
I must tell you that  i yust beginning with python.
I bought the book beginning programming with python.


Have you programming experience with other languages?

Well, the very first thing you should have learned is the basic syntax 
of Python. (That's how a program has to be written to work properly.)


And one of those first things is that python code is structured not by 
braces (like many other programming languages), but by intendation (as 
mentioned by others before).


That means that everything "depending" of a line somehow has to be 
intended deeper than that line.


Those lines are typically lines starting with "if", "for", "while", 
"def" or other keywords and end with a colon.


In your code the ifs and fors (and the following lines) are correctly 
intended. But you are using the "while" and "def" kind of wrong.


Let me give an example (note that the line numbers are only for this 
posting to prevent funny formating business and to talk about the single 
lines!):


01 for i in [1,2,3]:
02 print('A')
03 print('B')
04 print('C')

The first line (01) starts a loop. (Starting with a for, ending with a 
colon.) For every entry in the given list "something" is supposed to be 
repeated. But what is repeated and what isn't?


Easy: All following *intended* lines (02-03) are repeated.
Line 04 isn't intended and marks the point where the loop ends.

The output of the above is:

A
B
A
B
A
B
C


If we change the code just a tiny bit:

01 for i in [1,2,3]:
02 print('A')
03 print('B')
04 print('C')

(Notice, that the only change is the removed whitespace in line 03.)

only line 02 is repeated:

A
A
A
B
C


That works also for if and while:

01 if False:
02 print("This isn't printed.")
03 print("This neigther.")
03 print("But this is!")

01 c = 1
02 while c < 10:
03 print(c)
04 c = c*2
05 print("done")

prints

1
2
4
8
done


And of course those are mixable:

01 for a in [3,5,7]:
02b = 1
03while a*b < 10:
04  if a*b % 2 != 0:
05print(a*b)
06b = b+1
07print("Next a")
08 print("done")

prints:

3
9
Next a
5
Next a
7
Next a
done


And this is where your problems seems to be.

You start with

"while True:"

which does start an endless loop.

But: As explained it only repeats the lines theat follow and are intended!

In your original post the next line isn't intended at all, which is 
considered an error.
In your second attempt you intended only the first 5 lines. So those 
(and only those) are repeated.


The next line ("if mindist > us_dist(15):") wasn't intended and 
therefore *not* repeated.


If you just learning programming with Python you migth want to start 
with smaller examples to understand the syntax better.

Do you understand what the script is supposed to do in every line?

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


Re: GoPiGo script

2015-11-02 Thread Robin Koch

Am 02.11.2015 um 22:06 schrieb Larry Hudson:


[snip a lot of text, also using the word intend...]

The word you want is indent not intend.


Oops. Of course you are right.
You might have noticed, english isn't my native language.
Not an excuse, but an explanation. ;-)

I can only hope, that Loek does understand what I meant.


Intend means something entirely different,
and is not a Python term.


Yes, I know the difference. I just didn't pay enough attention to it.

Ironically enough I wrote actually another post about Android-intends 
earlier.


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


Re: Casting to a number (both int and float)?

2015-08-28 Thread Robin Koch

Am 28.08.2015 um 18:09 schrieb Sven R. Kunze:

 I'm reading JSON output from an input file, and extracting values.


for proper parsing into native Python types, I would recommend YAML.


What's the best way to get from A to B?
I recommend starting at C.

- Every other usenet-discussion.

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


Re: How to rearrange array using Python?

2015-07-30 Thread Robin Koch

Am 30.07.2015 um 22:31 schrieb Martin Schöön:


Scores to the right show how many wishes are fulfilled in each room


Is it possible the is a mistake in the sum column on the third row?
Should the be a 1?


The goal is to re-shuffle the array to maximize this score.

How do I go about doing that?


Depending on how you store those wishes I'd think you can use
random.shuffle()!?

But do you think simply maximising the score is the optimal solution to 
the problem?
That way some kids will get their both wishes fulfilled (s, e and p in 
your example), while other kids not even one (r, z, j, v, c, y, g, m, d).
Shouldn't be the goal to maximise the number of kinds which get at least 
one wished kid in the same room? (I hesitate writing friend, since you 
maybe wouldn't want to be picked by someone... Friend would be pairs of 
kids picking each other. Another thing one might want to takeinto 
account. :-))


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