字符串count python_在python中,为什么字符串.count()比循环快?

下面是一些timeit代码,显示了各种方法的速度,使用了所有4个密钥计数相等的完美数据和每个密钥数量大致相等的随机数据。在#!/usr/bin/env python3

''' Test speeds of various algorithms that check

if a sequence of U, D, L, R moves make a closed circle.

See https://stackoverflow.com/q/46568696/4014959

Written by PM 2Ring 2017.10.05

'''

from timeit import Timer

from random import seed, choice, shuffle

from collections import Counter, defaultdict

def judge_JH0(moves):

l = r = u = d = 0

for i in moves:

if i == 'L':

l += 1

if i == 'D':

d += 1

if i == 'R':

r += 1

if i == 'U':

u += 1

return ((l-r) == 0) and ((u-d) == 0)

def judge_JH1(moves):

l = r = u = d = 0

for i in moves:

if i == 'L':

l += 1

elif i == 'D':

d += 1

elif i == 'R':

r += 1

elif i == 'U':

u += 1

return (l == r) and (u == d)

def judge_count(moves):

return ((moves.count('R') == moves.count('L')) and

(moves.count('U') == moves.count('D')))

def judge_counter(moves):

d = Counter(moves)

return (d['R'] == d['L']) and (d['U'] == d['D'])

def judge_dict(moves):

d = {}

for c in moves:

d[c] = d.get(c, 0) + 1

return ((d.get('R', 0) == d.get('L', 0)) and

(d.get('U', 0) == d.get('D', 0)))

def judge_defdict(moves):

d = defaultdict(int)

for c in moves:

d[c] += 1

return (d['R'] == d['L']) and (d['U'] == d['D'])

# All the functions

funcs = (

judge_JH0,

judge_JH1,

judge_count,

judge_counter,

judge_dict,

judge_defdict,

)

def verify(data):

print('Verifying...')

for func in funcs:

name = func.__name__

result = func(data)

print('{:20} : {}'.format(name, result))

print()

def time_test(data, loops=100):

timings = []

for func in funcs:

t = Timer(lambda: func(data))

result = sorted(t.repeat(3, loops))

timings.append((result, func.__name__))

timings.sort()

for result, name in timings:

print('{:20} : {}'.format(name, result))

print()

# Make some data

keys = 'DLRU'

seed(42)

size = 100

perfect_data = list(keys * size)

shuffle(perfect_data)

print('Perfect')

verify(perfect_data)

random_data = [choice(keys) for _ in range(4 * size)]

print('Random data stats:')

for k in keys:

print(k, random_data.count(k))

print()

verify(random_data)

loops = 1000

print('Testing perfect_data')

time_test(perfect_data, loops=loops)

print('Testing random_data')

time_test(random_data, loops=loops)

典型输出

^{pr2}$

这些计时是在我的旧的2GHz 32位机器上获得的,该机器在Linux上运行Python3.6.0。在

这里还有几个函数。在def judge_defdictlist(moves):

d = defaultdict(list)

for c in moves:

d[c].append(c)

return (len(d['R']) == len(d['L'])) and (len(d['U']) == len(d['D']))

# Sort to groups in alphabetical order: DLRU

def judge_sort(moves):

counts = [sum(1 for _ in g) for k, g in groupby(sorted(moves))]

return (counts[0] == counts[3]) and (counts[1] == counts[2])

judge_defdictlist比judge_defdict慢,但比judge_JH1快,当然它比judge_defdict使用更多的内存。在

judge_sort比judge_JH0慢,但比judge_dict快。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值