Czysta bash (używając local
, szybciej, ale nie można pokonać inną odpowiedź za pomocą awk poniżej lub poniżej Python):
perm() {
local items="$1"
local out="$2"
local i
[[ "$items" == "" ]] && echo "$out" && return
for ((i=0; i<${#items}; i++)) ; do
perm "${items:0:i}${items:i+1}" "$out${items:i:1}"
done
}
while read line ; do perm $line ; done < File
Czysta bash (używając powłoki w tle, dużo wolniej):
perm() {
items="$1"
out="$2"
[[ "$items" == "" ]] && echo "$out" && return
for ((i=0; i<${#items}; i++)) ; do
(perm "${items:0:i}${items:i+1}" "$out${items:i:1}")
done
}
while read line ; do perm $line ; done < File
Od Pytający wspomniano Perl jest w porządku, myślę, że Python 2.6 +/3.X jest w porządku, zbyt:
python -c "from itertools import permutations as p ; print('\n'.join([''.join(item) for line in open('File') for item in p(line[:-1])]))"
dla Pythona 2.5 +/3.X:
#!/usr/bin/python2.5
# http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python/104436#104436
def all_perms(str):
if len(str) <=1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm)+1):
#nb str[0:1] works in both string and list contexts
yield perm[:i] + str[0:1] + perm[i:]
print('\n'.join([''.join(item) for line in open('File') for item in all_perms(line[:-1])]))
na moim komputerze przy użyciu większy plik testowy:
First Python code
Python 2.6: 0.038s
Python 3.1: 0.052s
Second Python code
Python 2.5/2.6: 0.055s
Python 3.1: 0.072s
awk: 0.332s
Bash (local): 2.058s
Bash (subshell): 22+s
co dokładnie jest cel tej operacji? –
Lubię walić rzeczy ...: P – siliconpi