Check for palindrome using recursion [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have used the following code for checking whether a string is palindrome. However it is returning None when a string is palindrome.
def check(a):
if len(a)==1 or len(a)==0:
return True
if a[0]==a[len(a)-1]:
check(a[1:len(a)-1])
else:
return False
print check("radar")

You need to return the result of the recursion in your function:
def check(a):
# Base Case
if len(a) < 2:
return True
# Recursive Call
if a[0] == a[-1]:
check(a[1:-1])
else:
return False
return check(a[1:-1])
print check("radar")
Bonus Info
Your function performs duplicate work as it checks the string a. To avoid duplicate function calls and greatly improve the performance of your algorithm, you might consider memoization. Otherwise, you could build up a large call stack and potentially cause a stack overflow error (hey, that's the name of the website...).
Here's one possible way to implement memoization, by constructing a class around your function:
class check:
def __init__(self):
self.memo = {}
def Check(self, a):
# Base Case
if len(a) < 2:
return True
# Check Memo
if a in self.memo:
return self.memo[a]
# Recursive Call
if a[0] == a[-1]:
self.Check(a[1:-1])
else:
return False
# Memoize
self.memo[a] = True
return self.Check(a[1:-1])
print check().Check("rats live on no evil star")

Related

random.choice() not selecting all possibilities [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
random.choice() in Python does not work correctly.
I have the following function, but the following happens when called:
def Randomswitch():
thechosenone = random.choice(range(0, 2))
if (thechosenone == 0):
return "WIN"
if (thechosenone == 1):
return "LOSE"
Randomswitch()
When Randomswitch is called it only returns WIN every time it's called.
I am breaking my head trying to figure this out.
Can anyone help me please?
Seems to be working pretty well, have you tried only a few times? Let's try 10,000 times and count the occurrences:
import random
from collections import Counter
def Randomswitch():
thechosenone = random.choice(range(0, 2))
if (thechosenone == 0):
return "WIN"
if (thechosenone == 1):
return "LOSE"
Counter(Randomswitch() for i in range(10000))
output:
Counter({'LOSE': 4980, 'WIN': 5020})
Seems pretty decent ;)
improving the code
That said, you code can be improved, why don't you just pass the values to chose from to random.choice?
def Randomswitch():
return random.choice(['WIN', 'LOSE'])
try this:
import random
def Randomswitch():
range_list = [i for i in range(0, 2)]
thechosenone = random.choice(range_list)
if (thechosenone == 0):
return "WIN"
if (thechosenone == 1):
return "LOSE"
Try use random.randint(0,1) instead of random.choice(range(0,2))

why is my recursion not returning the desired output? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am writing a recursion function that simply returns x^n:
def myPow(x,n) -> float:
def recurs_n(x,n):
if n==1:
return x
if n>1:
result = myPow(x,n-1)
return result
return recurs_n(x,n)
print(myPow(2,5))
The output that I am getting for the above is 2, which isn't correct obviously. Any idea where I am going wrong?
Your inner function calls the outer function, that should not be allowed. Furthermore, there is no logic applied anywhere for the multiplication when going to the n-1 step. So when n>1 you need to return x*myPow(x,n-1)
I should also mention, that in your case there is no real need to have an inner and outer function, one function should be enough. Like so;
def myPow(x,n) -> float:
if n == 1:
return x
if n > 1:
return x*myPow(x,n-1)
print(myPow(2,5))
Your code runs until power n=5 reaches 1, where it activates the first if condition where x is returned (here x=2) without continuing onwards.
An alternative is presented below:
def power(N, P):
# if power is 0 then return 1
if P == 0:
return 1
# if power is 1 then number is
# returned
elif P == 1:
return N
else:
return (N*power(N, P-1))

python recursion [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Update:
I forgot the quotation mark... easy fix...
I was trying to do a Leetcode question, the question is #93 Restore IP Address.
Given a string containing only digits, restore it by returning all
possible valid IP address combinations.
For example: Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
This is the correct code by using DFS:
class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
res = []
self.restore(s,0,[],res)
return res
def restore(self,s,count,path,res):
if count == 4:
if not s:
temp = '.'.join(path)
res.append(temp)
else:
return
if not s:
return
if len(s)>2 and int(s[:3])<256 and int(s[:3])>99:
self.restore(s[3:],count+1,path+[s[:3]],res)
if len(s)>1 and int(s[:2])>9:
self.restore(s[2:],count+1,path+[s[:2]],res)
self.restore(s[1:],count+1,path+[s[:1]],res)
return res
This is another approach:
class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
res = []
self.restore(s,0,[],res)
return res
def restore(self,s,count,path,res):
if count == 4:
if not s:
temp = '.'.join(path)
res.append(temp)
else:
return
if not s:
return
if s[0] == '0':
#self.restore(s[1:],count+1,path+[0],res)
self.restore(s[1:],count+1,path+['0'],res)
else:
if len(s)>2 and int(s[:3])<256:
self.restore(s[3:],count+1,path+[s[:3]],res)
if len(s)>1:
self.restore(s[2:],count+1,path+[s[:2]],res)
self.restore(s[1:],count+1,path+[s[:1]],res)
return res
The only difference is that the second approach I firstly check if s is start with '0'.
I do not understand why my second approach is wrong.
take s = '0000' as an example, the second approach will not write '0.0.0.0' to res even s == '' and count = 4
Please help,thanks!
The issue is probably with this statement:
if s[0] == '0':
self.restore(s[1:],count+1,path+[0],res)
It strips leading zeroes. If the input is nothing but zeroes, well, then there's nothing left.

Trying to average a list of numbers using functions [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
First and foremost, I am new to python. As of such, I only know for loops, range, lens, and sum to do this problem. I am having difficulty trying to make a function that can average list of numbers.
This is my code so far:
def ave(L):
L = list(range(len(L))
for a in range(len(L)):
if len(L) == 0: return 0
else: return float((sum(L))/len(L))
So far, I am getting a syntax error on my third line with range(L).
All you need to do is return the sum of L divided by the length of L:
def ave(L):
if not L:
return 0
return sum(L) / len(L)
No range() or float() or for required.
In Python 3, / always produces a floating point number. sum() will do all the looping for you. The only thing you need to take care of, is returning 0 if the list is empty.
Following line is missing a ):
L = list(range(len(L)))
^
Because average of empty list is undefined, you should rather return None instead of '0'.
And instead checking for length, it is better to catch potential error, according to EAFP principle. It makes also more clear what are you doing, as error is self-descriptive.
def ave(L):
try:
return sum(L) / len(L)
except ZeroDivisionError:
return None

Permutation returning True or False python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm trying to make a function isPerm(P) that returns True if it is a permutation, and False otherwise.
So far I've got:
def isPerm(P):
if len(P) == list(range(P)):
return True
else:
return False
Any help would be great.
The simplest way which I can think of is to use Counter
from collections import Counter
def isPerm(P, Q):
return Counter(P) == Counter(Q)
print isPerm("oolegg", "google")
Output
True
This is the easy solution, for short lists.
def is_perm(a, b):
return sorted(a) == sorted(b)
Naive approach: sort a clone of the list and then compare the original list with the sorted clone. If equal then you have a permutation. But sorting takes time.
Efficient approach: create a dictionary/counter with items set to 0 and loop through the list increasing the value in the dictionary. If you get a value of 0 or greater that 1 after finishing the list then you don't have a permutation.

Categories

Resources