计算偶数和奇数及其总数(python)
我在做作业时遇到了困难,我觉得我快要找到答案了,但现在卡住了。基本上,我们需要输入一个高的整数作为范围,一个低的整数作为范围,然后输入一个数字,找出这个数字的倍数。虽然我能得到我输入的任何数字的倍数,但接下来我们还需要统计这些倍数中偶数和奇数的数量,并把它们加起来:
这是我目前的代码:
def main():
high = int(input('Enter the high integer for the range: ')) # Enter the high integer
low = int(input('Enter the low integer for the range: ')) # Enter the lower integer
num = int(input('Enter the integer for the multiples: ')) # Enter integer to find multiples
def show_multiples():
# Find the multiples of integer
# and print them on same line
for x in range(high, low, -1):
if (x % num) == 0:
print(x, end=' ')
def isEven(x):
count = 0
total = 0
for count in range():
if (x % 2) == 0:
count = count + 1
else:
count = count + 1
print(count, 'even numbers total to')
print(count, 'odd numbers total to')
isEven(x)
show_multiples()
main()
我离答案近吗,还是完全错了?我刚开始学Python,这是我第一次在课堂上用它。
编辑:
Here are the instructions for the homework:
Part 1: Write a program named multiples1.py that generates all multiples of a specified
integer within a specified consecutive range of integers. The main function in the program
should prompt the user to enter the upper and lower integers of the range and the integer
for which multiples will be found. A function named show_multiples should take these three
integers as arguments and use a repetition structure to display (on same line separated by
a space) the multiples in descending order. The show_multiples function is called inside
main. For this program, assume that the user enters range values for which multiples do exist.
SAMPLE RUN
Enter the high integer for the range 100
Enter the low integer for the range 20
Enter the integer for the multiples 15
90 75 60 45 30
Part 2: Make a copy of multiples1.py named multiples2.py. Modify the show_multiples
function so it both counts and totals the even multiples and the odd multiples. The
show_multiples function also prints the counts and sums. See sample run.
SAMPLE RUN
Enter the high integer for the range 100
Enter the low integer for the range 20
Enter the integer for the multiples 15
90 75 60 45 30
3 even numbers total to 180
2 odd numbers total to 120
Part 3: Make another copy of multiples1.py named multiples3.py. Modify the show_multiples
function so that it creates and returns a list consisting of all of the multiples (even
and odd). The show_multiples function should print only "List was created", not the
multiples. Create another function named show_list that takes the list as its sole
argument. The show_list function should output the size of the list, display all of the
list elements, and output the average of the list accurate to two decimal places. See
sample run.
SAMPLE RUN
Enter the high integer for the range 100
Enter the low integer for the range 20
Enter the integer for the multiples 15
List was created
The list has 5 elements.
90 75 60 45 30
Average of multiples is 60.00
5 个回答
在编程中,有时候我们需要把一些代码放在一个地方,以便在需要的时候可以重复使用。这就像把常用的工具放在一个工具箱里,随时可以拿出来用。
有些时候,我们会遇到一些问题,比如代码运行得不太顺利。这时候,我们可以通过查看错误信息来找到问题所在。错误信息就像是一个提示,告诉我们哪里出错了,应该怎么修正。
另外,编程中还有一个重要的概念叫做“调试”。调试就是找出代码中的错误并修复它们的过程。就像是修理坏掉的机器,找到问题后把它修好,让它重新正常工作。
总之,编程就像是解决难题的过程,我们需要不断尝试、调整,直到找到最好的解决方案。
def find_it(seq):
for i in seq:
count = seq.count(i)
if count%2 != 0:
return i
break
写一个Python程序,让用户输入一个正数,比如N。在输入时要给用户一个合适的提示。如果用户输入的不是正数,就要再次提示用户输入,直到他们输入一个正数为止。接着,计算前N个奇数的和以及前N个偶数的和。最后,把这两个和用合适的标题显示出来。
n = int(input("enter n no.... : "))
sumOdd =0
sumEven = 0
for i in range (n) :
no = int(input("enter a positive number : "))
if no > 0 :
if no % 2 == 0 :
sumEven = sumEven + no
else :
sumOdd = sumOdd + no
else :
print("exit.....")
break
print ("sum odd == ",sumOdd)
print ("sum even == ",sumEven)
这里是代码
def show_multiples():
# Find the multiples of integer
# and print them on same line
lst = []
for x in range(low, high+1):
if (x % num) == 0:
#print x
lst.append(x)
return lst
def check_even_odd(lst):
count = 0
total = 0
eventotal = 0
oddtotal = 0
for x in lst:
if (x % 2) == 0:
count = count + 1
eventotal = eventotal + x
else:
total = total + 1
oddtotal = oddtotal + x
print(count, 'even numbers total to', eventotal)
print(total, 'odd numbers total to', oddtotal)
def main():
high = int(input('Enter the high integer for the range: ')) # Enter the high integer
low = int(input('Enter the low integer for the range: ')) # Enter the lower integer
num = int(input('Enter the integer for the multiples: ')) # Enter integer to find multiples
reslst = show_multiples()
print reslst
check_even_odd(reslst)
main()
首先,使用嵌套函数会让代码变得难以阅读和理解,这一点要注意。接下来,关注一下你计算偶数个数的部分——这和乘法没有关系,所以从定义上来说,它是不正确的。更清晰的做法是把乘法的结果保存下来,以便打印和计算偶数个数。另外,你的函数叫做isEven,但它并没有检查一个数字是否是偶数,而是根据x来计算一些东西。这是不好的编程习惯。函数的名字应该清楚地描述它们的功能。然后,看看你的打印语句。它们打印的是同一个变量,但给出的信息不同,这看起来像是个错误。在这里,我给你提供一个清晰而优雅的解决方案。如果你是新手,可能需要学习一些有用的Python函数,比如filter
,并了解range
和xrange
之间的区别。另外,注意你指定的边界中的下限是不包括在内的。要改变这一点,可以在调用xrange时使用low-1。
def get_multiplies(high, low, num):
"""Find the multiples of integer"""
return filter(lambda x: x % num == 0, xrange(high, low, -1))
def isEven(x):
return x % 2 == 0
def main():
high = int(input('Enter the high integer for the range: ')) # Enter the high integer
low = int(input('Enter the low integer for the range: ')) # Enter the lower integer
num = int(input('Enter the integer for the multiples: ')) # Enter integer to find multiples
multiplies = get_multiplies(high, low, num)
# print multiplies on same line
print ' '.join(str(m) for m in multiplies)
even_count = len(filter(isEven, multiplies))
print(even_count, 'even numbers total to')
print(len(multiplies) - even_count, 'odd numbers total to')
main()
让我们把这个问题拆分成几个部分来理解。
首先,我们需要获取范围在[X, Y]之间的数字(包括X和Y,但说明中没有明确提到这一点)。
high = int(input('Enter the high integer for the range: ')) # Enter the high integer low = int(input('Enter the low integer for the range: ')) # Enter the lower integer num = int(input('Enter the integer for the multiples: ')) # Enter integer to find multiples multiples = [] for value in range(high, low-1, -1): if value % num == 0: multiples.append(value)
现在有很多方法可以改进这个过程(让它更符合Python的风格,并可能提高速度,特别是在低值和高值之间差距很大的情况下)……所以我们先让它更符合Python的风格。
multiples = [value for value in range(high, low-1, -1) if value % num == 0]
也许甚至可以
multiples = [value for value in range(high, low-1, -1) if not value % num]
提高速度的方法是找到一个小于或等于
high
的第一个倍数(在这个例子中叫做first
),然后通过以下方式生成倍数:multiples = list(range(first, low, -num))
这个方法跳过了所有你已经知道不是倍数的中间数字。
所以我们得到了倍数,并且它们是按降序排列的……太好了!现在我们想把这些数字分成两组,
odd
(奇数)和even
(偶数)。为了做到这一点,我们可以用一些聪明的技巧,或者就老老实实地一个一个遍历。odd, even = [], [] for value in multiples: if value % 2 == 0: even.append(value) else: odd.append(value)
一旦我们把
odd
和even
填充了相应的值,我们可以用内置的len
函数来计算每组有多少个数字,代码看起来像这样:len(odd) len(even)
要计算总和,我们可以使用内置的
sum
函数,代码看起来像这样:sum(odd) sum(even)
所以第二部分的一个工作示例是:
def show_multiples(low, high, num):
first = high // num * num # Divided the high by num and floor it (ie. 100 // 15 == 6) ... then mutiply by 6.
# can be written as
# first = (high // num) * num
# if that is clearer
multiples = list(range(first, low-1, -num)) # more efficient for large delta
# OR
# multiples = [value for value in range(high, low-1, -1) if not value % num]
odd, even = [], []
for value in multiples:
if value % 2 == 0:
even.append(value)
else:
odd.append(value)
print(" ".join(map(str, multiples))) # just some trickery to get a list of numbers to work with join
# could also do this - the comma prevents a newline
# for multiple in multiples:
# print(multiple),
# print()
print("{} even numbers total {}".format(len(even), sum(even))) # string.format
print("{} odd numbers total {}".format(len(odd), sum(odd)))
def main():
high = int(input('Enter the high integer for the range: ')) # Enter the high integer
low = int(input('Enter the low integer for the range: ')) # Enter the lower integer
num = int(input('Enter the @integer for the multiples: ')) # Enter integer to find multiples
show_multiples(low, high, num)
if __name__ == "__main__":
main()
注意
我仍在使用Python2,所以这段代码和Python3之间可能会有一些细微的差别。例如,我不确定你是否需要像我这样把range
包裹在列表中。我是为Python2写的这段代码,并把我知道需要转换的部分改成了Python3。
编辑
如果你需要在不使用列表的情况下做到这一点……那么这将是我的方法:
def show_multiples(low, high, num):
even_count = 0
odd_count = 0
even_sum = 0
odd_sum = 0
for value in range(high, low-1, -1):
if value % num:
continue
if value % 2 == 0:
even_count += 1
even_sum += value
else:
odd_count += 1
odd_sum += value
print(value),
print
print("{} even numbers total {}".format(even_count, even_sum))
print( "{} odd numbers total {}".format(odd_count, odd_sum))
def main():
high = int(input('Enter the high integer for the range: ')) # Enter the high integer
low = int(input('Enter the low integer for the range: ')) # Enter the lower integer
num = int(input('Enter the @integer for the multiples: ')) # Enter integer to find multiples
show_multiples(low, high, num)
if __name__ == "__main__":
main()