面试的一道编程题
本帖最后由 新手·ing 于 2017-4-25 19:13 编辑对给出的一串数字找出重复的数字和重复的次数~ arr =
dic = {}
for item in arr:
if item in dic.keys():
dic += 1
else:
dic = 1
print(dic)
哪个公司的{:10_245:} @ooxx7788 @lumber2388779 @gopythoner @冬雪雪冬
have a look ~ str1 = '12312245532432543508932743284724532098349320320676965765'
dict1 = {}
for i in str1:
if i not in dict1:
dict1 = 1
else:
dict1 += 1
for i, j in dict1.items():
if j > 1:
print('重复的数字%s有%s个'%(i, j)) a =
dic = {}
for i in a:
dic = a.count(i)
print(dic) 新手·ing 发表于 2017-4-25 19:12
哪个公司的
可以用count()函数
a =
dic = {}
for i in a:
dic = a.count(i)
print(dic) 冬雪雪冬 发表于 2017-4-25 19:24
{:10_275:} 冬雪雪冬 发表于 2017-4-25 19:24
或者这样:
str1 = '12312245532432543508932743284724532098349320320676965765'
list1 = []
for i in str1:
if i not in list1:
n = str1.count(i)
if n > 1:
print('重复数字%s共有%s个'%(i, n))
list1.append(i) 本帖最后由 ooxx7788 于 2017-4-28 10:52 编辑
def duplicate_count_num(nums):
if isinstance(nums, str):
return [(nums.count(c), c) for c in set(nums) if nums.count(c) > 1] # (次数,数字)
elif isinstance(nums, list):
return list(filter(lambda x: x != 1, zip(map(nums.count, set(nums)), set(nums))))# (次数,数字)
duplicate_count_num()
[(4, 1), (2, 2)]
str1 = '12312245532432543508932743284724532098349320320676965765'
duplicate_count_num(str1)
[(11, '2'), (3, '8'), (4, '0'), (10, '3'), (7, '5'), (4, '9'), (7, '4'), (4, '6'), (4, '7'), (2, '1')]
冬雪雪冬 发表于 2017-4-25 19:41
或者这样:
为啥可以这样写,not in list1,这个list字典不是明明是空值吗? def seacher(n):
y=[]
for i in n:
num=n.count(i)
if i not in y:
print("%s:%s次"%(i,num))
y.append(i)
seacher() {:10_249:}观看各路大神 美团 大家不用字典,不用count函数怎么写啊 willLin 发表于 2017-4-25 22:04
为啥可以这样写,not in list1,这个list字典不是明明是空值吗?
not in list1 是因为要给某个第一次出现的数字的次数赋值为1, 否则没有初始值 a =
count ={}.fromkeys(a, 0)
for i in a:
count += 1
print(count) willLin 发表于 2017-4-25 22:04
为啥可以这样写,not in list1,这个list字典不是明明是空值吗?
第一次循环是空值,后面会逐步append新的内容。 冬雪雪冬 发表于 2017-4-26 10:30
第一次循环是空值,后面会逐步append新的内容。
嗯嗯,谢谢,昨天debug了一下,明白了 本帖最后由 ButcherRabbit 于 2017-4-26 13:52 编辑
ad ="13245652135489761314567483213154875613124"
temp = []
for i in ad:
if ad.count(i) > 1 and i not in temp:
temp.append(i)
else:
continue
print(temp)
for each in temp:
print('重复数字%s,出现%d次'%(each, ad.count(each)))
ad ="13245652135489761314567483213154875613124"
temp = []
num1 = 0
for i in ad:
if i not in temp:
temp.append(i)
else:
continue
for i in temp:
for j in ad:
if j == i:
num1 += 1
if num1 > 1:
print('重复数字%s,出现%d次'%(i, num1))
else:
continue
num1 = 0
这道题目使用字典的方法很简单, 键对应数字, 次数对应值, 最后使用迭代器打印出次数超过1的那些键和值即可