NameError: name 'fib_cache' is not defined
So I am trying to implement the fibonacci number sequence using memoization, but I keep getting this error in leetcode and I am not sure why. Can anyone point me in the right direction?
class Solution:
fib_cache = {}
def fib(self, n: int) -> int:
value;
if n <=1:
value = n;
elif n>2:
value = fib(n-1) + fib(n-2);
fib_cache[n] = value
return value
I fixed some lines in your code and now it works. And actually you were not using memoization in your code so I fixed this ,too.
class Solution:
fib_cache = {}
def fib(self, n: int) -> int:
value = 0 # You don't need this line
if n in Solution.fib_cache: # this adds the memoziation idea
return Solution.fib_cache[n]
if n <=1:
value = n
elif n>=2: # <==== Fixed this line
value = self.fib(n-1) + self.fib(n-2) # <==== Fixed this line
Solution.fib_cache[n] = value # <==== Fixed this line
return value
s = Solution() # You don't need these 2 lines in leetcode
print(s.fib(5)) # I wrote them for testing
Output: 5
Related
I was attempting this question on leetcode using python3.
My solution for this problem is as follows:
class Solution:
def __init__(self):
self.memo = {}
def numRollsToTarget(self, d: int, f: int, target: int) -> int:
if target < d or target > d*f: return 0
if d == 1:
if target<=f: return 1
else: return 0
key = d+f+target
if key not in self.memo:
total = 0
for i in range(1,f+1):
if key not in self.memo:
total += self.numRollsToTarget(d-1,f,target-i)
self.memo[key] = total%((10**9) + 7)
return self.memo[key]
My solution works for small inputs like:
Input: n = 1, k = 6, target = 3 Output: 1 Explanation: You throw one die with 6 faces. There is only one way to get a sum of 3.
However inputs such as
Input: n = 30, k = 30, target = 500 Output: 222616187 Explanation: The answer must be returned modulo 109 + 7.
do not pass the test cases, even when I have made sure that I return the modulo answer. For example for the second test case, the correct output is 222616187. However, my code returns 146996393. Can anyone point out where I am going wrong?
d+f+target is not a unique key for the tuple (d, f, target), which makes the memoization yield incorrect results. Using the tuple (d, f, target) itself is a simple fix.
Also it is unclear why there is a second if key not in self.memo: inside the loop. It shouldn't be possible for that condition to be changed by the computation of the sub-problems, and if it was possible then it would be the wrong way to do it because the wrong total is added up and written over the memo entry that apparently exists.
They gave me the first two lines of code. I thought I knew how to do it but I don't really understand what I'm missing.
class Solution:
def findFinalValue(self, nums: List[int], original: int) -> int:
if original in nums:
for original in nums:
original = original * 2
print(original)
else:
print(original)
yeyo = Solution()
yeyo.findFinalValue()
I think this is what you're trying to accomplish?
from typing import List
class Solution:
def findFinalValue(self, number_list: List[int] = [1,2,3,4,5,6,7,8,9,10], search_value: int = 9) -> int: # Added some default values to test without adding parameters
_done = False # Created a bool value to act as a switch to disable the while loop
original_number = search_value # saving the original value since im recycling the original var below
while _done is False: # Keep doing until the switch above is turned off
if search_value in number_list: # The condition you needed set
search_value *= 2 # that action if condition is met
else:
_done = True # the off "switch"
return "Original Number: {} Search value multiplied up to: {}".format(original_number, search_value) # returns both using a formatted string
#return original_number # Uncomment this line and delete the other return to only return the original number
yeyo = Solution()
yeyo.findFinalValue([1,2,3,4,5,6,7,8,9,10], 2)
I want bo create a function which returns sum of all passed arguments.
I found similar problem on forum, but It doesn't work with last case.
def sum_all(*args):
sum = 0
for num in args:
if not str(num).isdigit():
return False
else:
sum += int(num)
return sum
This code work with first and second case, but return false on third case.
sum_all(2,-3)
# -1
sum_all([3,4,5])
# 12
sum_all(1,2,[3,4,5])
# false
How can i make it work? To make it return 15 in last case?
Thanks!
In case of a list, just call the function recursively, example:
def sum_all(*args):
sum = 0
for num in args:
if type(num) is list:
sum += sum_all(*num)
else:
sum += int(num)
return sum
Can use this
def sum_all(*args):
s = 0
for a in args:
if type(a)==list:
s+=sum(a)
else:
s+=int(a)
return s
print(sum_all(2,-3))
print(sum_all([3,4,5]))
print(sum_all(1,2,[3,4,5]))
Here is my python code:
class Solution():
def isPalindrome(self):
return str(self.x) == str(self.x)[::-1]
s1 = Solution()
s1.x = 121
s1.isPalindrome()
It checks to see if the input is a palindrome. I want to create a new object that has the x value 121 and when I execute the isPalindrom function, I want it to return either a true or false boolean answer.
Currently when I run this program, nothing gets outputted. I am a bit lost as to where to go from here, would appreciate help.
Just print out the return value of isPalindrome(), because if you have a line with only a return value (this case being a boolean), the compiler won't know what to do with it.
class Solution():
def isPalindrome(self):
return str(self.x) == str(self.x)[::-1]
s1 = Solution()
s1.x = 121
print(s1.isPalindrome())
You're not telling the program to print anything. Try using print to make it reveal the answer.
Along with printing results we can also make class more pythonic.
class Solution:
def __init__(self):
self.input = None
def is_palindrome(self):
if isinstance(self.input, str):
return self.input == self.input[::-1]
print("Error: Expects str input")
return False # or leave blank to return None
s1 = Solution()
print(s1.is_palindrome())
s1.input = "121"
print(s1.is_palindrome())
output
Error: Expects str input
False
True
The main idea here is divide number. let's take number 122. First of all you need store it in a variable, in this case r_num. While loop is used and the last digit of the number is obtained by using the modulus operator %. The last digit 2 is then stored at the one’s place, second last at the ten’s place and so on. The last digit is then removed by truly dividing the number with 10, here we use //. And lastly the reverse of the number is then compared with the integer value stored in the temporary variable tmp if both are equal, the number is a palindrome, otherwise it is not a palindrome.
def ispalindrom(x):
r_num = 0
tmp = x
while tmp > 0:
r_num = (r_num * 10) + tmp % 10
tmp = tmp // 10
if x == r_num:
return True
return False
Trying to do this question I got on leetcode.com in python:
Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Note:
You may assume that all elements in nums are unique.
n will be in the range [1, 10000].
The value of each element in nums will be in the range [-9999, 9999].
FIRST ATTEMPT
class Solution(object):
count = 0;
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if (nums[count] == target):
return count;
elif(count +1 >len(nums)):
return -1;
else:
count += 1;
return search(self, nums, target);
My Second attempt was the same exact code except the following line:
count = 0;
was put right after the function definition:
def search(self, nums, target):
Input:
nums = [-1,0,3,5,9,12]
target = 9
Expected Answer: 4
(First Attempt) Actual Answer:
Line 10: UnboundLocalError: local variable 'count' referenced before assignment
(Second Attempt) Actual Answer:
Line 16: NameError: global name 'search' is not defined
I looked up recursive functions with python on the web and it didn't offer too much help as all the example code is more or less the same. Any help will be appreciated!
Your problems have nothing to do with recursion, but rather with misuse of class members.
UnboundLocalError: local variable 'count' referenced before assignment means that you use return count and count += 1, but never initialized it to anything. Presumably, you either want to do count = 0 in the method body, or use self.count instead.
NameError: global name 'search' is not defined is because you're calling a class method wrong. self is special on class methods, so instead of search(self, nums, target), do self.search(nums, target).
You need to use self.search and also I think there is a better way to solve the problem
The question is basically related to Binary Search. You can learn more about it at this https://www.geeksforgeeks.org/binary-search/
I am also attaching the code in Python for reference along with test data. Hope it helps
def binarySearch (nums, left, right, target):
if right >= left:
mid = left + (right - left)/2
if nums[mid] == target:
return mid
elif nums[mid] > target:
return binarySearch(nums, left, mid-1, target)
else:
return binarySearch(nums, mid + 1, right, target)
else:
return -1
nums = [-1,0,3,5,9,12]
target = 9
result = binarySearch(nums, 0, len(nums)-1, target)
print result