11 AnswersNew Answer
#4 print first n even numbers in reverse order n= int(input()) num= 0 x= 0 listt=  while n>x: if num%2==0: listt.append(str(num)) x+=1 num+=1 listt= listt.reverse() #for loop is working fine but using while loop it is creating a problem #sample input- 5 #desired output- 8,6,4,2,0
1/24/2022 4:31:06 AMShaurya Agarwal
11 AnswersNew Answer
n= int(input()) num= 2 #debug listt=  while n>0: listt.append(num) n-=1 num+=2 listt.reverse() print(listt)
This just indicates that the `reverse` method does not return anything. It only modifies the existing list. It does not return an updated list. Don't bother doing listt = listt.reverse(). If you just want to reverse a list, do listt.reverse() to modify your listt. listt.reverse() print(listt)
Now solve this problem without the extra variable num ☺️
Thanks to all for your help 🙏🙏
Brian, great example with bitwise operation 👍, but it's easy ☺️. Try all the same to print the n-th number of even numbers. Example: input 5 output 10,8,6,4,2
Shaurya Agarwal the description says to print them in reverse order, but the #desired output shows them in forward order. Which is correct?
n = int(input()) # If n is odd, force n to next lower even. if n&1: n -= 1 #now only even numbers will print while n>0: print(n, end=',') n -= 2 print(n) #final 0 without comma
Solo oops, I missed that detail. Okay, it is easily corrected with the same loop, only a different adjustment to n. #print the first n even Natural numbers in reverse order n = int(input()) n = 2*(n - 1) while n>0: print(n, end=',') n -= 2 print(n) #final 0 without comma
Solo thanks bro! I know there is debate about whether 0 is even, so I included it only because the OP did. There is also debate about whether 0 belongs in the Natural number set. I decided to adopt it in that set in my comment because it is the only difference that would distinguish Natural numbers from Counting numbers. On the other hand, 0 is most unnatural!
Brian, yes, you did it. 👏👏👏 Except 0 is not an even number ☺️.
Sololearn Inc.535 Mission Street, Suite 1591
Send us a message