【问题标题】:CS circles Coding Exercise: 26 LettersCS 圆圈编码练习:26 个字母
【发布时间】:2019-08-02 08:23:30
【问题描述】:

这个编码练习给我带来了很多麻烦,我需要帮助。

这就是问题所在。

编写一个与上面示例相反的程序:它应该 以一个字符为输入,输出对应的数字(介于 1 和 26)。你的程序应该只接受大写字母。作为 错误检查,如果输入不是大写字母则打印无效。

这是我目前所拥有的。

inp = input()

if (len(inp) > 1 or inp != inp.upper()):
    print("invalid input")

else:
    print(ord(inp)-ord("A")+1)

【问题讨论】:

  • 您当前的解决方案有什么问题?
  • 输入:@程序执行没有崩溃。程序输出:0 --------------------当输入@符号时,它不会打印无效预期这个正确的输出:无效评分结果:您的输出不是正确。

标签: python computer-science


【解决方案1】:

正如评论中所阐明的,问题似乎是验证没有涵盖足够的案例。

要检查您计算的数字是否为有效的大写字符,您只需检查它是否在 1 到 26 之间:

if 1 < ord(inp) - ord("A") + 1 < 26:
    print(ord(inp) - ord("A") + 1)
else:
    print("Invalid input")

将此添加到您当前的验证中:

inp = input()

if (len(inp) > 1 or inp != inp.upper() or 
    ord(inp) - ord("A") + 1 < 1 or ord(inp) - ord("A") + 1 > 26):
    print("invalid input")

else:
    print(ord(inp)-ord("A")+1)

【讨论】:

  • 嗨@Harpoonfever,如果这个或任何答案已经解决了您的问题,请考虑通过单击复选标记接受它。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。 (meta.stackexchange.com/questions/5234/…)
【解决方案2】:

这可能会对你有所帮助。

将您想要测试的任何内容添加到test_data 列表中。

# take advantage of the string module to get a string of all upper-case characters
from string import ascii_uppercase # equiv of 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

test_data = ['z', 'AB', '', 10, None, "@", *ascii_uppercase] # some test data including all the upper-case characters

for item in test_data:
    string = str(item) # turn the item into type str
    length_is_one = len(string) == 1 # get the length
    if all((length_is_one, string in ascii_uppercase)): # if all these are true
        print(ascii_uppercase.index(item) + 1) # print the index of the letter + 1
    else:
        print(f'"{item}" is {INVALID}') # I modified the invalid output

输出:

"z" is invalid
"AB" is invalid
"" is invalid
"10" is invalid
"None" is invalid
"@" is invalid
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

【讨论】:

    【解决方案3】:
    letter = input()
    
    if letter>='A' and letter<='Z':
       
       print(int(ord(letter))-64)
    
    else:
    
       print('invalid')
    

    【讨论】:

    • 代码在附有解释时会更有帮助。 Stack Overflow 是关于学习的,而不是提供 sn-ps 来盲目复制和粘贴。请edit您的问题并解释它如何回答所提出的具体问题。见How to Answer
    猜你喜欢
    • 1970-01-01
    • 2017-01-25
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    相关资源
    最近更新 更多