Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What's wrong
#1
What's wrong with this code?
n = int(input())
m = [int(i) for i in input().split()]
l = []
for i in range(n):
    if m[i] != -1:
        l.append(m[i])
l.sort()
for i in range(n):
    if(m[i] != -1) and m[i] in l: 
        m[i] = l[0]
        del l[0]
for i in range(n):
    print(m[i], end = ' ')
It's supposed to rearrange the inputs the increasing manner, except for -1's.

My input:
4
949 -1 3957 949
My output:
949 -1 949 949
How did that happen?
Reply
#2
First of all, learn to use meaningful names, single letter are meaningless to another programmer.
Next, Add text to input statements indicating what is expected.
example:
n = int(input('Enter number of items: ')
m = [int(i) for i in input('Enter the items : ').split()]
First statement:
n = int(input())
is not needed, and no need to terminate with -1 use instead:
for i in range(len(m)):
this code:
for i in range(n):
    if m[i] != -1:
        l.append(m[i])
is totally unnecessary, you already have the values in m
finally, you show your input, and actual output, but not your desired output which is important
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Am I wrong or is Udemy wrong? String Slicing! Mavoz 3 2,621 Nov-05-2022, 11:33 AM
Last Post: Mavoz
  python gives wrong string length and wrong character thienson30 2 3,043 Oct-15-2019, 08:54 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020