Computer Science, asked by anindyaadhikari13, 2 months ago

Challenge for all programmers.
Display the given series using only 1 loop and only 1 print statement in Python.

1 1 2 1 1 1 3 1 1 1 1 4 1 1 1 1 1 5....N terms.

Language: Python.

Don't use any inbuilt function or strings. ​

Answers

Answered by 5anju
0

please check the screenshot.

Attachments:
Answered by HarishAS
2

Answer:

Challenge accepted again : )

Constrains - to use only 1 loop and 1 print statement in the program and not to use any inbuilt function or strings.

Keeping this in mind, i found the following way to print the N terms of this series.

Porgram:

n = int(input('Enter the number of terms: ' ))

l=[ ]

for i in range (2,n+1):

a=[1 for x in range (i)] + [i]

l.append(a)

t=[x for y in l for x in y]

print(*t[:n],sep=' ')

Explanation :

As you can see i used just one loop and print statement . To avoid the useage loops i made use of the list comprehension which isn't considered as a loop.

Here first i get the number of terms to be printed as an input and made a empty list.

So to achieve this i splited the series into parts like [1,1,2] ; [1,1,1,3] ...

By using for loop , list comprehension and addition of lists as seen above in the program, i was able to achieve these segemets of the series.

These lists are again added to the empty list l that we created initially.

Now this list l is a nested list , to make a one dimensional list we use list comprehension again and stored it in variable t.

Finally with the help of list slicing we are able to print the desired number of terms.

This was an interesting question.

Hope this answer helps  : )  

Similar questions