Counting Change
Write a recursive function that counts how many different ways you can make change for an amount, given a list of coin denominations. For example, there are 3 ways to give change for 4 if you have coins with denomination 1 and 2: 1+1+1+1, 1+1+2, 2+2.
Do this exercise by implementing the countChange function in Main.scala. This function takes an amount to change, and a list of unique denominations for the coins. Its signature is as follows:
def countChange(money: Int, coins: List[Int]): Int
Once again, you can make use of functions isEmpty, head and tail on the list of integers coins.
Hint: Think of the degenerate cases. How many ways can you give change for 0 CHF(swiss money)? How many ways can you give change for >0 CHF, if you have no coins?
I tried to do like this, but this error occured
object main {
def countChange(money: Int, coins: List[Int]): Int = {
if (money == 0)
1
else if (money > 0 && !coins.isEmpty)
countChange(money - coins.head, coins) + countChange(money, coins.tail)
else
0
}
def main(args: Array[String]): Unit = {
var money = scala.io.StdIn.readInt()
var coins = scala.io.StdIn.readInt()
println(countChange(money, coins))
}
}
type mismatch;
found : Int
required: List[Int]
println(countChange(money, coins))
Related
Wrote this code in comp sci class and I cant get it to work, it always returns as false every time I run it. Its supposed to be a recursive binary search method... Any idea why it only returns false?
arr = [1,10,12,15,16,122,132,143,155]
def binarysearch(arr,num):
arr2 = []
if (len(arr) == 1):
if (arr[0] == num):
return 1
else:
return 0
for i in range (len(arr)/2):
arr2.append(0)
if (arr[len(arr)/2]>num):
for x in range (len(arr)/2,len(arr)):
arr2[x-(len(arr)/2)]=arr[x]
return binarysearch(arr2,num)
if(arr[len(arr)/2]<num):
for x in range(0, len(arr) / 2 ):
arr2[x] = arr[x]
return binarysearch(arr2, num)
num = raw_input("put number to check here please: ")
if(binarysearch(arr,num)==1):
print "true"
else:
print "false"
You're doing vastly more work than you need to on things that Python can handle for you, and the complexity is masking your problems.
After your base case, you have two if statements, that don't cover the full range—you've overlooked the possibility of equality. Use if/else and adjust the ranges being copied accordingly.
Don't create a new array and copy stuff, use Python's subranges.
Don't keep repeating the same division operation throughout your program, do it once and store the result.
If you want to print True/False, why not just return that rather than encoding the outcome as 0/1 and then decoding it to do the print?
Recall that raw_input returns a string, you'll need to convert it to int.
The end result of all those revisions would be:
def binary_search(arr,num):
if (len(arr) == 1):
return (arr[0] == num)
mid = len(arr) / 2
if (arr[mid] > num):
return binary_search(arr[:mid], num)
else:
return binary_search(arr[mid:], num)
num = int(raw_input("put number to check here please: "))
print binary_search(arr,num)
The function should accept a single list as a parameter. The function should return an integer value as the result of calculation. If there are no positive and even integer values in the list, your function should return 0.
My current code:
def main():
print (sum_positive_even([1,2,3,4,5]))
print (sum_positive_even([-1,-2,-3,-4,-5]))
print (sum_positive_even([1,3,5,7,9]))
def sum_positive_even(list):
for num in list:
if num < 0:
list.remove(num)
for num in list:
if num % 2 == 1:
list.remove(num)
result = sum(list)
return result
main()
The output should be like:
6
0
0
I'm confused where I should put the 'return 0'.
Thanks TA!
Deleting from a list while you iterate over it is a Bad Idea - it's very easy to get hard-to-track-down bugs that way. Much better would be to build a new list of the items you want to keep. You don't need a special case of returning 0; the general approach should be able to handle that.
Also, it's better not to use list as a variable name in Python, because that's the name of a built-in.
A modification of your approach:
def sum_positive_even(lst):
to_keep = []
for num in lst:
if num > 0 and num % 2 == 0:
to_keep.append(num)
return sum(to_keep)
Since the sum of an empty list is 0, this covers the case where there are no positive even numbers.
I am not sure how to implement this, but here is the description:
Take a number as input in between the range 0-10 (0 always returning false, 10 always returning true)
Take the argument which was received as input, and pass into a function, determining at runtime whether the boolean value required will be true or false
Say for example:
Input number 7 -> (7 has a 70% chance of generating a true boolean value) -> pass into function, get the boolean value generated from the function.
This function will be run multiple times - perhaps over 1000 times.
Thanks for the help, I appreciate it.
bool func(int v) {
float f = rand()*1.0f/RAND_MAX;
float vv= v / 10.0f;
return f < vv;
}
I would say generate a random number representing a percentage (say 1 to 100) then if the random number is less then or equal to the percentage chance mark it as true, else mark it as false.
This is an interesting question! Here's what I think you should do, in pseudo code:
boolean[] booleans = new boolean[10]; //boolean array of length 10
function generateBooleans(){
loop from i = 0 to 10:
int r = random(10); //random number between 0 and 9, inclusive
if(r < i){
booleans[i] = true;
}
}
}
You can then compare the user's input to your boolean array to get the pre-determined boolean value:
boolean isTrue = booleans[userInputNumber]
Here's an idea , I'm not sure that's it's gonna be helpful;
bool randomChoice(int number){
int result =rand() % 10;
return number>=result;
}
Hope it's helpful
This is my first question here so be kind :-) I'm trying to make a recursive call here, but I get the following compiler error:
In file included from hw2.cpp:11:
number.h: In member function ‘std::string Number::get_bin()’:
number.h:60: error: no matching function for call to ‘Number::get_bin(int&)’
number.h:27: note: candidates are: std::string Number::get_bin()
string get_bin ()
{
bin = "";
printf("Value is %i\n",val);
if (val > 0)
{
int remainder = val;
printf("remainder is %i\n",remainder);
printf("numbits is %i\n",size);
for (int numbits = size-1;numbits>=0;numbits--)
{
//printf("2 raised to the %i is %i\n",numbits,int(pow(2,numbits)));
printf("is %i less than or equal to %i\n",int(pow(2,numbits)),remainder);
if (int (pow(2,numbits))<=remainder)
{
bin+="1";
remainder -= int(pow(2,numbits));
printf("Remainder set to equal %i\n",remainder);
}
else
{
bin+= "0";
}
}
return bin;
}
else
{
int twoscompliment = val + int(pow(2,size));
return get_bin(twoscompliment);
}
Any thoughts? I know get_bin works for positive numbers.
In the last line you are calling get_bin() with an integer reference argument, but there are no formal parameters in the function signature.
string get_bin ()
return get_bin(twoscompliment);
These are mutually incompatible. I don't see how you can say that code works for positive numbers since it's not even compiling.
You probably need to change the first line to something like:
string get_bin (int x)
but, since you don't actually use the argument, you may have other problems.
If you're using global or object-level variables to do this work, recursion is not going to work, since they different levels will be stepping on each other's feet (unless you do your own stack).
One of the beauties of recursion is that your code can be small and elegant but using local variables is vital to ensure your data is level-specific.
By way of example, examine the following (badly written) pseudo-code:
global product
def factorial (n):
if n == 1:
return 1
product = factorial (n-1)
return n * product
Now that won't work for factorial (7) since product will be corrupted by lower levels. However, something like:
def factorial (n):
local product
if n == 1:
return 1
product = factorial (n-1)
return n * product
will work just fine as each level gets its own copy of product to play with. Of course:
def factorial (n):
if n == 1:
return 1
return n * factorial (n-1)
would be even better.
The function is defined to take no arguments, yet you pass an int.
It looks like you're accessing a global or member variable val. That should probably be converted into the argument.
string get_bin ( int val )
Since you have not declared bin and val in the function I guess they are global.
Now you define the function get_bin() to return a string and not accept anything. But in the recursive call you are passing it an int. Since you want to pass twoscompliment as val for the recursive call you can do:
int twoscompliment = val + int(pow(2,size));
val = twoscompliment; // assign twoscompliment to val
return get_bin();
Assume the availability of a function is_prime. Assume a variable n has been associated with a positive integer. Write the statements needed to compute the sum of the first n prime numbers. The sum should be associated with the variable total.
Note: is_prime takes an integer as a parameter and returns True if and only if that integer is prime.
Well, I wrote is_prime function like this:
def is_prime(n):
n = abs(n)
i = 2
while i < n:
if n % i == 0:
return False
i += 1
return True
but it works except for n==0. How can I fix it to make it work for every integer?
I'm trying to find out answers for both how to write function to get the sum of first n prime numbers and how to modify my is_prime function, which should work for all possible input, not only positive numbers.
Your assignment is as follows.
Assume the availability of a function is_prime. Assume a variable n has been associated with a positive integer. Write the statements needed to compute the sum of the first n prime numbers. The sum should be associated with the variable total.
As NVRAM rightly points out in the comments (and nobody else appears to have picked up on), the question states "assume the availability of a function is_prime".
You don't have to write that function. What you do have to do is "write the statements needed to compute the sum of the first n prime numbers".
The pseudocode for that would be something like:
primes_left = n
curr_num = 2
curr_sum = 0
while primes_left > 0:
if is_prime(curr_num):
curr_sum = curr_sum + curr_num
primes_left = primes_left - 1
curr_num = curr_num + 1
print "Sum of first " + n + " primes is " + curr_sum
I think you'll find that, if you just implement that pseudocode in your language of choice, that'll be all you have to do.
If you are looking for an implementation of is_prime to test your assignment with, it doesn't really matter how efficient it is, since you'll only be testing a few small values anyway. You also don't have to worry about numbers less than two, given the constraints of the code that will be using it. Something like this is perfectly acceptable:
def is_prime(num):
if num < 2:
return false
if num == 2:
return true
divisor = 2
while divisor * divisor <= num:
if num % divisor == 0:
return false
divisor = divisor + 1
return true
In your problem statement it says that n is a positive integer. So assert(n>0) and ensure that your program outer-loop will never is_prime() with a negative value nor zero.
Your algorithm - trial division of every successive odd number (the 'odd' would be a major speed-up for you) - works, but is going to be very slow. Look at the prime sieve for inspiration.
Well, what happens when n is 0 or 1?
You have
i = 2
while i < n: #is 2 less than 0 (or 1?)
...
return True
If you want n of 0 or 1 to return False, then doesn't this suggest that you need to modify your conditional (or function itself) to account for these cases?
Why not just hardcode an answer for i = 0 or 1?
n = abs(n)
i = 2
if(n == 0 || n == 1)
return true //Or whatever you feel 0 or 1 should return.
while i < n:
if n % i == 0:
return False
i += 1
return True
And you could further improve the speed of your algorithm by omitting some numbers. This script only checks up to the square root of n as no composite number has factors greater than its square root if a number has one or more factors, one will be encountered before the square root of that number. When testing large numbers, this makes a pretty big difference.
n = abs(n)
i = 2
if(n == 0 || n == 1)
return true //Or whatever you feel 0 or 1 should return.
while i <= sqrt(n):
if n % i == 0:
return False
i += 1
return True
try this:
if(n==0)
return true
else
n = abs(n)
i = 2
while i < n:
if n % i == 0:
return False
i += 1
return True