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.
Related
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
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
I am currently taking 6.00.2x from MITx, and there is a line from a search tree algorithm that confuses me, could anyone help please?
val, taken = maxVal(foods, maxUnits)
This syntax does not make sense to me. maxVal is a function, so presumably foods and maxUnits are inputs. But what are val and taken, what does this line do? Nowhere in the code are there variables instantiated with those names, so I am just not sure what they are (and this line of syntax means).
PS: The complete code is as follows. The aforementioned syntax occurs on 3rd line of the function testMaxVal. foods is a list of 1) food, 2) values, and 3) calories.
def maxVal(toConsider, avail):
"""Assumes toConsider a list of items, avail a weight
Returns a tuple of the total value of a solution to the
0/1 knapsack problem and the items of that solution"""
if toConsider == [] or avail == 0:
result = (0, ())
elif toConsider[0].getCost() > avail:
#Explore right branch only
result = maxVal(toConsider[1:], avail)
else:
nextItem = toConsider[0]
#Explore left branch
withVal, withToTake = maxVal(toConsider[1:],
avail - nextItem.getCost())
withVal += nextItem.getValue()
#Explore right branch
withoutVal, withoutToTake = maxVal(toConsider[1:], avail)
#Choose better branch
if withVal > withoutVal:
result = (withVal, withToTake + (nextItem,))
else:
result = (withoutVal, withoutToTake)
return result
def testMaxVal(foods, maxUnits, printItems = True):
print('Use search tree to allocate', maxUnits,
'calories')
val, taken = maxVal(foods, maxUnits)
print('Total value of items taken =', val)
if printItems:
for item in taken:
print(' ', item)
testMaxVal(foods, 750)
As you can see, maxVal can return two outputs at the same time like at the line :
result = (withoutVal, withoutToTake)
Recover these two outputs in two variable val and taken is done by the line :
val, taken = maxVal(foods, maxUnits)
The function maxVal returns a tuple. You can return multiple values from a function in python in the form of tuple.
Example:
def connect():
connection = _connect()
message = "Connected"
if not connection:
message = "Not connected"
return connection, message
connection, message = connect()
maxVal returns a pair.
You can "deconstruct" any tuple by assigning its elements to the appropriate number of variables simultaneously.
Example:
>>> a,b,c = (1,2, "hello")
>>> a
1
>>> b
2
>>> c
'hello'
I'm trying to use pyresttest's benchmarking framework to generate a sequence of entries in my flask_sqlalchemy-based database. I would like to read input values from a pre-defined list as advertised by this framework's benchmarking generator type 'fixed_sequence', but it's only picking up the first element of the list.
Here is the issue that explains my problem in detail, with an example: https://github.com/svanoort/pyresttest/issues/264
Any pointer in the right direction will be greatly appreciated
I looked into the code, it is jsut a bug, this feature was never used by anyone.
https://github.com/svanoort/pyresttest/blob/master/pyresttest/generators.py#L100
instead of:
```
def factory_fixed_sequence(values):
""" Return a generator that runs through a list of values in order, looping after end """
def seq_generator():
my_list = list(values)
i = 0
while(True):
yield my_list[i]
if i == len(my_list):
i = 0
return seq_generator
It should be:
def factory_fixed_sequence(values):
""" Return a generator that runs through a list of values in order, looping after end """
def seq_generator():
my_list = list(values)
i = 0
while(True):
yield my_list[i]
i += 1
if i == len(my_list):
i = 0
return seq_generator
```
The i += 1 is missing
So I am trying to get a grasp on Hash Functions and how exactly they work. I have the following code but I keep getting an error when I try and run the code.
import sys
def part_one():
foo = open('input_table.txt')
for line in foo:
id, make, model, year = line.split(",")
print(make, model)
tuple_list = (make+model,)
return tuple_list
def hash_one(num_buffers, tuple_list):
#part_one()
# A being the first constant prime number to multiply by
# B being the prime number that we add to A*sum_of_chars
tuple_list = part_one()
A = 3
B = 5
count = 0
for item in tuple_list:
for char in item:
# sum_of_chars is the total of each letter in the word
count = ord(char)
count = count + tuple_list
index = ((A * sum_of_chars + B)) % num_buffers
return index
if __name__ == '__main__':
input_table = sys.argv[1]
num_buffers = int(sys.argv[2])
chars_per_buffer = int(sys.argv[3])
sys.argv[4] = 'make'
sys.argv[5] = 'model'
lst = []
for item in range(4, len(sys.argv)):
lst.append(sys.argv[item])
print(lst)
hash_one(lst)
What is wrong with my code that is causing the error? Can anyone help me?
1
You're calling hash() with no arguments, you have to hash something.
A hash of a number will just return the same number though, so it's not very interesting. It's for hashing things like strings.
2
part_one returns nothing, therefore when you call tuple_list = part_one(), it's value is set to None, and you can't iterate though it.
3
Passing in a list through an argument then overwriting it doesn't make any sense anyway. If you want to return a list then use a return statement.
4
It's odd to set argument variables in code, they're for reading things from the command line.
5
(Not an error, but...)
You can use a slice (lst = sys.argv[4:]) as an easier way to get a sub-section of a list.