I need help with converting my iterative code to recursive.
def pattern(int):
if int == 0:
return ''
else:
result = '*-'
for i in range(int-1):
if i%2 != 0:
result += '*-'
elif i % 2 == 0:
result += '*--'
return result
Above is the code I wrote to convert an integer into repetitive patterns. For int%2 != 0, it prints '*-' , and for int%2 == 0, it prints '*--'.
I have been stucked with converting the above to recursive. I understand the base case is '*-' with the terminating condition of int == 1. I should then concatenate the base case with pattern(int-1) recursively. Can anyone advise me?
IIUC, Use:
def pattern(n):
if n == 1: # Base case
return "*-"
if n % 2 == 0:
return pattern(n - 1) + "*--"
else:
return pattern(n - 1) + "*-"
Calling the function:
print(pattern(10)) # builds the pattern corrensponding to integers from 1,2...10.
This prints:
*-*--*-*--*-*--*-*--*-*--
Related
Leetocode keeps giving me this UnboundLocalError, and I don't know why...
This is my code
class Solution:
def longestPalindrome(self, s: str) -> str:
def isPalindrome(s):
if len(s) == 1:
return True
if len(s) == 2 and s[0] == s[1]:
return True
else:
if s[0] == s[-1]:
return isPalindrome(s[1:-1])
else:
return False
max_ = 0
lenght = len(s)
for i in range(lenght):
for r in range(i + 1, lenght):
if isPalindrome(s[i:r]):
len_ = r - i + 1
if len_ > max_:
max_ = len_
final = s[i:r]
return final
and the error it gives me is
UnboundLocalError: local variable 'final' referenced before assignment
return final
Can someone please help me understand why this may be occurring?
I think the problem may be given in the case where the final string is of len() = 1. In that case it might be a problem the s[i : r]
your final variable is defined inside the if block and is not visible outside. just declare it outside to get rid of this erro
class Solution:
def longestPalindrome(self, s: str) -> str:
def isPalindrome(s):
if len(s) == 1:
return True
if len(s) == 2 and s[0] == s[1]:
return True
else:
if s[0] == s[-1]:
return isPalindrome(s[1:-1])
else:
return False
max_ = 0
lenght = len(s)
final = 0 # declared final here
for i in range(lenght):
for r in range(i + 1, lenght):
if isPalindrome(s[i:r]):
len_ = r - i + 1
if len_ > max_:
max_ = len_
final = s[i:r]
return final
Testcase in which s consist of only one letter. like ("a","d") your inner for loop is not executing and hence you define final inside the if is not initialize and you are returning final hence unbound error occurs.
for ex. let's say s="s"
Dry run-:
max_ :0
lenght :1 (i.e len(s))
for i in range(1):
for j in range(1,1) (i.e when first loop iterating i=0) no inner loop run
Exit()
return Final #Unbound error
To solve this error you can initialize final outside. or you can add a condition if len(s)==1: return 1
also your code solution has time complexity O(n^2) I think it will show Time limit exceeded.
I'm tying to do a Collatz sequence with python code. I'm supposed to make a function that, given n, calculates the next number in the sequence. I want the next function "write" to print each number within the sequence.
My code so far:
def collatz(n):
while n != 1:
if n % 2 == 0:
n = n/2
return write(n)
else:
n = 3*n+1
return write(n)
def write(n):
print(n)
print(collatz(n))
write(6)
It gives me the right sequence, which should be 6, 3,10,5,16,8,4,2,1, but also gives me 9 "nones".
I'm new to programming, it should probably be something easy, but I can't figure out what.
write() is a function that executes two print() statements, and then implicitly returns None (since there are no return statements in the function).
You can simplify the code by using print() directly in collatz(), and eliminating the mutual recursion:
def collatz(n):
while n != 1:
if n % 2 == 0:
n = n//2
print(n)
else:
n = 3*n+1
print(n)
collatz(6)
#Here this will help you understand.
#When n becomes 1, the while loop is not executed,
#collatz does not return write(n)... thus returns None
def collatz(n):
while n != 1:
if n % 2 == 0:
n = n/2
return write(n)
else:
n = 3*n+1
return write(n)
#return None.... there is no return type, so this is implied
def write(n):
print(n)
result = collatz(n)
if result != None:
print(collatz(n))
I'm a beginner in Python and I'm practicing to code this problem I saw. Next prime is needed, but there are limitations on the input. I have searched for similar questions, but my code is still not working. Hope you can help. Thank you!
The problem I get is when I enter 32, the results show 33 when the next prime is 37...
Here's my code so far.
num = int(input("Enter a positive number:"))
import math
def nextprime(n):
if n < 0:
raise ValueError
for next in range(n + 1, n +200):
if next > 1:
for i in range(2, next):
if (next % i) == 0:
break
else:
return next
In your code when you arrive to a number that reminder is not zero you return that number. You need a flag for every number this flag is True if can be divide flag convert to False for the first number that flag not convert to false return that number like below.
Don't use next because this is a builtin function.
Try this: (I don't improve your code)
def nextprime(n):
if n < 0:
raise ValueError
for i in range(n + 1, n +200):
if i > 1:
pr = True
for j in range(2, i):
if (i % j) == 0:
pr = False
break
if pr:
return i
return 'not found'
You can also try this code, write function to check that a number is prime or not like def is_prime then for number of larger that you input num find min number next. (this answer from this thread.)
def is_prime(x):
return all(x % i for i in range(2, x))
def next_prime(x):
return min([a for a in range(x+1, 2*x) if is_prime(a)])
print(next_prime(32))
You can also use sympy like below: (this answer from this thread.)
from sympy import *
nextprime(32)
def next_prime(n):
while True:
n=n+1
for i in range (2,int(n/2)):
if n%i==0:
break
else:
return n
print(next_prime(67))
Few off-topic tips:
as user1740577 mentioned, don't use next as a variable name
refrain from using eval when possible, it's okay here, but in real project this will lead to big no-no.
Place imports at the very top of your script
Consider using variable names i and j only for iterations.
For duplicate except blocks use (Error, Error)
As for solution to your problem, with some adjustments, if you don't mind
def next_prime(n: int) -> int:
if n < 0:
raise ValueError('Negative numbers can not be primes')
# Base case
if n <= 1:
return 2
# For i as every odd number between n + 1 and n + 200
for i in range(n + 1 + (n % 2), n + 200, 2):
# For every odd number from 3 to i (3 because we covered base case)
for j in range(3, i, 2):
# If remained is equals to 0
if not i % j:
# break current loop
break
# If loop j didn't break [nobreak: ]
else:
return i
raise RuntimeError('Failed to compute next prime number :c')
def main():
while True:
try:
num = int(input('Enter positive number: '))
print(f'Next prime is: {next_prime(num)}')
break
except ValueError:
print('Please enter a positive integer!')
if __name__ == '__main__':
main()
Made some speed improvements to the code from #rajendra-kumbar:
#!/usr/bin/env python
import sys
import time
import math
def next_prime(number):
if number < 0:
raise ValueError('Negative numbers can not be primes')
# Base case
if number <= 1:
return 2
# if even go back 1
if number % 2 == 0:
number -= 1
while True:
# only odds
number += 2
#only need to check up to and including the sqrt
max_check = int(math.sqrt(number))+2
# don't need to check even numbers
for divider in range(3, max_check, 2):
# if 'divider' divides 'number', then 'number' is not prime
if number % divider == 0:
break
# if the for loop didn't break, then 'number' is prime
else:
return number
if __name__ == '__main__':
number = int(sys.argv[1].strip())
t0 = time.time()
print('{0:d} is the next prime from {1:d}'.format(next_prime(number), number))
run_time = time.time() - t0
print('run_time = {0:.8f}'.format(run_time))
it is about twice as fast
You can try something like simple:
def is_prime(number:int):
check = 0
for i in range(2,number):
if number % i == 0:
check += 1
if check == 0:
return True
else:
return False
def next_prime(value):
check = value + 1
while is_prime(check) is False:
check += 1
return check
value = int(input("Insert the number: "))
print(next_prime(value))
def iq_test(numbers):
i = 0
length = len(numbers)
numbers = numbers.split()
ints = []
even = []
odd = []
try:
for i in range(i, length, i + 1):
number = int(numbers[i])
ints.append(number)
if ints[i] % 2 == 0:
even.append(ints[i])
else:
odd.append(ints[i])
except:
pass
if len(even) > len(odd):
return i
else:
return i
iq_test("1 2 2")
No matter how many times or ways I try to fix this it doesn't seem to return i. Whenever I do print(i) it gives me the exact thing I wanted and the function works well, but when it's return i I get nothing, how can I fix this?
Edit: this function is supposed to take in some numbers (in string format), one of those numbers will be different in evenness (one is even and the rest are odd and vice versa), I want to return the index of that number.
I have modified your code and it's working :
def iq_test(numbers):
i = 0
numbers = list(map(int,numbers.split()))
even = []
odd = []
try:
for i in range(len(numbers)):
if numbers[i] % 2 == 0:
even.append(i)
else:
odd.append(i)
except:
pass
finally:
if len(even) > len(odd):
return odd[0]
else:
return even[0]
print(iq_test("1 1 2"))
Points I have modified :
instead of creating another list for converting list elements to an integer you could just use the map function
you should store the index of the even and odd value instead of the value itself
And if there is something in the code that is necessary to do even if the error occurs you could use the finally block
def iq_test(numbers):
numbers = numbers.split()
length = len(numbers)
ints = []
even = []
odd = []
try:
for i in range(0, length):
number = int(numbers[i])
ints.append(number)
if ints[i] % 2 == 0:
even.append(ints[i])
else:
odd.append(ints[i])
if len(even) > len(odd):
return even[0]
else:
return odd[0]
except:
pass
ReturnedNumber = iq_test("1 2 2")
print("Returned number from function:",ReturnedNumber)
Hi I have a question with regards to python programming for my assignment
The task is to replace the occurrence of a number in a given value in a recursive manner, and the final output must be in integer
i.e. digit_swap(521, 1, 3) --> 523 where 1 is swapped out for 3
Below is my code and it works well for s = 0 - 9 if the final answer is outputted as string
def digit_swap(n, d, s):
result = ""
if len(str(n)) == 1:
if str(n) == str(d):
return str(s)
else:
return str(n)
elif str(n)[0] == str(d):
result = result + str(s) + str(digit_swap(str(n)[1:], d, s))
return result
else:
result = result + str(n)[0] + str(digit_swap(str(n)[1:], d, s))
return result
However, I have trouble making the final output as Integer
The code breaks down when s = 0
i.e. digit_swap(65132, 1, 0) --> 6532 instead of 65032
Is there any fix to my code?
def digit_swap(n, d, s):
result = ""
if len(str(n)) == 1:
if str(n) == str(d):
return str(s)
else:
return str(n)
elif str(n)[0] == str(d):
result = result + str(s) + str(digit_swap(str(n)[1:], d, s))
return int(result) # Changes
else:
result = result + str(n)[0] + str(digit_swap(str(n)[1:], d, s))
return int(result) # Changes
Conversion to string is unnecessary, this can be implemented much easier
def digit_swap(n, d, s):
if n == 0:
return 0
lower_n = (s if (n % 10) == d else (n % 10))
higher_n = digit_swap(n // 10, d, s) * 10
return higher_n + lower_n
assert digit_swap(521, 1, 3) == 523
assert digit_swap(65132, 1, 0) == 65032
do not return int from method, instead convert it to int from where you are calling method. Problem lies where your code trying to convert string to int return int(result).
So if result is 03 then function will return int('03') i.e 3.
call your method like this
print int(digit_swap(65132, 1, 0)) so you will get integer at the end.
For example int(00) is casted to 0. Therefore a zero is discarded. I suggest not to cast, instead leave it as a string. If you have to give back an int, you should not cast until you return the number. However, you still discard 0s at the beginning. So all in all, I would suggest just return strings instead of ints:
return str(result) # instead of return int(result)
And call it:
int(digit_swap(n,d,s))