Neighbors of the same sign. Given a list of numbers, find and print the first pair of adjacent elements that have the same sign. If no such pair exists, leave the output blank.
|
numbers = list(map(int, input().split())) for i in range(1, len(numbers)): if numbers[i] * numbers[i - 1] > 0: print(numbers[i - 1], numbers[i]) break |
Explanation of the Code
- Reading Input:
numbers = list(map(int, input().split()))
- The
input()
function reads a line of text from the user.
- The
split()
method splits this line into a list of strings based on spaces.
map(int, ...)
converts each string in the list to an integer.
list(...)
converts the map object to a list and stores it in the variable numbers
.
- Iterating Through the List and Finding the First Pair with Same Sign:
for i in range(1, len(numbers)):
if numbers[i] * numbers[i - 1] > 0:
print(numbers[i - 1], numbers[i])
break
- Use a
for
loop to iterate through the list numbers
starting from index 1 to the end of the list.
- In each iteration, check if the product of the current element (
numbers[i]
) and the previous element (numbers[i - 1]
) is greater than 0.
- If the product is greater than 0, it means both elements have the same sign (both positive or both negative). Print the pair and break the loop.