Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

One-liner to print two statements in a for-loop in one line

How can I write this code in one line? The concept is that you should:

  • get one input from the user and check if the (ASCII form of the character) – 97 is divisible by 2 or not
    • if yes, you should print the original form of the character
    • else, you should print the upper case form of the character.
  • last, you should reverse the answer.
  • Example, if the input is alexander, the output should be e e a a X R N L D
  • But it should be in one line and only one, I came up with a solution but it was 3 lines, I don’t know what to do next.

This is the code I came up with so far:

h = []
for i in input() : h.append(i.lower() if (ord(i) - 97) % 2 == 0 else i.upper())
print(*sorted(h, reverse=True))

The original code for the question, which you should convert to one line is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

input_string = str(input())
array = []
for i in range(len(input_string)):
    if (ord(input_string[i]) - 97) % 2 == 0:
        array.append(input_string[i])
    else:
        array.append(input_string[i].upper())
array.sort(reverse=True)
answer = ' '.join(array)
print(answer)

>Solution :

List comprehension (I did not check your code, only rewrite it):

h = []
for i in input() : h.append(i.lower() if (ord(i) - 97) % 2 == 0 else i.upper())
print(*sorted(h, reverse=True))

print(*sorted([i.lower() if (ord(i)-97)%2 == 0 else i.upper() for i in input() ], reverse=True))

To quote your question:

you should print the original form of the character

That is not what the code does at the moment, just saying so you are aware.

after reading your deleted comment:

And if you are wondering about the if and else in list comprehension:

You can put it in your list, but if that was your problem (the actual question apparently) then I would suggest to use google, there are plenty of examples where this is used.: if/else in a list comprehension, https://towardsdatascience.com/a-gentle-introduction-to-flow-control-loops-and-list-comprehensions-for-beginners-3dbaabd7cd8a, https://pythonguides.com/python-list-comprehension-using-if-else/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading