【python】判断一个字符串是否包含重复字符?

Python018

【python】判断一个字符串是否包含重复字符?,第1张

题目:判断一个字符串是否包含重复字符。例如good则包含,abc则不包含

分析:哈希法。

code:

(1)

strs = 'Good'

hashTable = dict()

listStrs = list(strs)

i = 0

while i <len(strs):

    if listStrs[i] in hashTable:

        print("有重复字符")

        break

    else:

        hashTable[listStrs[i]] = None

    i += 1

    if i >= len(strs):

        print("没用重复字符")

        break

程序运行结果:

有重复字符

(2)

def longest_repetition(chars):

    if len(chars) is None or len(chars) <= 1:

        return (chars, len(chars))

    result = [1] * len(chars)

    for left in range(len(chars) - 1):

        for right in range(left + 1, len(chars)):

            if chars[left] == chars[right]:

                print("a")

                result[left] += 1

            else:

                print("aa")

                break

    #return result

    return (chars[result.index(max(result))], max(result))

if __name__ == "__main__":

    txt = 'banaaana'

    print(longest_repetition(txt))

题目:给定由字母组成的字符串s1和s2,其中,s2中字母的个数少于s1,如何判断s1是否包含s2?

分析:哈希法。

code:

str1 = 'aaaabbce'

str2 = 'abcbbaaad'

list1 = list(str1)

list2 = list(str2)

i = 0

hashTable1 = dict()

while i <len(str1):

    if list1[i] not in hashTable1:

        hashTable1[list1[i]] = 0

    i += 1

i = 0

hashTable2 = dict()

while i <len(str2):

    if list2[i] not in hashTable2:

        hashTable2[list2[i]] = 0

    i += 1

count = 0

for k, v in hashTable1.items():

    if k in hashTable2:

        count += 1

    else:

        print("不包含")

        break

程序运行结果:

不包含

1.使用series.unique() 发现其长度为18

而使用describe()中的count 或者dingdan_df['driver_phone'].value_counts()时为17个value,原因是后两者仅统计非空的值。

查找:

unique()得到的为一个ndarray,从而无法直接用list中的if np.nan in test1:来判断。

list求并交差:

http://blog.chinaunix.net/uid-200142-id-3992553.html

2.dictionary转DataFrame

dict.items()为一个dict_items类型的对象,需要转为list再传入,同时指定列名

gongdan_users=pd.DataFrame(list(gongdan_dic.items()),columns=['driver_phone','counts'])