برنامهی پیدا کردن جملهی nام بسط ۲ جملهای:
#!/usr/bin/python
def GetSen(i, num):
n = i
k = num - 1
s = n - k
z = Combination(n, k)
if z == 1:
z = ''
out='{z}a^{s} * b^{k}'.format(z=z,n=n,s=s,k=k)
return out
def Factorial(number):
if number < 0:
raise ValueError('number must be higher than zero.')
elif number > 1:
return number * Factorial(number - 1)
else:
return 1
def Combination(n, k):
return Factorial(n) / (Factorial(k) * (Factorial(n - k)))
def GetFinnalSen(i):
finnal = ''
for num in range(1, i + 1):
finnal = finnal + GetSen(i, num) + ' + '
finnal = finnal + GetSen(i, i + 1)
return finnal
def OptSen(sen):
if sen.count('^0'):
s = sen.find('^0') - 1
d = sen[s:s+3]
sen = sen.replace(d, '')
if sen.count(' '):
sen = sen.replace(' ', ' ')
if sen.count('* +'):
s = sen.find('* +')
d = sen[s:s+3]
sen = sen.replace(d, ' + ')
if sen.count('+ *'):
s = sen.find('+ *')
d = sen[s:s+3]
sen = sen.replace(d, ' + ')
if sen.count('* *'):
s = sen.find('* *')
d = sen[s:s+3]
sen = sen.replace(d, ' * ')
if sen.count('^1'):
s = sen.find('^1')
d = sen[s:s+2]
sen = sen.replace(d, '')
return sen
def GetSentence(power):
power = int(power)
if power == 0:
return '1'
finnal = GetFinnalSen(power)
for x in range(0, finnal.count('') - 1):
finnal = OptSen(finnal)
return finnal
def InitSen(a, b, sen):
pass
if __name__ == '__main__':
import sys
try:
n = sys.argv[1]
except IndexError:
print 'Error: Give a Number!!!'
exit()
n = int(n)
print '(a + b)^' + str(n) + ' = ' + GetSentence(n)
طرز استفاده:./(File Name) (number)
(دادن توان بصورت آرگومان)