Reputation: 320
I have this activity where I have to use star growth in a string where it grows with the amount of a character in the string. Here is an example: star_match_growth("incandescent", "c") and have it return as: inc*andesc**ent and have it continue if there are any more c's in the string. This is what I have to far:
def star_match_growth(word, letter):
builder = ""
for i in range(0, len(word)):
word_2 = word.replace(letter, str(star_growth(word.count(letter))))
return word_2
def star_growth(top):
word = top * "*"
builder = ""
for i in range(1, len(word) + 1):
builder += word[0:i] + " "
return builder[:-1]
print(star_match_growth("incandescent", "c"))
and the output is:
inc* **andesc* **ent
Note it also has to ignore capitalization Note I'm also not allowed to import anything into the code iteself
Upvotes: 0
Views: 88
Reputation: 10799
You can provide re.sub
with a callable (function, lambda, etc.) which must accept a single regex match-object as an argument, and which must return a string with which to replace that match. In my snippet, I'm taking advantage of a persistent default argument it
, which is an iterator that yields ascending integers (starting at 1 in this case). The state of the iterator is preserved between invocations, which has the effect of appending more and more stars to subsequent matches:
def star_match_growth(string, pattern):
import re
from itertools import count
def replace(match, it=count(1)):
return match.group() + ("*" * next(it))
return re.sub(pattern, replace, string, flags=re.IGNORECASE)
print(star_match_growth("incandescent", "C"))
Output:
inc*andesc**ent
>>>
EDIT - Not taking advantage of the standard library, and using a generator that yields characters (and sometimes strings of stars):
def star_match_growth(string, letter):
num_stars = 1
for char in string:
yield char
if char in {letter.lower(), letter.upper()}:
yield "*" * num_stars
num_stars += 1
print("".join(star_match_growth("incandescent", "C")))
Upvotes: 2