简体   繁体   English

如何要求 python 中的 20 个数字,然后打印正数和负数的数量?

[英]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.另外,如果有人可以在 Javascript 中翻译相同的练习,我将不胜感激。

Something like this?是这样的吗?
Python: 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)

Your issue is that you put the input statement in the wrong place:您的问题是您将input语句放在了错误的位置:

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.由于您需要 20 个数字,因此需要将input放在 for 循环中,以便每次需要一个值时都能得到一个值。

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.关于计算positivesumnegativeqt之间的区别,您正在寻找正项的总数,因此您需要将它们加在一起,而您只想要负项的数量,因此我们每次看到一个时都会增加一次。

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. int_list是一种叫做列表理解的东西。 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() .当出现输入提示时,用户可以输入 20 个数字,由于调用了split() ,因此在不同数字之间有空格。 split() by default will split by a white space character. split()默认情况下将按空格字符拆分。 split() will return an iterable list, so we iterate over that list with for inp in … . split()将返回一个可迭代列表,因此我们使用for inp in …迭代该列表。 int(inp) will convert each of the numbers from type str to type int . int(inp)会将每个数字从类型str转换为类型int input() returns a string, so this is needed to do number operations input()返回一个字符串,因此需要执行数字操作

pos_sum calls the sum built in and passes it a generator expression. pos_sum调用内置的sum并将其传递给生成器表达式。 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.它遍历由在int_list中完成的所有操作产生的列表,并且只查找大于 0 的数字。它将把这些加起来,得到我们的总和。

neg_quantity calls the len built in and passes in an iterable list to len , constructed through a list comprehension. neg_quantity调用内置的len并将可迭代列表传递给len ,通过列表推导构建。 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 comprehension 的结果列表将包含int_list小于 0 的所有数字,并且len将返回该列表的长度,为我们提供负数的数量

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, ie number, to its int .默认情况下将以空格split的输入和 map 每个 substring,即数字,分割为其int list initializes a list to store the result of of map . list初始化一个列表来存储map的结果。

Notice that sum takes iterable .请注意, sum采用iterable Expressions in the form of num for num in nums if num > 0 are generators. num for num in nums if num > 0形式的表达式是生成器。 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 .当生成器表达式作为参数传递给 function 时,结果作为iterabletuple传递。 Therefore pos gives you the sum of all positive numbers in the list.因此pos为您提供列表中所有正数的总和。 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.与列表理解相比,生成器不需要额外的空间,一旦结果传入,python 可以自动为您收集垃圾。

This answer explains a little bit more about generator expressions and provides another way to get and store the input.这个答案更多地解释了生成器表达式,并提供了另一种获取和存储输入的方法。

sum(iterable,/,start=0) 总和(可迭代,/,开始= 0)

len(s) 镜片)

map(function,iterable,...)映射(函数,可迭代的,...)

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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