编写一个有1个参数的函数,返回两列排序整数

2024-09-29 06:34:02 发布

您现在位置:Python中文网/ 问答频道 /正文

编写具有1个参数num(不大于100的正整数)的函数oddEven(num)。此函数返回两列,一列为正整数,一列为负整数 我不知道在最后一行代码之后要做什么才能得到两列。 随机导入

def oddEven(num):
    x=num
    a,b=[],[]
    for i in range(x):
        o= b.append(random.randomint(-50,50))
        if o % 2 == 0:
            a.append(o)
        else:
            b.append(o)
    a.sort()
    b.sort()
    return a,b

def main():
    y=eval(input('What # of integers would you like in this list?:'))
    list1, list2 = oddeven(y)
    print('even','odd')
    for i in range (min(len(odd),len(even)):
            print(odd[i],even[i])            
    if len(odd) != len(even):

Tags: 函数inforlenifdefrangesort
2条回答
  1. 您需要的函数是random.randint而不是random.randomint

  2. 您需要对代码逻辑进行主要编辑:

    • 为奇数和偶数列两张表
    • 将相应的值附加到相应的列表中
    • 如果返回到循环内部,它将只运行一次

我的代码:

import random

def oddEven(num):
    x = num
    a, b = [], []
    for i in range(x):
      o = random.randint(-50,50)
      if o % 2 == 0:
        a.append(o)
      else:
        b.append(o)
    a.sort
    b.sort()
    return a,b
print(oddEven(45))

输出:

([14, 48, -10, -6, 10, 36, 26, 34, -6, 8, -26, 
16, 22, -42, -40, 38, -32, -44, 14, -46, 36, 20, 30, 10, -42], 
[-47, -41, -35, -21, -15, -15, -9, -3, -3, -1, 
5, 7, 9, 11, 17, 21, 25, 27, 33, 49])

您描述的代码的简单示例

import random

def oddEven(num):
    # create list of random numbers from -50 to 50 of length num
    l = [random.randint(-50, 50) for i in range(num)]

    # Split list l into even and odd elements
    odd = [x for x in l if x % 2 == 1]
    even = [x for x in l if x % 2 == 0]

    return odd, even

# Test
print(oddEven(20)) # ([-47, -45, -25, -25, 27, -45, 39, -19, -3, -33], [-18, -46, -8, -10, -28, -12, -30, -12, 0, -10])

相关问题 更多 >