Home > Back-end >  Neighbours of same sign exercise in pyhton - help needed
Neighbours of same sign exercise in pyhton - help needed

Time:10-19

I have the following exercise.

Neighbours of same sign Given a sequence of numbers, find and print the first adjacent elements which have the same sign. If there is no such pair, print NONE. Please note that the output must be the same as indicated in the example.

Example Input: -1 2 -3 -4 -5 1 2 Output: -3 -4

this is my code, but it does not work when I try to catch the case when the pairs are not the same sign, can someone help? The code works fine, but when i add the ELSE things break down.

s = input()
my_list_str = s.split()
my_list = []

for beta in my_list_str:
  my_list.append(int(beta))

for i in range(len(my_list)-1):
  if my_list[i]>0 and my_list[i 1] >0:
     print (my_list[i], end =' ')
     print (my_list[i 1])
     break
  elif my_list[i]<0 and my_list[i 1] <0:     
      print (my_list[i], end =' ')
      print (my_list[i 1])
      break
  else:
    print ('NONE')

CodePudding user response:

just add a found flag

s = input()
my_list_str = s.split()
my_list = []


for beta in my_list_str:
    my_list.append(int(beta))


found=False
for i in range(len(my_list)-1):
  if my_list[i]>0 and my_list[i 1] >0:
     print (my_list[i], end =' ')
     print (my_list[i 1])
     found=True
     break
  elif my_list[i]<0 and my_list[i 1] <0:     
      print (my_list[i], end =' ')
      print (my_list[i 1])
      found=True
      break
    
if not found:
    print ('NONE')

you should check the else part once

CodePudding user response:

I would suggest keeping track of the sign of the previous and current numbers and a found flag. For example like this:

list = [-1, 2, -3, 4, -5, 1]

prev_sign = -1
found = 0
for i in range(len(list)):
    this_sign = list[i] < 0
    if this_sign == prev_sign:
        print("{} {}".format(list[i - 1], list[i]))
        found = 1
        break
    prev_sign = this_sign

if not found:
    print("NONE")

Or even more concise, the for loop could look like this:

for i in range(1, len(list)):
    if (list[i] < 0) == (list[i - 1] < 0):
        print("{} {}".format(list[i - 1], list[i]))
        found = 1
        break

CodePudding user response:

One error I see with the code is the placement of the else statement inside the for-loop. In the existing code, if the first two elements have mismatched sign, then it will immediately print 'NONE' because it reaches that else statement, and will continue printing 'NONE' until it does find matching neighbors. I would rewrite your for-loop as follows:

found_pair = False
for i in range(len(my_list)-1):
    if my_list[i] * my_list[i 1] > 0: # matching sign
        found_pair = (my_list[i], my_list[i 1])
        break
if found_pair:
    print(found_pair[0], found_pair[1])
else:
    print('NONE')

In the above code, the result must necessarily only print once after it's already finished the for-loop. If a pair is found, it is stored and we break, otherwise we exhaust the loop without ever assigning found_pair, leading 'NONE' to be printed only once at the end. Let me know if this doesn't work or if you have any questions!

David

CodePudding user response:

Lots of suggestions for a found flag, but you don't need one. This is where the else on a for loop comes in:

lst = [-1, 2, -3, 4, -5, 1]

# zip lst with a slice of itself to get corresponding
# elements offset by 1 position
for a, b in zip(lst, lst[1:]):
    if a * b > 0:
        print(f"Found pair {a} {b}")
        break
else:
    print("NONE")

The else will only trigger if the for loop completes (isn't ended early by break)

  • Related