Print within Recursion function Python3 - recursion

the point of my recursion function is to print integers in reverse order.
def rDisp(s):
n=str(s)
if n == "":
return n
else:
return rDisp(n[1:]) + n[0]
def main():
number=(int(input("Enter a number :")))
rDisp(num)
main()
If within the main function I implement print(reverseDisplay(number)), it works, however, for the purpose of this code, I want the reverseDisplay function to do the printing. How would I go about implementing the print function into that block of code.
Thanks!

Untested code:
def reversePrint(s):
if not s:
return
print(s[-1])
reversePrint(s[:-1])
def main():
number=input("Enter a number :")
reversePrint(number)
main()

Just got it
def reverseDisplay(s):
n=str(s)
if n == "":
return n
else:
reverseDisplay(n[1:])
b=n[0]
print(b,end='')

Related

Unable to get mypy to accept code which works correctly; generics appear to be the problem

The following program is self-documenting. It gives the correct results, but it fails typechecking with mypy --strict.
Maybe there's a bug in mypy. More likely, my type annotations are incorrect. Any ideas?
"""
This code shows a technique for creating user-defined infix operators.
The technique is not my invention. However, I would like to have an implementation that:
a) I understand
b) type-checks with mypy --strict.
This code allows any two-argument function to be called as an operator, using the syntax:
leftArgument <<functionName>> rightArgument
... for the avoidance of doubt, << and >> are literally present in the code.
"""
from typing import Callable, Generic, TypeVar
T = TypeVar("T")
U = TypeVar("U")
V = TypeVar("V")
class WithLeft(Generic[T, U, V]):
def __init__(self, func, left: T) -> None:
self.func = func
self.left = left
def __rshift__(self, right: U) -> V:
return self.func(self.left, right)
class WithRight(Generic[T, U, V]):
def __init__(self, func, right: U) -> None:
self.func = func
self.right = right
def __rlshift__(self, left: T) -> V:
return self.func(left, self.right)
class Op(Generic[T, U, V]):
def __init__(self, func) -> None:
self.func = func
def __rlshift__(self, left: T) -> WithLeft[T, U, V]:
return WithLeft(self.func, left)
def __rshift__(self, right: U) -> WithRight[T, U, V]:
return WithRight(self.func, right)
if __name__ == "__main__":
print("Define the operator <<add>>, which adds two ints.")
#Op
def add(a: int, b: int) -> int:
return a + b
print("Demonstrate that it works.")
print(f"{12 <<add>> 44} correctly prints {12 + 44}")
print('Previous line gives error from mypy:')
print('\tUnsupported operand types for << ("int" and "Op[<nothing>, <nothing>, <nothing>]")')
print()
print("Define the operator <<compose>>, which composes two functions.")
P = TypeVar("P")
Q = TypeVar("Q")
R = TypeVar("R")
#Op
def compose(left: Callable[[Q], P], right: Callable[[R], Q]) -> Callable[[R], P]:
return lambda x: left(right(x))
print("Demonstrate that it works.")
from math import (
cos, # angle in radians, not degrees
log # base e, not base 10
)
logcos: Callable[[float], float] = log <<compose>> cos
print('Previous line gives two errors from mypy:')
print('\tUnsupported operand types for << ("Callable[[SupportsFloat, SupportsFloat], float]" and "Op[<nothing>, <nothing>, <nothing>]")')
print('\tUnsupported operand types for >> ("WithLeft[<nothing>, <nothing>, <nothing>]" and "Callable[[SupportsFloat], float]")')
print()
print(f"{logcos(1)} correctly prints {log(cos(1))}")
Stackoverflow doesn't like this post because it is mostly code.
So I'll repeat the explanation from the code. No need to read this again!
This code shows a technique for creating user-defined infix operators.
The technique is not my invention. However, I would like to have an implementation that:
a) I understand
b) type-checks with mypy --strict.
This code allows any two-argument function to be called as an operator, using the syntax:
leftArgument <> rightArgument
... for the avoidance of doubt, << and >> are literally present in the code.

Subset sum using recursive backtracking in python using list and return statements.

I am trying to solve the subset sum problem using recursive back-tracking. While it works if I print the result instantly, it does not seem to work if I try to return it.
Here is a look at the code in python. I have added intermediate print statements to make things easier(please uncomment them):
l = [int(i) for i in input().split()]
num = int(input())
#print(num)
#print(l)
def subset(l):
tot = 0
ch = []
return(subsetHelper(l,tot,num,ch))
def subsetHelper(l,tot,num,ch):
#print("("+str(l)+" "+str(tot)+" "+str(num)+" "+str(ch)+")")
if(tot==num):
return(ch)
elif(tot>num or len(l)==0):
return
else:
ch.append(l[0])
return subsetHelper(l[1:],tot+l[0],num,ch)
del ch[-1]
return subsetHelper(l[1:],tot,num,ch)
print(subset(l))
The same concept works when I print the result without returning it.
l = [int(i) for i in input().split()]
num = int(input())
#print(num)
#print(l)
def subset(l):
tot = 0
ch = []
subsetHelper(l,tot,num,ch)
def subsetHelper(l,tot,num,ch):
#print("("+str(l)+" "+str(tot)+" "+str(num)+" "+str(ch)+")")
if(tot==num):
print(ch)
elif(tot>num or len(l)==0):
#return "Hello"
return
else:
ch.append(l[0])
subsetHelper(l[1:],tot+l[0],num,ch)
del ch[-1]
subsetHelper(l[1:],tot,num,ch)
subset(l)
Any suggestions?

Reverse order recursion

I want to print out the elements in the list in reverse order recursively.
def f3(alist):
if alist == []:
print()
else:
print(alist[-1])
f3(alist[:-1])
I know it is working well, but I don't know the difference between
return f3(alist[:-1])
and
f3(alist[:-1])
Actually both are working well.
My inputs are like these.
f3([1,2,3])
f3([])
f3([3,2,1])
There is a difference between the two although it isn't noticeable in this program. Look at the following example where all I am doing is passing a value as an argument and incrementing it thereby making it return the value once it hits 10 or greater:
from sys import exit
a = 0
def func(a):
a += 1
if a >= 10:
return a
exit(1)
else:
# Modifications are made to the following line
return func(a)
g = func(3)
print(g)
Here the output is 10
Now if I re-write the code the second way without the "return" keyword like this :
from sys import exit
a = 0
def func(a):
a += 1
if a >= 10:
return a
exit(1)
else:
# Modifications are made to the following line
func(a)
g = func(3)
print(g)
The output is "None".
This is because we are not returning any value to handle.
In short, return is like internal communication within the function that can be possibly handled versus just running the function again.

how to compute a%b recursively?

I need to write a recursive function that returns the remainder of two numbers. Here's what I wrote:
def remainder(a,b):
if a==b:
return 0
else:
k=a-b
return a-b + remainder(b,a-k)
If we test remainder(5,3) the function will return 2 and it's correct but if we test remainder(15,3),
we'll get 12 and its false. I just don't know how to debug it.
You are missing a case: (when a < b)
def remainder(a,b):
if a<b: #trivial: remainder = a - b*0 = a
return a
else: #reduce the problem to a simple one
return remainder(a-b, b)
Test:
print remainder(15,3)
Output:
0
Here if you are lazy and don't want to write more than 2 lines:
def remainder(a,b):
return a if a < b else remainder(a-b, b)
It should be something like this :
def remainder(a,b):
if a<b:
return a
else:
return remainder(a-b,b)
You can do:
def remainder(a, b):
if a < b:
return a
return remainder(a - b, b)
Examples:
>>> remainder(15, 3)
0
>>> remainder(14, 3)
2
>>> remainder(13, 3)
1
If a < b then it means we're done: we know the result of the computation and we can return a. Otherwise we need to subtract b from a and we call remainder again recursively. This can then repeatedly continue until a is smaller than b. Once that happens the recursion stops (i.e., it won't call remainder again) but we're able to return the result.

How to call a closure with multiple parameters from collect() method of a groovy collection?

Let's say I have a closure:
def increment = {value, step ->
value + step
}
Now I want to loop over every item of my integers collection, increment it with 5, and save new elements to a new collection:
def numbers = [1..10]
def biggerNumbers = numbers.collect {
it + 5
}
And now I want to achieve the same result but by means of using increment closure. How can I do this?
Should be something like this (wrong code below):
def biggerNumbers = numbers.collect increment(it, 5) //what's the correct name of 'it'??
The solution to your problem would be nesting your call of increment in a closure:
def biggerNumbers = numbers.collect {increment(it, 5)}
If you wanted to pass a premade closure to the collect you should have made it compatible with collect - accepting a single parameter that is:
def incrementByFive = {it + 5}
def biggerNumbers = numbers.collect incrementByFive
mojojojo has the right answer, but just thought I'd add that this looks like a good candidate for currying (specifically using rcurry)
If you have:
def increment = {value, step ->
value + step
}
You can then curry the right-hand parameter of this function with:
def incrementByFive = increment.rcurry 5
And then, you can do:
def numbers = 1..10
def biggerNumbers = numbers.collect incrementByFive
Just thought it might be of interest ;-)
The main issue is that [1..10] creates a List<IntRange> which you are trying to increment. You should collect on the IntRange directly (note the lack of brackets):
(1..10).collect { it + 5 }
Or with curry:
def sum = { a, b -> a + b }
(1..10).collect(sum.curry(5))

Resources