Home > Software design >  I want to find the largest negative number out of a random range from -10 to 10 and the largest numb
I want to find the largest negative number out of a random range from -10 to 10 and the largest numb

Time:06-23

I want to find the largest negative number out of a random range from -10 to 10 and the largest number will be squared from that range that will be inputted by a person. for example lets say we have numbers like -7, -4, -2, 1, 3, 5, 8 so the largest negative value in here is -2 , I would like that number to be squared as in MAXI(x) ** 2 and the largest negative value to be squared and then written in a new range of the values, but not sure how to use MAXI in a loop and to find the largest negative value.

    import random

print("Enter number of elements:")
n = int(input())

nums = []

for i in range(n):
    nums.append(random.randint(-10, 10))
    neg = [n for n in nums if n < 0]
    return [max(neg) if neg else 0]

for i in range(n):
    if

CodePudding user response:

You have too much code in the loop.

import random

n = 10

numbers = [random.randint(-10, 10) for _ in range(n)]
try:
    max_negative = max(number for number in numbers if number < 0)
except ValueError:  # there might be no negative value
    max_negative = 0

print(f'numbers: {numbers}')
print(f'square of max negative: {max_negative ** 2}')
  • Related