Monday, 15 August 2011

Python: Create dynamic loop based on pattern -



Python: Create dynamic loop based on pattern -

i'm still learning code in python

i want generate string based on pattern, way know using loop.

in illustration code below, create loop "vcvcv" pattern. c=consonant, v=vowel

how create dynamic loop, based on pattern provide script?

eg. if pattern "cvcvc" loop should build produce string

help appeciated.

thanks.

#!/bin/env python vowel="aeiou" consonant="bcdfghjklmnpqrstvwxyz" lvowel=list(vowel) lconsonant=list(consonant) # pattern "vcvcv" = ababa in lvowel: b in lconsonant: c in lvowel: d in lconsonant: e in lvowel: myname=a+b+c+d+e print myname # pattern "cvcvc" = babab # how create loop dynamic based on pattern ?

something should work:

import itertools mapping = { 'v': 'aeiou', 'c': 'bcdfghjklmnpqrstvwxyz' } pattern = 'vcvcv' thing in itertools.product(*map(mapping.get, pattern)): print ''.join(thing)

here's how works:

map(mapping.get, pattern) converts 'vcv' ['aeiou', 'bcdfghjklmnpqrstvwxyz', 'aeiou']. replaces each letter corresponding list of characters. *map(...) unpacks argument list. itertools.product() bunch of nested loops. ''.join(thing) joins list of characters single string.

if want without itertools, you'll have create recursive function.

python

No comments:

Post a Comment