Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A program in Python that prints the alphabet - except q and e - in lowercase and without a newline

Tags:

python

I need to write a program in Python that prints the alphabet in lowercase and without the newline. Other requirements:

* only use one print function with string format
* only use one loop in your code
* you are not allowed to store characters in a variable
* you are not allowed to import any module

Here's what I have so far:

#!/usr/bin/python3  



for alpha_letters in range(ord('a'), ord('z')+1):
    if alpha_letters == 'e' or alpha_letters == 'q':
       continue
    print("{:c}".format(alpha_letters), end="")

The output:

abcdefghijklmnopqrstuvwxyzvagrant:

As you can see, I'm able to print the alphabet without a newline, but the 'e' and 'q' are still being printed.

like image 915
Laney Fran Avatar asked Dec 01 '25 22:12

Laney Fran


1 Answers

You're mixing character code with character value. range yields codes, you're testing value. You'd need if alpha_letters == ord('e'): instead (ot if alpha_letters in [ord('e'),ord('q')]: to test for 2 letters.

So regardless of some ludicrious constraints, I'd do the following (without importing any magical module, storing the character value in a variable so I'm able to test it against its values not its code, and then no need for format):

for letter_code in range(ord('a'), ord('z')+1):
    letter = chr(letter_code)
    if letter not in "qe":
        print(letter, end="")

Although I notice that "you cannot import any module", it's better when you can get rid of range, since you can iterate on elements directly in python. Also when you need to test for 2 characters (your sample code doesn't try to test for q), you can do it with in and a string made of those characters

In an industrial context, I'd do this using string.ascii_lowercase constant:

import string
for alpha_letters in string.ascii_lowercase:
    if alpha_letters not in 'qe':
       print(alpha_letters, end="")  # no need for format: the format is already OK

or the list comprehension approach to directly generate a string (which you can print or use for something else):

"".join([alpha_letter for alpha_letter in string.ascii_lowercase if alpha_letter not in "qe"])

Performance purists would advise to create a set (set("qe")) beforehand to test on multiple values like this. This isn't necessary (and even slower) when you have only a few values to test.

like image 189
Jean-François Fabre Avatar answered Dec 04 '25 11:12

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!