On 29/08/2021 12:13, dn via Python-list wrote:
On 29/08/2021 20.06, Peter Otten wrote:
...
OK, maybe a bit complicated... but does it pay off if you want to
generalize?

def roll_die(faces):
     while True: yield random.randrange(1, 1 + faces)

def hmt(faces, dies):
     for c, d in enumerate(zip(*[roll_die(faces)]*dies), 1):
         if len(set(d)) == 1: return c, d


Curiosity:
why not add dies as a parameter of roll_die()?

Dunno. Maybe because I've "always" [1] wanted a version of random.randrange() that generates values indefinitely. It would need to check its arguments only once, thus leading to some extra

Efficiency:
- wonder how max( d ) == min( d ) compares for speed with the set() type
constructor?

I did the simplest thing, speed was not a consideration. If it is, and dies (sorry for that) is large I'd try

first = d[0]
all(x == first for x in d)  # don't mind one duplicate test

For smaller numbers of dice I'd unpack (first, *rest) inside the for loop. But it's a trade-off, you' have to measure if/when it's better to go through the whole tuple in C.


- alternately len( d ) < 2?
- or len( d ) - 1 coerced to a boolean by the if?
- how much more efficient is any of this (clever thinking!) than the
OP's basic, simpler, and thus more readable, form?

It really isn't efficiency, it's a (misled?) sense of aesthetics where I've come to prefer

- for-loops over while, even when I end up with both to get the desired for

- enumerate() over an explicit counter even though there is the extra unpack, and you still need to initialize the counter in the general case:

for i, item in enumerate([]): pass
print(f"There are {i+1} items in the list.")  # Oops

English language 'treachery':
- one die
- multiple dice

You might have inferred that I knew (or had looked up) the singular of dice, so this is but a momentary lapse of reason. It hurts me more than you, trust me. Not as much, as going on record with confusing they're and their, but still ;)

(probably not followed in US-English (can't recall), particularly on
computers running the Hollywood Operating System).

I've come to the conclusion that International English is hopelessly and inevitably broken. That's the price native speakers have to pay for having they're (oops, I did it again!) language used as lingua franca.

Continuous Education:
Thanks for the reminder that enumerate() can be seeded with a "start" value!

[1] I think I've suggested reimplementing the whole module in terms of generators -- can't find the post though.

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

Reply via email to