简体   繁体   中英

How to check specific numbers in list and then count specific elements till that number?

I have a task to make program which generates a list with random 50+ numbers from -10 to 10. Then I need to find the first negative number and count all elements which are from 1 to 5 before that number.

Eg for [2, 6, -1] the result should be 1 .

I do need to use *args in this task.

I have done almost all code but I don't know how to return back from that first negative number and start counting.

import random

def check(arr, val):  #creating function which is checking numbers      
    for x in arr:
      if val>= x: 
        return True 
    return False

def function(*args):
  val = 0
  if(check(arr, val)): 
    count = arr.count(1)
    count1 = arr.count(2)
    count2 = arr.count(3)
    count3 = arr.count(4)
    count4 = arr.count(5)
    print(count + count1 + count2 + count3 + count4)
  else: # how to start counting back from here?
    return print('No negative numbers')


def generate(x):
    array = []
for i in range(0, 50):
    array.append(random.randint(-10, 10))
return array

arr = generate(60)

print(arr)

function(*arr)
import random

def function(arr):
    counter = 0
    for el in arr:
        if el >= 0:
            counter += 1
        else:
            break
    return counter


def generate():
    array = []
    for i in range(50):
        array.append(random.randint(-10, 10))
    return array

my_arr = generate()

print(my_arr)

print(function(my_arr))

The other answers are probably more useful for you. Here is a more functional approach.

First i use a list comprehension to make a list of 50 random numbers. Then i select only positive numbers up to but not including the first negative number. I transform every number between 1 to 5 to True and every other number to False . Finally i count how many numbers are between 1 and 5 , and print it to the console.

from random import randint
from itertools import takewhile

numbers = [randint(-10, 10) for _ in range(50)]

print(sum(# accumluate the result and print
    map(# only count numbers that are between 1 and 5 inclusive
        lambda n: n in range(1, 6),
        takewhile( # get all numbers up to but not including negative numbers
            lambda n: n >= 0,
            numbers))))
from random import randint

#make a list of random numbers (integers)
numbers = [ randint(-10, 10) for i in range( 50 )]

#collect the only the negative number (ri) and their position (i)
negative_numbers = [ (i, ri) for i, ri in enumerate( numbers ) if ri < 0 ]
print( numbers )

#check to ensure there are negative numbers
if negative_numbers:
    #since i is the first position of that a negative occurs, 
    # count the numbers in the list between 1 and 5
    i, ri = negative_numbers[0] 
    
    n_preceding = len( [ri for ri in numbers[0:i] if ri >= 1 and ri <= 5 ] )
    
    print( f"first random number: {ri}" )
    print( f"numbers preceding: {n_preceding}")
else:
    print( f"no negative numbers were produced" )

The above code uses list iterations, which in my opinion is a very cool feature of python.

numlist = [ i for i in range( 10 ) ]
#output: [ 0, 1, 2, 3, 4, 5.....]

strlist = [ si for si in "HELLO WORLD" ]
#output: [ "H", "E", "L", "L", "O".....]

filtered_list = [ si for si in "HELLO WORLD" if not si == "L" ]
#output = [ "H", "E", "O", " ", "W", "O", "R", "D" ]

#the for loop equivalent of the last
filtered_list = []
for si in "HELLO WORLD":
    if not si == "L":
        filtered_list.append( si )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM