Mr.Code Mr.Code - 20 days ago 6
Python Question

Can someone note what line 6 to line 10 do. In simple form e.g. lst.remove(0) - removes 0 from the list (lst)

sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
s = sentence.split()
lst = [0]
print(sentence)
for count, x in enumerate(s):
if s.count(x) < 2:
lst.append(max(lst) + 1)
else:
lst.append(s.index(x) +1)
lst.remove(0)
print(lst)


Can someone describe what each line does so that i can understand what the code is doing at each stage.

Can someone give notes on what the lines do in the for statement until lst.append(s.index(x)+1).

e.g.

lst.remove(0) - removes 0 from the list lst

Answer

Here ya go, but you should really, REALLY try learning this on your own via google + documentation. It's quite a fun process actually (or at least it was for me).

sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
# this ^ defines sentence as that string
s = sentence.split() 
# this ^ splits sentence at each occurence of ' ' and assigns it all to s (in the form of a list)
lst = [0]
# this ^ makes lst a list containing the number zero
print(sentence)
# this ^ this prints sentence
for count, x in enumerate(s): 
# this ^ this begins to iterate over s, with x as the item in s and count as the index for x in s
    if s.count(x) < 2:
# this ^ tests whether the number of occurrences of x in s is less than 2
        lst.append(max(another) + 1)
# this ^ should append the largest item in another plus one to lst, but another is not defined
    else:
# this ^ you should understand
        lst.append(s.index(i) +1)
# this ^ should append the item at index i plus 1 in s to lst, but i is not defined and you can't add integers to a string like that
lst.remove(0)
# this ^ removes occurrences of 0 in lst
print(another)
# this ^ prints another
Comments