from __future__ import division
# ^- so that 3/2 is 1.5 not 1
def averages( lst ):
it = iter(lst) # Get a iterator over the list
first = next(it)
for item in it:
yield (first+item)/2
first = item
print list(averages(range(1,11)))
# [1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]
from itertools import tee, izip
def average(iterable):
"s -> (s0,s1)/2.0, (s1,s2)/2.0, ..."
a, b = tee(iterable)
next(b, None)
return ((x+y)/2.0 for x, y in izip(a, b))
import itertools
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return itertools.izip(a, b)
def pair_averages(seq):
return ( (a+b)/2 for a, b in pairwise(seq) )
>>> a = range(10)
>>> sum(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del sum
>>> sum(a)
45
n = int(input("Enter the length of array: "))
list1 = []
for i in range(n):
list1.append(int(input("Enter numbers: ")))
print("User inputs are", list1)
list2 = []
for j in range(0, n-1):
list2.append((list1[j]+list1[j+1])/2)
print("result = ", list2)
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sm = sum(a[0:len(a)]) # Sum of 'a' from 0 index to 9 index. sum(a) == sum(a[0:len(a)]
print(sm) # Python 3
print sm # Python 2
# If you are given a list
numList = [1,2,3,4,5,6,7]
# and you are asked to find the number of three sums that add to a particular number
target = 10
# How you could come up with the answer?
from itertools import permutations
good_permutations = []
for p in permutations(numList, 3):
if sum(p) == target:
good_permutations.append(p)
print(good_permutations)
s = lambda l: [(l[0]+l[1])/2.] + s(l[1:]) if len(l)>1 else [] #assuming you want result as float
s = lambda l: [(l[0]+l[1])//2] + s(l[1:]) if len(l)>1 else [] #assuming you want floor result
第二个问题也使用匿名函数(aka。Lambda函数):
p = lambda l: l[0] + p(l[1:]) if l!=[] else 0
这两个问题组合在一行代码中:
s = lambda l: (l[0]+l[1])/2. + s(l[1:]) if len(l)>1 else 0 #assuming you want result as float
s = lambda l: (l[0]+l[1])/2. + s(l[1:]) if len(l)>1 else 0 #assuming you want floor result
message = "This is a global!"
def main():
global message
message = "This is a local"
print(message)
main()
# outputs "This is a local" - From the Function call
print(message)
# outputs "This is a local" - From the Outer scope
这个概念被称为阴影
在Python中对数字列表求和
nums = [1, 2, 3, 4, 5]
var = 0
def sums():
for num in nums:
global var
var = var + num
print(var)
if __name__ == '__main__':
sums()