【问题标题】:Count even and odd numbers and the totals (python)计算偶数和奇数以及总数(python)
【发布时间】:2014-09-02 05:04:18
【问题描述】:

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

这是我目前的代码:

 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

【问题讨论】:

  • 这取决于,当你运行它时 - 你会得到你期望的答案吗?
  • 看起来您对偶数和奇数使用相同的计数?
  • 是的,我对偶数和奇数使用相同的计数。我应该为每个做不同的计数吗?是的,当我运行它时,它会打印我输入的数字的倍数。但在那之后它就不起作用了。
  • 如果您使用相同的计数,那么您计算的是偶数和奇数的总和,而不是单独的计数。
  • 好的,我解决了这个问题,并做了一个 even_count 和一个 odd_count。但它仍然失败,因为 isEven 函数中的 for 循环范围

标签: python loops


【解决方案1】:

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

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

【讨论】:

  • 非常感谢!它奏效了,我现在正在回顾这本书并阅读你和伊万提到的功能。如果没有清单,还有什么方法可以完成第 2 部分吗?只是想确定一下。因为在第 3 部分是我的导师希望我们做清单的地方。还是没关系?
  • 当然不用列表也可以。请参阅我上面的编辑。现在,当您在打印倍数的同一循环中进行迭代时,您只需计算 even_counteven_sum 之类的值。
  • @Brandon:如果我回答了您的问题,您应该通过单击答案开头左侧的复选标记将其标记为已接受的答案。乐意效劳。不要只是复制和粘贴你的作业......确保你理解它。
  • 好吧,是的,我现在正在检查它以确保哈哈。
【解决方案2】:

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

【讨论】:

  • 是的,我是 python 的新手。第一周上课,我在网上上课。我会看看你提到的一些功能。
  • 为了更好的理解,我把作业的说明贴出来了。
【解决方案3】:

这里是代码

  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接受一个列表并打印出来时,这是一个糟糕的设计。
  • @klass : 这里没有 isEven,使用 list 也是一种可能的方法,通过考虑两个计数器来找出偶数和奇数。
  • 是的,但我的评论是针对您之前版本的代码。至于目前,更好的设计是将函数命名为count_even_odd(lst)return eventotal, oddtotal,并在该函数内不打印任何内容,但在main 方法中获取它:eventotal, oddtotal = count_even_odd(reslst) 然后打印
【解决方案4】:
    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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 2015-08-22
    • 2016-04-28
    相关资源
    最近更新 更多