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

时间:2014-09-02 05:04:18

标签: python loops

我很难完成作业,我觉得我已经接近答案了,但我现在已经陷入困境了。基本上我们应该为范围输入一个高整数,为该范围输入一个低整数,然后输入一个数字来找出该数字的倍数。虽然我能够得到我输入的任何数字的倍数,但我们应该计算打印倍数中的偶数和奇数并将它们总计:

到目前为止,这是我的代码:

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

我接近答案还是离开了? 这是我第一次将它用于课堂。

修改:

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

4 个答案:

答案 0 :(得分:0)

首先,为什么要使用嵌套函数,这使得阅读和理解变得困难。接下来,注意你的偶数计算 - 它对乘法没有任何作用,因此根据定义它是不正确的。更明确的方法是以某种方式保存您的乘法以进行打印甚至计算计算。另请注意,您的函数名为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() 

答案 1 :(得分:0)

这是代码

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

    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)