first of all, hello to everyone! I'm a first timer in here! anyways, I had this problem and I dont have a real direction... I tried this:
def MyStars(inputList):
l = len(inputList)
ret = []
for x in inputList:
ret.append("* ")
print(ret)
but then I realised that the output is a string of * which last the number of integers I have in the original List... the outcome is:
['* ', '* ', '* ']
while I want it to be for the list [3,9,7] for example:
*** ********* *******
can someone help? tnx
CodePudding user response:
I would not use append
but a list comprehension with string multiplication:
def MyStars(inputList):
print(' '.join(['*'* i for i in inputList]))
MyStars([3, 9, 7])
output: *** ********* *******
To fix your code, you would need 2 loops, one to iterate over the numbers, and one to append your characters, then join
your lists:
def MyStars(inputList):
l = len(inputList)
for x in inputList:
ret = []
for i in range(x):
ret.append('*')
print(''.join(ret), end=' ')
MyStars([3, 9, 7])
NB. note that this version gives a trailing space.
CodePudding user response:
try this code.
What happened with your code is that you were close to the answer, but you needed to use the range function and loop through x to add the correct number of stars to your list.
def MyStars(inputList):
l = len(inputList)
ret = []
for x in inputList:
for i in range(x):
ret.append("*")
ret.append(" ")
for a in ret:
print(a)
CodePudding user response:
If to print is all you want to do, you can just
print(*("*" * n for n in input_list))
which for input_list = [3, 9, 7]
prints *** ********* *******
<s: str> * <n: int>
multiplies strings
n
times e.g."xYZ" * 3
will result in"xYZxYZxYZ"
(in this case"*" * 3
will be"***"
)("*" * n for n in input_list)
creates a collection of"*" * n
-s for eachn
ininput_list
(this creates a generator that can be iterated only once, if you want to iterate the collection more than once, you can create e.g. a list([...]
) instead)print(*<iterable>)
prints each item of the iterable and separates them withsep
(that is by default a space, which happens to be what you want, you can passsep
as aprint
param, e.g.print(*<iterable>, sep="\n")
An example of fixing your solution (I also adjusted naming to follow python conventions):
def my_stars(input_list):
stars_strings = []
for x in input_list:
stars_strings.append("*" * x)
ret = " ".join(stars_strings)
print(ret)