Funktioniert für [-999999,.....,-2,-1,0,1,2,.......,999999]
Code: Alles auswählen
def multiplication(a,b):
if b>=0:
return sum(a for _ in range(b))
elif a<0 and b<0:
return sum(-a for _ in range(-b))
else:
return sum(b for _ in range(a))
Code: Alles auswählen
def multiplication(a,b):
if b>=0:
return sum(a for _ in range(b))
elif a<0 and b<0:
return sum(-a for _ in range(-b))
else:
return sum(b for _ in range(a))
Was willst du damit sagen? Dass es für alle ganzen Zahlen funktioniert?fail hat geschrieben:Funktioniert für [-999999,.....,-2,-1,0,1,2,.......,999999]
Code: Alles auswählen
def multiplication(a,b):
return a/(1/b)
Als Fingerübung kann man auch gleich die Addition mittels Bitoperatoren mit umsetzen. Interessant dürften da AND (&) und XOR (^) sein.BlackJack hat geschrieben:@fail: Es gibt übrigens noch eine effizientere Methode die mit Bit-Verschiebungen und Addition auskommt. Also die Operatoren ``<<``, ``>>``, und ``+``.
Code: Alles auswählen
from functools import reduce
def addition(a,b):
a = list(map(int,list(bin(a)[2:])))
b = list(map(int,list(bin(b)[2:])))
remainder = 0
resultat=[]
for c in reversed(range(max(len(a),len(b)))):
resultat.append(adder(get(a,c),get(b,c),remainder)[0])
remainder=adder(get(a,c),get(b,c),remainder)[1]
return bin2dec(list(reversed(resultat)))
def adder(a,b,cin):
s=cin ^ a ^ b
cout=(a&b)| (cin&(a^b))
return s,cout
def get(von,das):
try:
return von[das]
except IndexError:
return 0
def bin2dec(binary):
return reduce(lambda acc,y: acc*2 + y,binary)
Code: Alles auswählen
def add(a, b):
while True:
a, b = a ^ b, b & a
if b == 0:
return a
b <<= 1
Code: Alles auswählen
def add(a, b):
if a == -b:
return 0
if a < b:
a, b = b, a
if a > 0 and b < 0:
if -b < a:
return -add(-a, -b)
while True:
a, b = a ^ b, b & a
if b == 0:
return a
b <<= 1
Code: Alles auswählen
add = lambda a, b: a - (-b)
Code: Alles auswählen
>>> a, b = 23, 42
>>> a--b
65
Und woher soll Python dann wissen, ob nicht (a-)-b gemeint war????derdon hat geschrieben:Die Klammern sind überflüssig:
Code: Alles auswählen
>>> a, b = 23, 42 >>> a--b 65
Code: Alles auswählen
n [86]: (a-)-b
File "<ipython-input-86-e4fa2a309856>", line 1
(a-)-b
^
SyntaxError: invalid syntax
Ok, Abkürzungen gelten nicht:nomnom hat geschrieben:@jerch: Du benutzt doch in deinem Code ständig "-", das ist doch unfair :p Dann geht auchCode: Alles auswählen
add = lambda a, b: a - (-b)
Code: Alles auswählen
ZERO = 0
ONE = 1
# simple 1 testing
def is_one(a):
return ONE if a==ONE else ZERO
# xor equal testing
def equal(a, b):
return is_one(((a^b) << ONE) | ONE)
# testing for zero (lazy version with using equal)
def is_zero(a):
return equal(a, ZERO)
# simple incrementor
def inc(a):
if equal(a, ~ZERO):
return ZERO
b = ONE
while ONE:
if is_zero(b):
return a
a, b = a^b, (a&b) << ONE
# negativate number: positive to negative and negative to positive
def neg(a):
if is_zero(a):
return a
return inc(~a)