Home > database >  how do you make a list of numbers and then arrange them even first then odd?
how do you make a list of numbers and then arrange them even first then odd?

Time:01-30

"I’m a world-renowned fashion designer and I’m about to screen new models for next month’s Fashion Week. I made them all wear different numbers and what I want you to do is separate the even-numbered models from the odd-numbered ones and make sure they get to go first. I don’t care if they call it number discrimination, I just have a preference for even numbers, okay? It’s not weird!"

An example of the output should look like:

Enter the number of elements: 4
Element #1: 6
Element #2: 5
Element #3: 17
Element #4: 12

Arranged Elements:
Element #1: 6
Element #2: 12
Element #3: 5
Element #4: 17

as you can see the list of elements are arranged, even first, then odd.

This is my current code:

num_list = []
listLength = int(input("Enter the number of elements: "))
num = 1

for i in range(listLength):
  el = int(input("Element #%d: " % num))
  num  = 1
    if el % 2 == 0:
        num_list.append(el)
    elif el % 2 != 0::
         num_list.append(el)
print(num_list)

CodePudding user response:

You are on the right track, but you keep appending to the same list, whether it is an even or an odd number. You need two lists:

even_list = []
odd_list = []
listLength = int(input("Enter the number of elements: "))
...

then:

    if el % 2 == 0:
        even_list.append(el)
    elif el % 2 != 0:
        odd_list.append(el)

and finally, concatenate the two lists:

num_list = even_list   odd_list
print(num_list)

CodePudding user response:

You can make two list of odd and even elements and than concatenate them.

Code:

Time Complexity - O(n) Space Complexity - O(n)

num_list = []
listLength = int(input("Enter the number of elements: "))
num = 1

for i in range(listLength):
    el = int(input("Element #%d: " % num))
    num  = 1
    if el % 2 == 0:
        num_list.append(el)
    elif el % 2 != 0:
        num_list.append(el)

#Created Two list
#List Comprehension
even_element=[i for i in num_list if i % 2 == 0] #Stored even_element
odd_element=[i for i in num_list if i % 2 != 0]  #Stored odd_element

arranged_elements=even_element odd_element

print("Arranged Elements:")
for index,element in enumerate(arranged_elements):
    print("Element #%d: %d" % (index 1, element))

Output:

Enter the number of elements: 4
Element #1: 6
Element #2: 5
Element #3: 17
Element #4: 12
Arranged Elements:
Element #1: 6
Element #2: 12
Element #3: 5
Element #4: 17
  • Related