【发布时间】:2017-10-01 14:10:01
【问题描述】:
我通过命令行接受两个字符串。
我想要的是,
- 如果第一个字符串包含的 z 比第二个字符串多,则第一个字符串获胜。
如果他们有相同的号码 z 的,然后 y 最多的字符串获胜。
如果它们的 y 数量相同,则 x 的数量 确定获胜者等。
-
如果它们包含相同数量的z,y .... a,则为平局 而且没有赢家。
我本来打算做的是,
创建一个包含所有字母的字典并分配递增值,例如,
alphabets = dict(a=1, b=2, c=3, ... ,y=25, z=26)
并将其值乘以字母重复的次数。
For example, python myprogram.py zzza zzza
string1: zzza and string2: zzza
In string1, Z is repeated 3 times and a is repeated once.
In string2, Z is repeated 2 times, b and a is repeated once.
So, (26*3) + (2*1) and (26*2) + (2*1) + (1*1)
具有最大数量的字符串将获胜。但是,它并不总是给出正确的答案。 (string1: zzza and string2: zyyx 条件失败)
word1_count = {}
word2_count = {}
class FindWinner:
def __init__(self, word1, word2):
self.word1 = word1
self.word2 = word2
def check_conditions(self):
special_chars = set('[~!@#$%^&*.-()_+{}":;01234567989\']+$')
# check conditions
if special_chars.intersection(self.word1) or
special_chars.intersection(self.word2) or \
(len(self.word1) != len(self.word2) or ('no' in self.word1)
or ('no' in self.word2)) or (self.word1 == self.word2):
print('Invalid string.')
else:
print("String is valid")
for w1 in list(self.word1):
if w1 not in word1_count:
word1_count[w1] = 1
else:
word1_count[w1] += 1
for w2 in list(self.word2):
if w2 not in word2_count:
word2_count[w2] = 1
else:
word2_count[w2] += 1
# print(word1_count, word2_count)
merged_data = [[k, word1_count.get(k, 0), word2_count.get(k, 0)] for k in word1_count.keys() | word2_count.keys()]
print(merged_data)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("word1", help="First word")
parser.add_argument("word2", help="Second word")
args = parser.parse_args()
c1 = FindWinner(args.word1, args.word2)
c1.check_conditions()
if __name__ == "__main__":
main()
输入:
python myprogramm.py qwwweq asdnnn
输出:
String is valid
{'e': 1, 'q': 2, 'w': 3} {'d': 1, 'a': 1, 'n': 3, 's': 1} # merged_data
应该采用什么方法? 谢谢
【问题讨论】:
-
嘿@batMan,我不确定你在说什么。
标签: string python-3.x dictionary