Python中的一种程序,它以小写形式打印字母表(q和e除外),并且不带换行符
我需要用Python编写一个程序,用小写字母打印字母表,不带换行符。其他要求:Python中的一种程序,它以小写形式打印字母表(q和e除外),并且不带换行符,python,Python,我需要用Python编写一个程序,用小写字母打印字母表,不带换行符。其他要求: * 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 以下是我目前掌握的情况: #!/usr/bin/pyth
* 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
以下是我目前掌握的情况:
#!/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="")
输出:
abcdefghijklmnopqrstuvwxyzvagrant:
正如你所看到的,我可以不换行地打印字母表,但“e”和“q”仍在打印中。你将字符代码与字符值混合在一起<代码>范围生成代码,您正在测试值。如果阿尔法字母==ord('e'):(ot
如果阿尔法字母在[ord('e')、ord('q')]中):
测试两个字母
因此,不管有什么荒谬的限制,我都会做以下事情(不导入任何神奇的模块,将字符值存储在变量中,这样我就可以根据它的值而不是它的代码来测试它,然后就不需要格式
):
虽然我注意到“您不能导入任何模块”,但最好是去掉范围,因为您可以直接在python中迭代元素。此外,当您需要测试2个字符时(您的示例代码不尝试测试q
),您可以使用中的和由这些字符组成的字符串来完成
在工业环境中,我会使用string.ascii_lowercase
常量:
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
或者使用列表理解方法直接生成字符串(可以打印或用于其他内容):
性能纯粹主义者建议事先创建一个集合(集合(“qe”)
)来测试这样的多个值。当只有几个值要测试时,这是不必要的(甚至更慢)。如果要使用相同的代码,请像这样更改If条件
if alpha_letters in [101,113]:
我不知道你能把字母表打印成那样,这段代码在将来的拼图游戏中肯定会派上用场
这是一条涵盖所有标准的单行线(我认为):
我使用了列表理解,Jean-Francois Fabre使用“qe”作为字符串(我本来打算使用一个列表,但这个要小得多),以及上面的ord/格式技巧
编辑:
我意识到我上面的代码使用了两次字符串格式化程序。下面是另一个版本,稍微长一点,不太好看,但只使用了一次字符串格式化程序:
print(*["%c" % a for a in range(ord('a'),ord('z')+1) if a not in (ord('q'),ord('e'))],sep='',end='')
我猜您正在同时使用ASCII和直接字符比较的概念:
您完全可以选择ASCII:
for alpha_letters in range(ord('a'), ord('z')+1):
if ord(alpha_letters) ==101 or ord(alpha_letters) == 113:
continue
print("{:c}".format(alpha_letters), end="")
您可以使用比较:
for alpha_letters in range(97, 122):
if alpha_letters == ord(e) or alpha_letters == ord(q):
continue
print("{:c}".format(alpha_letters), end="")
此外,我觉得输出应该是:abcdefghijklmnopqrstuvwxyz
没有额外的流浪汉跟随你的输出。
这是我对这种情况的看法。我非常怀疑您的输出是否以“流浪者”结尾!
print(*["%c" % a for a in range(ord('a'),ord('z')+1) if a not in (ord('q'),ord('e'))],sep='',end='')
for alpha_letters in range(ord('a'), ord('z')+1):
if ord(alpha_letters) ==101 or ord(alpha_letters) == 113:
continue
print("{:c}".format(alpha_letters), end="")
for alpha_letters in range(97, 122):
if alpha_letters == ord(e) or alpha_letters == ord(q):
continue
print("{:c}".format(alpha_letters), end="")