Python Forum
List comprehensions-Wrong result
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List comprehensions-Wrong result
#1
Hi,
I don't understand why this code that I have write didn't work:
if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())

new_list =[ [a,b,c] for a in range (0,x +1) for b in range (0,y +1) for c in (0,z +1) if a+b+c != n] 
print(new_list) 
Result :

[[0, 0, 0], [0, 1, 0], [0, 1, 2], [1, 0, 0], [1, 0, 2], [1, 1, 2]]
Correct result:

[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]
Regards,
Ravcoder
Reply
#2
what are the values of x, y, z and n when you run the code? And how you define the correct output? i.e. not example but in plain English
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
the values of input are this:
1
1
1
2
Instead for the output because I'm following an exercise that tells you what the correct output should be.
Reply
#4
look at the part for c in (0,z +1). You need it to be for c in range(0,z +1)
As it is now c will take values of 0 and 2
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
My mistake I had not seen that I had not set range, thanks now it works !!!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Am I wrong or is Udemy wrong? String Slicing! Mavoz 3 2,385 Nov-05-2022, 11:33 AM
Last Post: Mavoz
  convert this List Comprehensions to loop jacklee26 8 1,418 Oct-21-2022, 04:25 PM
Last Post: deanhystad
  set.difference of two list gives empty result wardancer84 4 1,433 Jun-14-2022, 01:36 PM
Last Post: wardancer84
  Are list/dict comprehensions interpreted really sequentially? anata2047 3 1,412 May-31-2022, 08:43 PM
Last Post: Gribouillis
  Noob Alert! Wrong result using loop and if statemnent GJG 7 2,794 Dec-19-2020, 05:18 PM
Last Post: buran
  list sum gives unexpected result Nesso 0 1,668 Feb-04-2020, 08:31 AM
Last Post: Nesso
  Dictionary and tuples list comprehensions help paul41 2 2,357 Nov-29-2019, 06:59 PM
Last Post: perfringo
  python gives wrong string length and wrong character thienson30 2 2,940 Oct-15-2019, 08:54 PM
Last Post: Gribouillis
  weird result trying to remove numbers from a list Exsul 6 3,364 Aug-27-2019, 05:10 AM
Last Post: perfringo
  Example of list comprehensions doesn't work Truman 17 10,714 May-20-2018, 05:54 AM
Last Post: buran

Forum Jump:

User Panel Messages

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