Recursion countup with string output - python

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)

Related

Decimal to binary function in Python using recursion

I am new in Python and trying to write a binary-to-decimal converted function like below
def decimaltobinary(n):
if n > 1:
decimaltobinary(n//2)
print(n%2,end='')
#return n%2
decimaltobinary(4)
This works perfectly fine. Now the question is when I am modifying it as below, it doesn't give me correct result -
def decimaltobinary(n):
if n > 1:
decimaltobinary(n//2)
#print(n%2,end='')
return n%2
a=decimaltobinary(4)
print(a)
Am I missing something with the return statement? Any pointer will be very helpful.
You need to be careful with your return statements. Try this:
def decimaltobinary(n):
def _dtb(n, lst):
if n <= 0:
return lst
lst.append(n&1)
return _dtb(n>>1, lst)
return ''.join(map(str, reversed(_dtb(n, list()))))
print(decimaltobinary(19))
Output:
10011
In the second example returned value from decimaltobinary in if is completely ignored.
What you need to do is assign the returned value to a variable and then return it together with n%2.
Try this:
def decimaltobinary(n):
x = ''
if n > 1:
x = decimaltobinary(n//2)
#print(n%2,end='')
return str(x) + '' + str(n%2)
a=decimaltobinary(4)
print(a)
In the first example you are printing on each iteration of the recursive method.
On the second example you're smashing the return statement.
You can see here:
def decimaltobinary(n):
if n > 1:
print('Making recursion for (n): ', n)
decimaltobinary(n//2)
print('Return for (n): ', n, ', result: ', n%2)
return n%2
a=decimaltobinary(4)
print(a)
Output:
Making recursion for (n): 4
Making recursion for (n): 2
Return for (n): 1 , result: 1
Return for (n): 2 , result: 0
Return for (n): 4 , result: 0
0

Removing substring from string in Python

I want to write a function that takes 2 inputs: a string and a substring, then the function will remove that part of the substring from the string.
def remove_substring(s, substr):
"""(str, str) -> NoneType
Returns string without string substr
remove_substring_from_string("Im in cs", "cs")
Im in
"""
other_s = ''
for substr in s:
if substr in s:
continue
How do I continue on from here? Assuming my logic is sound.
Avoiding the use of Python functions.
Method 1
def remove_substring_from_string(s, substr):
'''
find start index in s of substring
remove it by skipping over it
'''
i = 0
while i < len(s) - len(substr) + 1:
# Check if substring starts at i
if s[i:i+len(substr)] == substr:
break
i += 1
else:
# break not hit, so substr not found
return s
# break hit
return s[:i] + s[i+len(substr):]
Method 2
If the range function can be used, the above can be written more compactly as follows.
def remove_substring_from_string(s, substr):
'''
find start index in s of substring
remove it by skipping over it
'''
for i in range(len(s) - len(substr) + 1):
if s[i:i+len(substr)] == substr:
break
else:
# break not hit, so substr not found
return s
return s[:i] + s[i+len(substr):]
Test
print(remove_substring_from_string("I have nothing to declare except my genuis", " except my genuis"))
# Output: I have nothing to declare'
This approach is based on the KMP algorithm:
def KMP(s):
n = len(s)
pi = [0 for _ in range(n)]
for i in range(1, n):
j = pi[i - 1]
while j > 0 and s[i] != s[j]:
j = pi[j - 1]
if s[i] == s[j]:
j += 1
pi[i] = j
return pi
# Removes all occurences of t in s
def remove_substring_from_string(s, t):
n = len(s)
m = len(t)
# Calculate the prefix function using KMP
pi = KMP(t + '\x00' + s)[m + 1:]
r = ""
i = 0
while i + m - 1 < n: # Before the remaining string is smaller than the substring
if pi[i + m - 1] == m: # If the substring is here, skip it
i += m
else: # Otherwise, add the current character and move to the next
r += s[i]
i += 1
# Add the remaining string
r += s[i:]
return r
It runs in O(|s| + |t|), but it has a few downsides:
The code is long and unintuitive.
It requires that there is no null (\x00) in the input strings.
Its constant factors are pretty bad for short s and t.
It doesn't handle overlapping strings how you might want it: remove_substring_from_string("aaa", "aa") will return "a". The only guarantee made is that t in remove_substring_from_string(s, t) is False for any two strings s and t.
A C++ example and further explanation for the KMP algorithm can be found here. The remove_substring_from_string function then only checks if the entire substring is matched at each position and if so, skips over the substring.
I would do this using re.
import re
def remove_substring(s, substr):
# type: (str, str) -> str
return re.subn(substr, '', s)[0]
remove_substring('I am in cs', 'cs')
# 'I am in '
remove_substring('This also removes multiple substr that are found. Even if that substr is repeated like substrsubstrsubstr', 'substr')
# 'This also removes multiple that are found. Even if that is repeated like '
def remove_substring(s, substr):
while s != "":
if substr in s:
s = s.replace(substr, "")
else:
return s
if s == "":
return "Empty String"
The idea here is that we replace all occurrences of substr within s, by replacing the first instance of substr and then looping until we are done.

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)

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

Print a word in parts python

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%%

Categories

Resources