所以我对Python很陌生,正在尝试创建一个程序来识别“超级字谜”,即具有相同第一个和最后一个字母的字谜。我想出了这个,而且它有效,但我有一种感觉,有一种更干净的方法可以做到这一点。有任何想法吗?干杯。
words = input('Enter words: ')
listed = words.split()
first = listed[0]
second = listed[1]
first_split = (list(first))
second_split = (list(second))
if first_split[0]==second_split[0] and first_split[-1]==second_split[-1]:
first_split_alpha = sorted(first_split)
second_split_alpha = sorted(second_split)
if first_split_alpha == second_split_alpha:
print('Super Anagram!')
else: print('Huh?')
else: print('Huh?')
1) 临时变量
listed
是不必要的。使用元组解包来获取值
2) 不需要使用
list
。 str
也是一个可迭代对象。
3)
_alpha
的使用是不必要的。只需在表达中使用 sorted(foo)
即可。
a,b = input('Enter words: ').split()
if sorted(a) == sorted(b) and a[0] == b[0] and a[-1] == b[-1]:
print('Super Anagram!')
else:
print('Huh?')
我提出的一个建议是检查输入是否恰好包含两个单词。如果用户只输入一个单词,您的代码将引发异常。您可以通过以下方式执行此操作:
words = [] # empty list
while len(words) != 2:
words = input('Enter two words: ').split()
接下来,您可以减少创建的不同变量的数量。如果您创建一个变量然后只使用它一次,那么您很可能可以内联对该变量所做的任何操作:
first = words[0]
second = words[1]
if (first[0] == second[0] and
first[-1] == second[-1] and
sorted(first) == sorted(second)):
print('Super Anagram!')
else:
print('Huh?')
我认为它就像@Rob
a,b = input('Enter words: ').split()
if sorted(a) == sorted(b) and a[0] == b[0] and a[-1] == b[-1]:
print('Super Anagram!')
else:
print('Huh?')