Good day to all.

Condition A list of numbers is given. If there are two adjacent elements of the same character in it, output these numbers. If there are no adjacent elements of the same character, do not display anything. If there are several such pairs of neighbors, output the first pair.

http://pythontutor.ru/lessons/lists/problems/same_sign_neighbours/

a = [int(i) for i in input().split()] res = [] for i in range(len(a)-1): if (a[i] > 0 and a[i+1] > 0) or (a[i] < 0 and a[i+1] < 0): res.append(a[i]) res.append(a[i+1]) print(res[0], res[1]) 

In general, the code may be useful to the same beginners as I, because in general I did everything more or less correctly. He did elementary. Traversing the list, adding to the end of the new list of two adjacent elements with one sign. Output only the first two elements of the new list, in case there are several such pairs. It passes all the tests, except those where If there are no adjacent elements of the same character - do not print anything. What exactly does "not output" mean? So it is displayed on my screen only if there are at least two adjacent elements suitable for the conditions.

    2 answers 2

    The print command is called at the very end in any case, regardless of the conditions. If there are no neighboring elements of the same character, res will be an empty list and during the call to print, an IndexError exception will occur. To understand this situation, write in the console:

     >>> l = [] >>> print l[0] 

    You can not take the first items from the list where there are no items. Therefore, before calling the print command, impose a condition that res is not empty. In general, there is a more optimal solution. But this is a completely different conversation :)

    • what a stupid mistake was. Before the print, I just added if len (res)> 0 Thank you! Can I have another solution too? In order to improve education. - Emil Aliyev
    • By the way, you can check the list for emptiness simply by the condition if res . And about another solution I will say this. You do not need to keep all the pairs of numbers of the same character, all you need is the first one. How to find it, type it and make a break. Such a decision is just written in another answer. - Mikhail Lelyakin

    Here is another one of many possible options:

     l = [int(i) for i in input().split()] for i in range(1, len(l)): if l[i-1] * l[i] > 0: print(l[i-1], l[i]) break 
    • multiplying numbers with the same or different characters ... just before genius ... - Emil Aliyev