python recursion [closed] - python

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.

Related

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

The question is to find the sum of 2 consecutive numbers in the list x that equals to t and return x list without the second number [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 1 year ago.
Improve this question
def trouble(x, t):
for i in range(0,len(x)):
if (x[i]+ x[i+1]) == t:
return x
else:
return None
answer = trouble([4,5,6,7], 9)
print(answer)
Firstly it's not quite clear what you're actually asking, you just shoved a code blob and a title. Assuming you want someone to tell you if your code is correct; it is not.
Now this really just looks like a homework problem, so I won't just post an answer code blob, but here are some comments that might be useful:
def trouble(x, t):
for i in range(0,len(x)): # Range starts at 0 even when not specified
if (x[i]+ x[i+1]) == t:
return x
# You also want to remove the second number no ?
# Hint: you could use slicing, or the list remove(elem) function
else:
# Because this is in the loop it will return immediately
# if the if condition fails (ie: you'll only ever
# look at the first element !
return None
answer = trouble([4,5,6,7], 9)
print(answer)
Is this that you want done. It removes the second value that adds up to t. And returns that new list.
def trouble(x, t):
x = list(x)
for i in range(0, len(x)-1):
if (x[i]+ x[i+1]) == t:
y = list(x)
y.pop(i+1)
return y
else:
return None
answer = trouble([1,3,6], 9)
print(answer)

Bracket Question in Python . Solve in Minimum Time and Space? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 2 years ago.
Improve this question
I am trying to solve
https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/bracket-sequence-1-40eab940/submissions/ in python
Its showing Time Exceed Error. Can anyone tell me how time complexity can be decreased?
Here is my code:
def findBalanced(expr):
stack = []
for char in expr:
if char in ['(']:
stack.append(char)
else:
if not stack:
return False
current_char = stack.pop()
if current_char == '(':
if char != ')':
return False
if stack:
return False
return True
if __name__ == '__main__':
expr = input()
count = 0
for x in range(len(expr)):
expr = expr[1:] + expr[0]
if findBalanced(expr):
count +=1
else:
pass
print(count)
How to solve this problem using minimum time and minimum space?
I suggest adding the line print(stack) at the beginning or the for loop. Then execute your algorithm on a few example inputs. You might notice something a bit weird.
Please take a second to actually do it, and try to find out what's so weird about it. This will give you inspiration on how to improve your algorithm.
...
Did you do it? Please don't read further until you've done it.
The remainder of this answer assumes that you have added print(stack) at the beginning of the for loop, and that you have looked at the output on a few examples of input, and that you have tried to notice something a bit surprising about the outputs. Please do that before you read the remainder of this answer.
Your algorithm maintains a stack, but if you output the stack at every iteration, you'll notice something: the stack only contains copies of the character (. Nothing else. This is because the only occurrence of stack.append(char) is right under if char in ['(']:, so you are only ever appending (.
So really the only information contained in this stack is how many ( it contains. Instead of actually maintaining the stack, you could simply maintain a counter, i.e., an integer telling you how many ( would be on the stack if you had a stack.
Replace stack = [] with depth = 0, then stack.append(char) with depth += 1 and stack.pop() with depth -= 1.
Your check if current_char == '(': is not useful at all, because the chars on the stack are all (, so the check is always true and thus redundant.
I will let you figure out on which values of the counter you should return true and on which values you should return false. Good luck!
def solve(s):
p=0
t=0
res = 0
for i in s:
if(i=='('):
p+=1
else:
p -= 1
if (p<t):
print(f"Values of p and t are {p} and {t}")
t=p
res = 0
if(t==p):
res+=1
if p:
return 0
else:
return res
s= input()
print(solve(s))

Printing to stdout gives the correct list, but appending to a list does not [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 4 years ago.
Improve this question
I working on this problem on leetcode:
Given a collection of distinct integers, return all possible permutations.
If I iteratively print my results I get the correct values. As soon as I add it to a list the results are incorrect. What is happening?
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 1:
return nums
permutations = list()
import math
max_swaps = math.factorial(len(nums))
pair = [0,1]
for i in range(max_swaps):
if pair[1] == len(nums):
pair[0] = 0
pair[1] = 1
p = self.swap(nums, pair[0], pair[1])
print("Adding %s to the list" % p)
permutations.append(p)
pair[0] += 1
pair[1] += 1
return permutations
def swap(self, nums, index1, index2):
tmp = nums[index2]
nums[index2] = nums[index1]
nums[index1] = tmp
return nums
I should get:
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
But instead I get:
[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
You keep adding a reference to the same list to permutations.
When you call:
permutations.append(p)
Python doesn't take a copy of the list, it adds a reference. You only have one list.
What you want to do is:
permutations.append(p[:])
Which will take a copy.
When you return nums from swap, you're not making a copy, you're returning the same list that will be modified later. You can make a copy either at the return or when you append the list to your result.
This is a common bug in a lot of code. The bug you're seeing here is a symptom of having the values returned from swap be the same as nums. This means that you're appending nums over and over into the permutations list. If you were to print the entire permutations list instead of only p you'd see that they were always the same.
The solution is rather simple: At some point in your code (likely in swap or something) you need to make a copy of the nums list.

Check for palindrome using recursion [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 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")

Categories

Resources