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)
Related
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=' ')
I need a function that takes variables and then computes these variables (example for x and y xy) and recursively finds the sum of points there is two left.
But,
The function needs to print all the calculation.
For an example
Function is going to print this,53
Sorry for my bad english and good luck with the question.
Not very beautiful, but does the job
def f(x, y):
tmp = x**y
sum = 0
while tmp >= 1:
sum = sum + tmp % 10
tmp = (tmp // 10)
return sum
This might do it for you.
Not the most pretty code either:
def func(x,y):
res1 = str(x**y)
to_print = "{0}^{1} = {2}".format(x,y,res1)
while len(res1) > 1:
to_print += " = " + res1[0]
res2 = int(res1[0])
for n in res1[1:]:
to_print += " + " + n
res2 += int(n)
to_print += " = " + str(res2)
res1 = str(res2)
print(to_print)
Basically I created a string from the value of x**y so it would be easy to iterate(res1 = str(x**y)).
to_print saves the final output and is used to concatenate all the values.
to_print = "{0}^{1} = {2} = {3}".format(x,y,res1, res1[0])
I used a format string, if you are unfamiliar with this check this.
res2 saves the sum of the digits:
res2 = int(res1[0])
for n in res1[1:]:
res2 += int(n)
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
I need to do a countup value that prints as a string -- so if the user would enter 5 it would count up from 1 -- ' 1 2 3 4 5' in a string and not seperate lines. This is what i have for a basic recursion function that counts up however it is not giving me the output of a string. Any help would be much appreciated
def countup(N, n=0):
print(n)
if n < N:
countup(N, n + 1)
If you need to return a string, think about returning strings. The first part of your result is n converted to a string: str(n). While you're not yet done, you append a space followed by the countup of the rest of the numbers. Like so:
def countup(N, n=1):
res = str(n)
if n < N:
res += ' ' + countup(N, n + 1)
return res
print(countup(5))
Another version, without the need of a local variable, is:
def countup(N, n=1):
if n < N:
return str(n) + ' ' + countup(N, n + 1)
else:
return str(n)
Why not just use str.join? No recursion needed here.
def countup(N, n=1):
return ' '.join(map(str, range(n, N)))
For start, this is a basically a duplicate of python recursive function that prints from 0 to n? and recursion, Python, countup, countdown
Change your ending of the print with print(n, end = ' ') to avoid the new line. See How to print without newline or space?
Also, your default argument should be n=1 to comply with it would count up from 1 assuming the call of countup(5)
def countup(N, n=1):
print(n, end = ' ')
if n < N:
countup(N, n + 1)
Hello I want to make a function that will use enhance(which just changes the word already made it) and print the new word in parts of a given number n. Example for S=test I should get (‘##t’, ‘#te’, ‘tes’, ‘est’, ‘st%’, ‘t%%’)
def enhance(S,n):
S = "#"*(n-1)+S+"%"*(n-1)
return S
def exploder(S,n):
S = enhance(S,n)
x=0
for i in range (n <= len(S)):
print(S[x:i])
x=x+1
S="test"
n = 3
for n in range (0,n):
print(exploder(S,n))
n=n+1
print(exploder(S,n))
One immediate fix. Instead of:
for i in range (n <= len(S)):
I think you want:
for i in range(n, len(S) + 1):
That will give you values of i in the range n <= i < len(s).
Also, as Alex Hall suggested, change:
print(exploder(S,n))
To just:
exploder(S,n)
The exploder function was returning None. So that print is the source your spurious None outputs.
def enhance(S, n):
S = "#" * (n - 1) + S + "%" * (n - 1)
return S
def exploder(S, n):
S = enhance(S, n)
for i in range(len(S)-n+1):
print(S[i:i+n])
S = "test"
n = 3
exploder(S, n)
Output:
##t
#te
tes
est
st%
t%%