繁体   English   中英

计算偶数和奇数以及总数(python)

[英]Count even and odd numbers and the totals (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

首先,为什么要使用嵌套函数,它使阅读和理解变得困难。 接下来,请注意您的偶数计算 - 它对乘法没有任何作用,因此根据定义它不可能是正确的。 更清晰的方法是以某种方式保存您的乘数以进行打印甚至计数计算。 另请注意,您的函数被称为 isEven,但是,它不检查偶数或非数字是,它根据 x 计算某些内容。 这是不好的做法。 你的函数名称应该清楚地描述它们的作用。 然后,查看您的打印报表。 他们打印具有不同信息的相同变量。 看起来像错字。 在这里,我为您的问题发布了清晰而时尚的解决方案。 如果您是新手,可能您应该学习一些有用的 Python 函数作为filter ,并探索rangexrange的差异。 另请注意,不包括您指定的边界中的下限。 要更改它,请在调用 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() 

这是代码

  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()

让我们把它分解成它的组成部分。

  • 获取 [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)

    现在有很多方法可以改进这一点(使其更加 Pythonic,并可能提高速度 - 特别是对于低和高之间的大增量)......所以让我们首先使其更加 Pythonic。

     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))

    此解决方案跳过您已经知道不是倍数的所有中间数。

  • 所以我们有倍数,我们按降序排列……太好了! 现在我们想要将数字分成两组, oddeven 要做到这一点,我们可以使用一些聪明的技巧,或者我们可以用老式的方式来做——迭代。

     odd, even = [], [] for value in multiples: if value % 2 == 0: even.append(value) else: odd.append(value)
  • 一旦我们用相应的值填充oddeven ,我们就可以使用内置的len函数计算每个值的数量,如下所示

    len(odd) len(even)
  • 为了得到总和,我们可以使用像这样的内置sum函数

    sum(odd) sum(even)

因此,第 2 部分的一个工作示例是:

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,因此此代码和 Py3 之间可能存在一些细微差别。 例如,我不确定您是否需要像我一样将range包装在列表中。 我为 Py2 编写了这个,并将我知道需要转换的内容转换为 Py3。

编辑
如果您需要在没有列表的情况下执行此操作...那么这将是我的方法

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()
    Write a Python program to take input of a positive number, 
say N, with an appropriate prompt, from the user. 
The user should be prompted again to enter the number until 
the user enters a positive number. 
Find the sum of first N odd numbers and first N even numbers. 
Display both the sums with appropriate titles.  
    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)

暂无
暂无

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

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