sum of negative int in list - python

I am trying to add all of the negative integers in a user input list, but the function always returns 0 as the answer. It works if I include the list as part of the function, but not when its user input. The code I have is:
def sumNegativeInts(userList):
userList = []
sum = 0
for i in userList:
if i < 0:
sum = sum + i
return sum
userList = input("Enter a list of +/- integers: ")
print(sumNegativeInts(userList))

sum(i for i in alist if i < 0)
Done. It's Python, it has to be simple!

remove the second line of your code, it sets the input to an empty list no matter what your input is.

You assign an empty list to userList every time you enter the function, how can it not be 0?
Further more, the function input() seems not able to handle a list of inputs.
So I think you can do this:
def sumNegativeInts(userList):
sum = 0
for i in userList:
if i < 0:
sum += i
return sum
inputData = raw_input('some prompts')
userList = [int(i) for i in inputData.split(' ')]
print(sumNegativeInts(userList))

You could always just do if and elif statements to determine whether or not to add a number to a list and then take the sum of the list. My prompt is making a list of 100 number with random integers from -100 to 100. Then finding the sum of all the negative numbers.
import random
def SumNegative():
my_list = []
for i in range(100):
x = random.randint(-100, 100)
if x > 0:
pass
elif x < 0:
my_list.append(x)
print(sum(my_list))
SumNegative()

Related

How to ask for 20 numbers in python and, then, print the sum of positives and quantities of negatives?

The problem seems very simple but I'm cracking my head over it. It's just an algorithm exercise. This is what I have so far:
positivesum = 0
negativeqt = 0
value = int(input(("Enter the numbers: ")))
for _ in range(20):
value
if value > 0:
positivesum = positivesum + value
print("The sum of positives is ", positivesum)`
Also, if someone could translate the same exercise in Javascript, I would appreciate it.
Something like this?
Python:
sum_positive_number = 0
negative_number_quantities = 0
numbers = 20
for i in range(numbers):
number_input = int(input(f'Enter number #{i+1}: '))
if number_input > 0:
sum_positive_number += number_input
elif number_input < 0:
negative_number_quantities += 1
print('Sum of positive numbers: ', sum_positive_number)
print('Quantities of negative numbers: ', negative_number_quantities)
int_list = [int(inp) for inp in input("Enter 20 numbers: ").split()]
pos_sum = sum(num for num in int_list if num > 0)
neg_quantity = len([num for num in int_list if num < 0])
print(f"{pos_sum=} {neg_quantity=}")
How It Works
int_list is something called a list comprehension. When prompted with the input, a user is able to input the 20 numbers, with spaces in between the different numbers due to the call to split(). split() by default will split by a white space character. split() will return an iterable list, so we iterate over that list with for inp in …. int(inp) will convert each of the numbers from type str to type int. input() returns a string, so this is needed to do number operations
pos_sum calls the sum built in and passes it a generator expression. It iterates over the list resulting from all of the operations done in int_list and only looks for the numbers that are greater than 0. It will add these up, giving us our sum.
neg_quantity calls the len built in and passes in an iterable list to len, constructed through a list comprehension. The resulting list from the comprehension will contain all numbers from int_list less than 0, and len will return the length of that list, giving us our quantity of negatives
nums = list(map(int, input('Enter the numbers: ').split()))
pos = sum(num for num in nums if num > 0)
neg = len(num for num in nums if num < 0)
print(pos, neg)
split the input separated by whitespace by default and map each substring, i.e. number, to its int. list initializes a list to store the result of of map.
Notice that sum takes iterable. Expressions in the form of num for num in nums if num > 0 are generators. A generator yields a result one by one according to the condition until it terminates. When a generator expression is passed into a function as an argument, the result is passed as a tuple which is iterable. Therefore pos gives you the sum of all positive numbers in the list. Compared to a list comprehension, generators do not demand extra space and once the result is passed in, python can automatically collect the garbage for you.
This answer explains a little bit more about generator expressions and provides another way to get and store the input.
sum(iterable,/,start=0)
len(s)
map(function,iterable,...)
Your issue is that you put the input statement in the wrong place:
positivesum = 0
negativeqt = 0
for _ in range(20):
value = int(input(("Enter the numbers: ")))
if value > 0:
positivesum += value
else if value < 0:
negativeqt += 1
If you only ask for one input then the user can only give you one number. Since you want twenty numbers, you need to put the input inside your for-loop so you get a value every time you need a value.
With regard to the difference between calculating positivesum and negativeqt, you're looking for the total of the positive terms so you need to add them together whereas you only want the quantity of negative terms so we increment once every time we see one.
positive = 0
negative = 0
for i in range(-10 , 10):
print(i)
if i >= 0:
positive += i
elif i <= 0:
negative += 1
print(positive)
print(negative)

Trying to return multiple random numbers as an input parameter to a defined function to return true if the numbers are even and false is odd

I have to have three defined functions. The first asks the user for an input and it is returned to the next which creates random numbers in the range specified in the first function. That is then returned to the third function which checks all the numbers and returns true if they are even and false if they are odd. I have this so far, but I get the error "TypeError: 'int' object not iterable." I'm not sure what I'm doing wrong.
import random
def odd(n):
my_list = []
my_list.append(n)
for i in len(my_list):
if n%2 != 0:
return False
else:
return True
def producer(num):
for i in range(num):
n = random.randint(100,2000)
return n
def main():
ask = int(input('How many numbers do you want to generate? '))
return ask
num = main()
numbers = producer(num)
gen = odd(n)
print(gen)
the error is because of the for i in len(my_list). len(my_list) will return an int.
you want "for num in my_list" instead. then inside the function, "num%2" instead of "n%2".
Is this what you are trying to achieve:
import random
def get_user_input():
# The first asks the user for an input and it is returned to the next
user_input = int(input('How many numbers do you want to generate? '))
return user_input
def producer(n):
# which creates random numbers in the range specified in the first function.
random_list = [random.randint(100, 2000) for i in range(n)]
return random_list
def odd(lst):
# That is then returned to the third function which checks all the numbers and
for n in lst:
if n % 2 == 0:
# returns true if they are even
print(True)
else:
# and false if they are odd
print(False)
if __name__ == '__main__':
user_input = get_user_input()
list_range = producer(user_input)
odd(list_range)
I see a number of problems with your code.
Your for loops will each return a value on the first iteration of the loop, so they aren't doing you any good as loops...there will never be a second iteration of either loop.
n is undefined in your outer scope, so the line gen = odd(n) will throw an exception stating that n is undefined.
You have a problem with the definition of what you want your code to do. You want to generate a list of numbers and pass them to the odd function, but then you say you want odd to return True or False based on if "that number" is odd or even. But there isn't a single number. You're passing a list of numbers, and in general, some will be odd and some will be even.
Your interpretation of what n%2 != 0 means seems backwards.
Here's a version of your code that addresses all of these issues. I decided to replace your odd function with a function named more_odd_than_even. The function does as the name implies. It returns True if more of the numbers in the list are odd than are even, and False otherwise.
import random
def more_odd_than_even(the_list):
odd_count = 0
even_count = 0
for n in the_list:
if n % 2 == 0:
even_count += 1
else:
odd_count += 1
return odd_count > even_count
def producer(num):
my_list = []
for i in range(num):
n = random.randint(100, 2000)
my_list.append(n)
return my_list
def main():
ask = int(input('How many numbers do you want to generate? '))
return ask
num = main()
numbers = producer(num)
print(f"The generated list is:{numbers}")
gen = more_odd_than_even(numbers)
if gen:
print("More of the numbers are odd")
else:
print("More of the numbers are even (or there are an equal number of each)")
Here are a few sample runs of this code:
How many numbers do you want to generate? 6
The generated list is:[972, 1327, 1603, 1714, 491, 1007]
More of the numbers are odd
How many numbers do you want to generate? 7
The generated list is:[1540, 696, 904, 475, 1007, 1238, 148]
More of the numbers are even (or there are an equal number of each)

how do I print the smallest and largest number of n random numbers without using lists or any other data structure

The program should read a positive integer n from the user to decide how many number to generate.
The random numbers should be in the intervall [1, 100].
I should then print the average value, smallest value and largest value.
But WITHOUT using lists or any other data structure.
I managed to get the average value but I still need to get smallest and largest. any advise?
here is how my code look like so far
You can use the built in min() and max() functions. Here's a bit of code, should be pretty self explanatory:
import random
n = 20
# set up the values
smallest = 101
biggest = -1
for i in range(n):
x = random.randint(1,100)
# take the smallest of the new random number and the current smallest
smallest = min(x, smallest)
# take the biggest of the new random number and the current biggest
biggest = max(x, biggest)
print(smallest, biggest)
If I understand your question, you are trying to print the smallest and largest number of these five numbers without using a list.
You can easily create variables, and change them, if a higher/lower value is generated, then the highest/lowest value before. Hope it helps:
import random
n = int(input("Enter a number of integers to be generated: "))
if n < 0:
print("Please enter a positive integer!")
else:
highest_value = 0
smallest_value = 100
sum_of_random = 0
for x in range(n):
x = random.randint(1, 100)
sum_of_random += x
if x > highest_value:
highest_value = x
if x < smallest_value:
smallest_value = x
print(x, end = " ")
print("\n")
avg = round(sum_of_random / n, 2)
print(avg)
print(highest_value)
print(smallest_value)
If this answers your question, please mark it as a correct answer.

writing a loop that ends with a negative number and prints the sum of the positive numbers

i have to write a program with a loop that asks the user to enter a series of positive numbers. the user should enter a negative number to signal the end of the series, and after all positive numbers have been entered, the program should display their sum.
i don't know what to do after this, or whether this is even right (probably isn't):
x = input("numbers: ")
lst = []
for i in x:
if i > 0:
i.insert(lst)
if i < 0:
break
you should use input in the loop to enter the intergers.
lst = []
while True:
x = int(input('numbers:'))
if x > 0:
lst.append(x)
if x < 0:
print(sum(lst))
break
def series():
sum1 = 0
while True:
number = int(input("Choose a number, -1 to quit:"))
if number>=0:
sum1+=number
else:
return sum1
series()
while True means that the algorithm has to keep entering the loop until something breaks it or a value is returned which ends the algorithm.
Therefore, while True keep asking for an integer input , if the given integer is positive or equal to zero, add them to a sum1 , else return this accumulated sum1
You can use a while loop and check this condition constantly.
i, total = 0, 0
while i>=0:
total+=i
i = int(input('enter number:'))
print(total)
Also, don't use:
for loop for tasks you don't know exactly how many times it is going to loop
while loop as while True unless absolutely necessary. It's more prone to errors.
variable names that have the same name as some built-in functions or are reserved in some other ways. The most common ones I see are id, sum & list.
do you want that type of code
sum_=0
while True:
x=int(input())
if x<0:
break
sum_+=x
print(sum_)
Output:
2
0
3
4
5
-1
14
if you want a negative number as a break of input loop
convert string to list; input().split()
convert type from string to int or folat; map(int, input().split())
if you want only sum, it is simple to calculate only sum
x = map(int, input("numbers: ").split())
ans = 0
for i in x:
if i >= 0:
ans += i
if i < 0:
break
print(ans)

Get Better Time Complexity

This code is for asserting values into the list until the user inputs a negative number.
Is there a way better to implement it?
Below is my tried version.
i = -1
while i > -1:
x = raw_input("Enter array limit")
for i in limit(x):
listArr = list()
y = raw_input("Enter number")
y.append(listArr)
print (listArr)
Something like this should meet the requirements:
odds = [] # similiar to `listArr` but we only want odd numbers
limit = 5
for _ in range(limit): # Input 5 numbers into an array
y = int(input('Enter number: '))
if y > -1 and y % 2 !=0: # if odd number
odds.append(y) # add to array
else:
break # break after a negative number as input
if odds:
print(min(odds)) # and display minimum odd number
# and if no negative integer input then also display minimum odd number
else:
print(0) # and if no odd number display zero
If Python2 use raw_input() as used in question code, otherwise use input().

Categories