Вот код, который может быть вам полезен. Код выглядит следующим образом. Это довольно очевидно. Но я добавлю подробное объяснение, если оно покажется вам сложным.
public static int printSequence(int n) {
return printSequence(1, n); //start printing upper triangle (1 to n)
}
public static int printSequence(int currentNumber, int lastNumber){
for (int i = 1; i <= currentNumber; i++)
System.out.print(i);
System.out.println();
if(currentNumber<lastNumber) //if in upper triangle
return printSequence(currentNumber+1, lastNumber);
if(currentNumber>lastNumber) //if in lower triangle
return printSequence(currentNumber-1, lastNumber);
if(currentNumber==lastNumber) { //if the end of a triangle is reached
if(lastNumber==1) { //if the end of lower triangle is reached, exit the method
return 0;
} else {
return printSequence(lastNumber-1, 1); //if the end of upper triangle is reached, start the lower triangle ( n-1 to 1)
}
}
return 0;
}
import operator
tuple(map(operator.add, a, b))
Используя все созданные-ins..
tuple(map(sum, zip(a, b)))
Вид объединенных первые два ответа, с тонкой настройкой к коду ironfroggy так, чтобы это возвратило кортеж:
import operator
class stuple(tuple):
def __add__(self, other):
return self.__class__(map(operator.add, self, other))
# obviously leaving out checking lengths
>>> a = stuple([1,2,3])
>>> b = stuple([3,2,1])
>>> a + b
(4, 4, 4)
Примечание: использование self.__class__
вместо stuple
для упрощения разделения на подклассы.
from numpy import *
a = array( [1,2,3] )
b = array( [3,2,1] )
print a + b
дает array([4,4,4])
.
Да. Но Вы не можете переопределить встроенные типы. Необходимо разделить их на подклассы:
class MyTuple(tuple): def __add__(self, other): if len(self) != len(other): raise ValueError("tuple lengths don't match") return MyTuple(x + y for (x, y) in zip(self, other))
простое решение без определения класса, который возвращает кортеж
import operator
tuple(map(operator.add,a,b))