Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > it.comp.lang.python > #7598
| From | Antonio Valentino <antonio.valentino@tiscali.it> |
|---|---|
| Newsgroups | it.comp.lang.python |
| Subject | Re: Contatore in funzione ricorsiva |
| Date | 2015-10-17 17:22 +0200 |
| Organization | Netfront http://www.netfront.net/ |
| Message-ID | <mvtp46$khq$1@adenine.netfront.net> (permalink) |
| References | <mvtcdh$csn$1@adenine.netfront.net> |
Ciao Francesco,
Il 17/10/2015 13:45, Francesco Di Matteo ha scritto:
> Ciao a tutti,
> dovrei usare una routine che genera delle permutazioni di elementi in una
> lista.
> In rete ho trovato questa ricorsiva:
>
> def perm(n, i):
> if i == len(n) - 1:
> print n
> else:
> for j in range(i, len(n)):
> n[i], n[j] = n[j], n[i]
> perm(n, i + 1)
> n[i], n[j] = n[j], n[i] # swap back, for the next loop
>
> perm([1, 2, 3], 0)
>
> che è molto efficiente e compatta, ma non riesco a "numerare" le
> combinazioni.
> In pratica non riesco ad inserire un "contatore" nel ciclo ricorsivo che
> enumeri le combinazioni.
> Per esempio se voglio un output così
> 1 1,2,3
> 2 1,3,2
> 3 2,1,3
> ecc....
>
> Chi mi potrebbe dare un suggerimento?
>
> Francesco
>
esiste una funzione della libreria standard per generare le
permutazioni: itertools.permutations.
Per enumerare un iterabile si usa solitamente la funzione "enumerate".
In sintesi:
import itertools
for n, i in enumerate(itertools.permutations([1, 2, 3])):
print('{} {}'.format(n, i))
dovrebbe fare quello che chiedi.
In forma più sintetica puoi usare anche:
print('\n'.join('{} {}'.format(n, i) for n, i in
enumerate(itertools.permutations([1, 2, 3]))))
ciao
--
Antonio Valentino
--- news://freenews.netfront.net/ - complaints: news@netfront.net ---
Back to it.comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar
Contatore in funzione ricorsiva "Francesco Di Matteo" <frankdimat@TEMPOlibero.it> - 2015-10-17 13:45 +0200
Re: Contatore in funzione ricorsiva Leonardo Serni <lserni@gmail.com> - 2015-10-17 15:10 +0200
Re: Contatore in funzione ricorsiva Antonio Valentino <antonio.valentino@tiscali.it> - 2015-10-17 17:22 +0200
Re: Contatore in funzione ricorsiva "Francesco Di Matteo" <frankdimat@TEMPOlibero.it> - 2015-10-17 18:22 +0200
csiph-web