Home > Net >  Use only while and assignment to truncate a list of numbers?
Use only while and assignment to truncate a list of numbers?

Time:08-26

I've been asked (or challenged) by a friend (just taking some Python course) about this interesting question: given a list of numbers, you can only use - 1) while-loop, and 2) assignment to truncation this list and print each step of truncating (starting with first number each time). In other words, no slicing, no extra intermediate data structure (eg. copy) allowed. (He claimed no one in the class is able to answer it....)

An example will be easier to understand the strange requirements:


L = [1, 2, 3, 4, 5]
while ???: 
    <assignment statement>
    <print ??? > 

# expected:
2 3 4 5
3 4 5
4 5
5
[] 


CodePudding user response:

I was trying out and got this solution, before I read yours. I think yours is more elegant, haha!

L = [1, 2, 3, 4, 5]
while len(L) >0:
    L.pop(0)
    print(L)

[2, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
[]

CodePudding user response:

I kind of disappoint him - or surprise him by the end of a few minutes pause.

This is what I share with him, the syntax is called extend assignment. Wonder if there is better/more elegant solution to this. But this is what I can come up within 3-min...


>>> L = [1, 2, 3, 4, 5]
>>> while L:
    f,  *L = L
    #_, *L = L     # another way, since don't care the dropping num
    print(L)

# Output
[2, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
[]
  • Related