2017-10-11 15 views
0

而异?我最近开始练习codefights,它应该是网上面试问题的一个很好的练习空间。附加到字典的键是否因蟒蛇机/ env

问题是,这是我在Python在字符串找到的第一个非重复字符的解决方案为一个简单的问题:

def firstNotRepeatingCharacter(s): 
    d = dict() 
    for i in range(len(s)): 
     key = s[i] 
     print d 
     if key in d: 
      d[key] += 1 
     else: 
      d[key] = 1 
    found = '_' 
    for key in d: 
     if d[key] == 1: 
      found = key 
      break 
    return found 

,当我在我的本地jupyter笔记本运行给我下面的输出:

firstNotRepeatingCharacter('abacabad') 

{} 
{'a': 1} 
{'a': 1, 'b': 1} 
{'a': 2, 'b': 1} 
{'a': 2, 'b': 1, 'c': 1} 
{'a': 3, 'b': 1, 'c': 1} 
{'a': 3, 'b': 2, 'c': 1} 
{'a': 4, 'b': 2, 'c': 1} 
Out[89]: 
'c' 

这太棒了。这就是答案。

但是运行上codefights ENV同样给出了一个错误: code fights output gives **'d'** because it gets added to the dictionary before.

所以我的问题的存在,我是一个Python菜鸟,在字典中追加它的键添加到任意地方还是在有条不紊时尚? 或者输出差异是因为jupyter noteboook和它们的在线编译器的python env有所不同。

+1

键在'dict'没有一个订单。由于Python 2.7有'collections.OrderedDict' –

回答

0

您可以使用collections.Counter来计算字符出现次数。

由于在dictionary have no order钥匙,你需要遍历字符串:

import collections 


def first_singleton(s): 
    counter = collections.Counter(s) 
    for c in s: 
     if counter[c] == 1: 
      return c 
    return None 

print(first_singleton('abacabad'))