Home > Net >  Array task. Finding last two negative numbers in array
Array task. Finding last two negative numbers in array

Time:12-04

Search for the numbers of the last two consecutive negative elements in an array. The length of the array is entered from the keyboard. Float type.

my code is:

import math
import numpy
import random
#i = (random.uniform(-1000, 1000))
o = []
a = []
n = int(input())
n  = 1
l = 0
sh = 1
m2 = n
m = n-1
m=int(m)
for i in range(n):
    x = (random.uniform(-1000, 1000))
    a.append(x)
for i in range(m):
    otric = a.pop(m)
    otric = int(otric)
    a.insert(otric,int(m 1))
    if otric < 0:
        o.append(otric)
        m -= 1
        if len(o) > 2: break
print(a)
print(o)

and this doesn't work, idk how to fix it.. please help

CodePudding user response:

Use zip to get all consecutive negative numbers and return the last element of the resulting list:

a = [random.uniform(-1000, 1000) for _ in range(n)]
>>> [(x,y) for x,y in zip(a, a[1:]) if x<0 and y<0][-1]
(-696.9270891497699, -612.4999984966855)

CodePudding user response:

Iterate the list in reverse and when a value is negative also grab the next one and see if it is the pair we're looking for:

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

it = reversed(lst)
for a in it:
    if a < 0:
         b = next(it, 0)
         if b < 0:
             print(b, a)
             break
  • Related