Ich kann mir nicht erklären, weshalb die Funktion strings ausschließt. Ist halt so oder gibt es gute Gründe dafür?sum.__doc__ hat geschrieben:Returns the sum of a sequence of numbers (NOT strings)...
mutetella
Ich kann mir nicht erklären, weshalb die Funktion strings ausschließt. Ist halt so oder gibt es gute Gründe dafür?sum.__doc__ hat geschrieben:Returns the sum of a sequence of numbers (NOT strings)...
Code: Alles auswählen
class nostring(object):
def __init__(self, s):
self.s=s
def __add__(self, other):
return self.s+other
print sum([' ','nimmt',' ','Strings','!'],nostring('sum'))
# > 'sum nimmt Strings!'
Code: Alles auswählen
def summe(seq):
seq=iter(seq)
return sum(seq,seq.next())
Code: Alles auswählen
def timer(func, arg, calls):
results = []
for c in xrange(calls):
start = time.time()
func(arg)
stop = time.time()
results.append(stop - start)
print 'best result of {0} calls: {1}'.format(calls, min(results))
def numeric_sum(iterable):
result = 0
for n in iterable:
result += n
return result
def string_sum(iterable):
result = ''
for n in iterable:
result += n
return result
strings = [s for s in 100000*'a String']
numerics = [int(n) for n in 100000*'512']
Code: Alles auswählen
>>> timer(string_sum, strings, 30)
best result of 30 calls: 0.0892150402069
>>> timer(''.join, strings, 30)
best result of 30 calls: 0.0157160758972
>>> timer(numeric_sum, numerics, 30)
best result of 30 calls: 0.0150220394135
Code: Alles auswählen
#same as above...
strings = []
numerics = []
for i in xrange(100000):
strings.append('a String')
numerics.append(512)
Code: Alles auswählen
>>> timer(string_sum, strings, 30)
best result of 30 calls: 0.0110540390015
>>> sumtime.timer(''.join, strings, 30)
best result of 30 calls: 0.00193405151367
>>> timer(numeric_sum, numerics, 30)
best result of 30 calls: 0.00498700141907
>>> timer(sum, numerics, 30)
best result of 30 calls: 0.000773906707764
Code: Alles auswählen
strings = ["a string"]*100000
numerics = [512]*100000
Dann pass bei der Verwendung auf.mutetella hat geschrieben:Dagegen finde ich ein ['a'] * 10 schon 'ne andere Sache, begegnet man (ich?) nicht jeden Tag...
Code: Alles auswählen
>>> data = [[0]] * 10
>>> data[0][0] = 1
>>> data
[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
Code: Alles auswählen
>>> chr(ord("a") + ord("b"))
'\xc3'