Binomial newton (a-b)^n(Python) - python

I need help with the code for the Newton's binomial.I attach the code that outputs the binomial (x + y)^n,and I need to write the code for (x-y)^n.How to write this alternation in the code?
def fact(m):
f = 1
for i in range(1,m+1):
f = f*i
return f
def koef(n,k):
x = fact(n)
y = fact(k)
c = fact(n-k)
return x//(y*c)
print("Enter n:")
n = int(input())
k = 0
while k <= n:
print(koef(n,k),"*x^",n-k,"*y^",k,sep = '', end = '')
k = k+1
if k <= n:
print(" + ",end = '')
The binomial that outputs this code:
n = 10
x^10+10x^9y+45x^8y^2+120x^7y^3+210x^6y^4+252x^5y^5+210x^4y^6+120x^3y^7+45x^2y^8+10x*y^9+y^10
The bean I need to display:
n = 10
x^10-10x^9y+45x^8y^2-120x^7y^3+210x^6y^4-252x^5y^5+210x^4y^6-120x^3y^7+45x^2y^8-10x*y^9+y^10

What you need is to alternate + and - depending on the parity of k. You can do it in a number of ways but one that comes to mind is the following:
if k <= n:
operation = '+-'[k % 2] # + on even, - on odd
print(' ' + operation + ' ', end=' ')
you may also use format string:
if k <= n:
operation = '+-'[k % 2] # + on even, - on odd
print(f' {operation} ', end=' ')

Related

Adding numbers in python and in line using function recursion

Hey guys I have a code like this
def add_sum(n):
numStr = str(n)
sum = 0
for i in range(len(num_str)):
sum += int(numStr[])
return sum
print(add_sum(546))
I want the answer to be this way.
output: 5 + 4 + 6 = 15
How can I make this work for me?
add_sum = lambda number: sum([int(x) for x in str(number)])
If you wanna do it the string conversion way
Edit: I assume you were referring to the loop, when you mentioned "recursion"?
If you want to loop over digits of a number, you can also use module 10 and divide the number each time.
A solution with recursion that does not convert int to str (which is kind of an expensive operation):
def add_sum(n):
return 0 if n == 0 else n % 10 + add_sum(n // 10)
If you prefer a solution without recursion:
def add_sum(n):
result = 0
while n != 0:
result += n % 10
n //= 10
return result
If you want to convert int to str:
def add_sum(n):
return sum(map(int, str(n)))
You can try this non-recursive code.
def add_sum(n):
temp = list(str(n))
ans = 0
for i in temp:
ans += int(i)
print(f"{' + '.join(temp)} = {ans}")
for i in range(3):
num = int(input())
add_sum(num)
Output:
546
5 + 4 + 6 = 15
258
2 + 5 + 8 = 15
6985
6 + 9 + 8 + 5 = 28
You can try this
def add_sum(n):
numStr = str(n)
sum1 = 0
for i in range(len(numStr)):
sum1 += int(numStr[i])
return ' + '.join([str(x) for x in n]),sum1
i,j=add_sum('546')
print(i,'=',j)
This also works
def add(num):
num_ = str(num)
if (len(num_) == 1):
return int(num)
else:
x = add(num_[1:])
return (x + int(num_[0]))
def add_sum(n):
numStr = str(n)
sum = 0
for i in range(len(numStr)):
sum += int(numStr[i])
return sum
print(add_sum(546))
This is the correct version of your code!
You can use your function With recursion like this!
def add_sum(n, sum=0):
if n == 0:
return sum
else:
sum += n % 10
return add_sum(int(n/10), sum)
print(add_sum(546))
here you go! sol. with recursion
def add_sum(n, sum=0, orignal=0):
if n == 0:
return(f"{orignal} => {' + '.join(str(orignal))} = {sum}")
elif orignal == 0:
orignal = n
sum += n % 10
else:
sum += n % 10
return add_sum(int(n/10), sum, orignal)
print(add_sum(54236))
Output:
54236 => 5 + 4 + 2 + 3 + 6 = 20

function that prints counding down numbers and up but in a pattern

I already know how to count down and up using reccurssive function but I cant figure out how to define another function to have spaces in a pattern like this:
Desired output
My code for counting down and up:
def f(n):
if n==0:
print (n)
return
print (n)
f(n-1)
print (n)
a = 5 #you can take any value, it will be actually taken from the user
def f(n):
global a
if n == 0:
print(' '*a + str(n))
return
print(' '*(a-n), + str(n))
f(n-1)
print(' '*(a-n), + str(n))
a = int(input())
f(a)
I am posting this to contrast the other answers provided here -
def f(n, s = ""):
if n <= 0:
print(s, n)
else:
print(s, n)
f(n - 1, s + " ")
print(s, n)
f(5)
5
4
3
2
1
0
1
2
3
4
5
The program could be further simplified, if desired -
def f(n, s = ""):
print(s, n)
if n > 0:
f(n - 1, s + " ")
print(s, n)
f(5)
Default parameter s could be an integer instead of a string, if desired -
def f(n, s = 0):
print(" "*s, n)
if n > 0:
f(n - 1, s + 1)
print(" "*s, n)
f(5)
Output is the same.
print adds a space between the printed arguments. To remove this, we can print a single formatted value -
def f(n, s = ""):
print(s + str(n)) # <- single value
if n > 0:
f(n - 1, s + " ")
print(s + str(n)) # <- single value
Or you can use a formatted string literal -
def f(n, s = ""):
print(f"{s}{n}") # <- formatted string
if n > 0:
f(n - 1, s + " ")
print(f"{s}{n}") # <- formatted string
This is probably not exactly what you need. But it gives you an idea :)
As you can see it is based on #Samudra Ganguly's answer
def f(n,x):
if n < 0:
return
p(n,x-n)
f(n-1,x)
if n !=0:
p(n,x-n)
def p(m,x):
print(" ", end = "")
if x>0:
p(m,x-1)
else:
print(m, end = "\n")
f(8,8)
Also you can change the function like this:
k=4;
def f(n):
if n < 0:
return
p(n,k-n)
f(n-1)
if n !=0:
p(n,k-n)
def p(m,x):
print(" ", end = "")
if x>0:
p(m,x-1)
else:
print(m, end = "\n")
f(k)

Sum of digits untill reach single digit

I set an algorithm which sum a number's digits but I couldn't make it till single digit. It only work for one step.
For example:
a=2, b=8
a^b=256 = 6+5+2 = 13
But I want to reach single digit, like:
a^b=256 = 6+5+2 = 13 = 3+1 = 4
Below you can see my codes.
a = int(input("Enter a value"))
b = int("Enter second value")
number = pow(a, b)
sum= 0
while float(number) / 10 >= .1:
m = number % 10
sum += m
number = number // 10
if float(number) / 10 > .1:
print(m, end=" + ")
else:
print(m, "=", sum)
Here you go:
n = 256
while n > 9:
n = sum(int(i) for i in str(n))
print(n)
So whats going on? str(n) converts n to a string, strings in python can be iterated over so we can access digit by digit. We do this in a generator, converting each digit back to a integer, int(i) for i in str(n), we use sum to sum the elements in the generator. We repeat this process until n is a single digit.
Added a solution that gives the calculation explicitly:
def sum_dig(n):
_sum = sum(int(i) for i in str(n))
explained = "+".join(list(str(n)))
return _sum, explained
n = 256
s = ""
while n > 10:
n, e = sum_dig(n)
s+= f'{e}='
s += str(n)
print(s)
yields:
2+5+6=1+3=4
you can try this.
a = int(input("Enter a value"))
b = int(input("Enter second value"))
number = pow(a, b)
result = str(a)+'^'+str(b) + ' = ' + str(number)
while number > 9:
digit_sum = sum(map(int, str(number)))
result += ' = ' + '+'.join(str(number)) + ' = ' + str(digit_sum)
number = digit_sum
print ( result )
for a=2, b=8 result:
2^8 = 256 = 2+5+6 = 13 = 1+3 = 4
This produces the output in the format OP asked for:
a = int(input("Enter a value: "))
b = int(input("Enter second value: "))
n = pow(a, b)
while n >= 10:
nums = [i for i in str(n)]
op = "+".join(nums)
n = eval(op)
print("{}={}".format(op, n))
Logic:
Store the input in an array of individual numbers as strings.
Create the summation string using "+".join(nums) - for the output print.
Calculate the sum using eval(op) which works on strings (a built-in function) - store in n.
Print the summation string and what it equals.
Output:
Enter a value: 2
Enter second value: 8
2+5+6=13
1+3=4
Enter a value: 2
Enter second value: 6
6+4=10
1+0=1
Enter a value: 2
Enter second value: 50
1+1+2+5+8+9+9+9+0+6+8+4+2+6+2+4=76
7+6=13
1+3=4
sol = 0
if (a^b)%9==0:
sol = 9
else:
sol = (a^b)%9

How to write an adding function that prints each number being added, up to a certain number

I want to create a function that will multiply each number starting from one, up to the number that is specified as a parameter in the function by itself and then add them up together to the parameter number, the trick is, that I want also to write the multiplication as an adding equation.
Here's what I have so far:
def adding(num):
summ = 0
for x in range(1, num+1):
summ += x*x
return summ
So far I can show the total result, but I can't figure out a way to print each number being added as I showed above.
def adding(num):
summ = 0
for x in range(1, num+1):
if x > 1:
print(' + ', end='')
print('+'.join([str(x) for _ in range(x)]), end='')
summ += x*x
print(' =', summ)
return summ
This way is not beautiful by any means but I think it illustrates pretty simply what you're trying to do
def adding(num):
summ = 0
string = ''
for x in range(1, num + 1):
if x > 1:
# append to string x, x times #
string += ' + ' + (str(x) + '+') * x
# remove final character in string #
string = string[:-1]
else:
string += str(x)
summ += x * x
if x == num:
string += ' = ' + str(summ)
print(string)
return summ

How to remove this extra trailing space at the end of each line in python3

I am trying to print this pattern using print() function in python3.
0
0 1 0
0 1 2 1 0
0 1 2 3 2 1 0
0 1 2 1 0
0 1 0
0
the following are the two ways I implemented this.
numeric approach
limit = int(input())
space = ' '
for i in range(0, limit + 1):
print(space * (limit - i), end='')
for j in range(2 * i + 1):
if j > i:
print(i - (j - i), end=' ')
else:
print(j, end=" ")
print()
for i in range(0, limit)[::-1]:
print(space * (limit - i), end='')
for j in range(2 * i + 1)[::-1]:
if j > i:
print(i - (j - i), end=' ')
else:
print(j, end=" ")
print()
string and list comprehension approach
gap = ' '
y = int(input())
y = y + 1
for n in range(1, y + 1):
str1 = ' '.join(str(e) for e in list(range(n)))
str2 = ' '.join(str(e) for e in list(range(n - 1))[::-1])
print(gap * (y - n) + str1 + " " + str2.strip())
for n in range(1, y)[::-1]:
str1 = ' '.join(str(e) for e in list(range(n)))
str2 = ' '.join(str(e) for e in list(range(n - 1))[::-1])
print(gap * (y - n) + str1 + " " + str2.strip())
the pattern is printing right but when I am submitting this to online judge it do not accept.
wrong answer 1st lines differ - expected: ' 0', found: ' 0 '
it expects to remove that extra space after the 0.
PROBLEM: In both of the code snippet I am unable to remove the last line extra space. I do not know how to achieve this Pattern and also not to have that extra space after the number at the end of each line.
The problem appears to be the expression gap * (y - n) + str1 + " " + str2.strip(). For the first line, str is null, so you have str1 followed by a space, followed by nothing, which means that you have a space at the end of your line. The solution is to add the lists together first, then join:
for n in range(1, y + 1):
list1 = [str(e) for e in list(range(n))]
list2 = [str(e) for e in list(range(n - 1))[::-1]]
print(gap * (y - n)+" ".join(list1+list2))
BTW, an alternative to list(range(n - 1))[::-1] is list(range(n-2,-1,-1)).
You can also combine list comprehensions with various tricks, such as
[str(e) if e < n else str(2*n-e) for e in range(2*n+1) ]

Categories

Resources