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
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.
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)
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 string s
n
times eg "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 each n
in input_list
(this creates a generator that can be iterated only once, if you want to iterate the collection more than once, you can create eg a list( [...]
) instead) print(*<iterable>)
prints each item of the iterable and separates them with sep
(that is by default a space, which happens to be what you want, you can pass sep
as a print
param, eg 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.