The goal is: using the list generator (and not using the code outside of it), convert the string according to the following logic: for each character of the string, create a string in the final list containing copies of the character in an amount equal to the character number calculated from the end of the source string. For instance: 'abcd' - > ['aaaa', 'bbb', 'cc', 'd']. So, first i have tried to solve this problem without the list generator:
s='abcd'
a=' '.join(s)
b=a.split()
for i in range(len(b)):
b[i]*=len(b)-i
print(b)
Then i tried list generator and find the problem:
a=[input() for i in range(len(input()))]
print(a)
1)How to enclose input() in a variable and how to correctly convert a string to a list in a single line( i mean without using cod outside of generator)?2) How to write the body of the "for" loop, if the general form of the generator is as follows: [expr for targets in iterable]?
1 Answer 1
If I understand your requirement correctly the following one liner should satisfy your constraints-
print([character * (idx + 1) for idx, character in enumerate(input()[::-1])][::-1])
Its very un-idiomatic and you should consider a more readable solution - unless of course this is the purpose of the exercise.
[expr for targets in iterable]is a list comprehension, and(expr for targets in iterable)is a generator expression (the parentheses are optional in some cases).a = [s * i for i,s in enumerate(reversed(input()), start=1)][::-1]match your requirements?[char*(len(s)-i) for i, char in enumerate(s)]