how do i avoid returning the first function python3 - python-3.10

I need to execute the function in 10th line but i do not want it go through the 1-5,[the function will go through the def cat_count first and become cat_count(n-1)+cat_count(n-3), how do i do that? Right now, the function cat_count(n-1)+cat_count(n-3) is inside the 10th line, how can i avoid that? It is a fibonacci question, but i can not solve it correctly in second one, can you guys provide some hint
def cat_count(n):
if n<=3:
return 1
if n>3:
return cat_count(n-1)+cat_count(n-3)
def custom_count_cat(n,init,prod_year,num_cats):
if n>prod_year*num_cats-1:
return cat_count(n-init)+cat_count(n-(prod_year*num_cats-1))
elif num_cats==0:
return init
else:
return 1

Related

How to continue iteration over a codition even after it has been met once or even multiple times in ruby

I am writing a small package manager in ruby, and while working on its' package searching functionality, I want to continue iterating over a list of matches, even if it has found a package or sting identical to the inputted string.
def makelist(jsn, searchterm)
len = jsn.length
n = 0
while n < len do
pkname = jsn[n]["Name"]
pkdesc = jsn[n]["Description"]
pkver = jsn[n]["Version"]
unless pkname != nil || pkdesc != nil
# skip
else
puts "#{fmt(fmt("aur/", 6),0)}#{fmt(pkname,0)} [#{fmt(pkver,8)}]\n #{pkdesc}"
n += 1
end
end
end
I have tried using an if statement, unless statement and a case statement in which I gave conditions for what it should do if it specifically finds a packages that matches searchterm but when I use this condition, it always skips all other conditions and ends the loop, printing only that result. This block of code works, but I want to use my fmt function to format the text of matches differently in the list. Anyone have any ideas of how I could accomplish this?
EDIT:
Based on some back and forth the desired behavior is to print matched results differently from unmatched results.
So, in Ruby you have access to "functional" patterns like select, map, reduce, etc. that can be useful for what you're doing here.
It's also advantageous to separate functionality into different methods (e.g. one that searches, one that turns them into a string, one that prints the output). This is just an example of how to break it down, but splitting up the responsibilities makes it much easier to test and see which function isn't doing what you want by examining the intermediate structures.
Also, I'm not sure how you want to "match" the search term, so I used String#include? but you can replace that with whatever matching algorithm you like.
But I think you're looking for something like this:
def makelist(jsn, searchterm)
jsn.select do |package|
package["Name"] && package["Description"]
end.map do |package|
if matches?(package, searchterm)
matched_package_to_string(package)
else
package_to_string(package)
end
end.join("\n")
end
def matches?(package, searchterm)
package['Name'].include?(searchterm) || package('Description').include?(searchterm)
end
def matched_package_to_string(package)
pkname = package["Name"]
pkdesc = package["Description"]
pkver = package["Version"]
"#{fmt(fmt("aur/", 6),0)}#{fmt(pkname,0)} [#{fmt(pkver,8)}]\n #{pkdesc}"
end
def package_to_string(package)
# Not sure how these should print
end

Unable to find a correct output for the two-sum problem

Please mention the logical error in the below code as I am not getting a correct output. Also, do share the correct one to get an output of the indices only.
def find2Sum(A,X):
n=len(A)
for i in range(0,n):
l=[]
if X-A[i] in A:
l.append(i)
return l
nums = [1,4,6,44, 9,8]
target = 14
find2Sum(nums,target)
#Pradeepta Sahu
When you have target=8 the answer for nums=[1,4,6,44, 9,8] should be none because there are no such numbers. But with your code logic X-A[i] in A this for i = 1 will result into 8-4==4 and it will append index to L. This is the main logical bug in the code that you have written. Any number that is target/2 will be passed by your condition.
Aside this you also declared your list var inside the for loop but you are returning it outside the for loop.
This is wrong
for i in range(0,n):
l=[]
This is right
l=[]
for i in range(0,n):

Lua: Unexpected Iteration Result with Table

I was playing around in Lua with a simple 'isPrime' function I made, and, ignoring the actual 'isPrime' function, which is irrelevant to this query, wrote the following code:
out = {}
for i = -10,20 do
out[i] = isPrime(i)
end
for k,v in ipairs(out) do
print(k,v)
end
My expectation was that the program would print every single key and its respective value, -10 through 20, but found instead that only 1 through 20 were printed. -10 through 0 were in the table, I found, after checking specifically for those key-value pairs, but oddly, they were never printed.
Can anyone explain why this happened? I feel I do not fully understand how Lua iterates and accesses its keys through the ipairs() function.
ipairs(t) will iterate over the key–value pairs (1,t[1]), (2,t[2]), ..., up to the first nil value. That's not what you want. Just use the style of your first loop
for i = -10,20 do
print(i, out[i])
end

Store class initialize variable into array then loop through it.. [ruby]

I want to be able to store variables into an array and then loop through them then store the results in an array and return that new array.
The code should explain what I'm trying to do better:
This is my attempt:
# Important initializations
url_check_array = Array.new
return_array = Array.new
# The following initializes classes which then does the check by using the two variables that's passed to it
check_overall = CheckString.new("#{gitlab_cache}", 'success')
check_cache = CheckString.new("#{gitlab_cache}", 'success')
check_database = CheckString.new("#{gitlab_database}", 'success')
check_migrations = CheckString.new("#{gitlab_migrations}", 'success')
unless #is_verbose == "true"
# I haven't done much here as I am not done yet (still trying to get things work on the 'else' part)
url_check_array.insert(check_overall)
puts "url_check_array = #{check_overall}" # DEBUG
puts "Gitlab OVERALL URL is: #{gitlab_overall}" # DEBUG
else
# url_check_array.insert("#{check_cache}", "#{check_database}", "#{check_migrations}") # Results in TypeError - no implicit conversion of String into Integer
url_check_array.insert(check_cache, check_database, check_migrations)
url_check_array.each do |check_item|
return_array.insert(check_item)
end
#puts "Result is: #{check_cache.class}" # DEBUG
return return_array
end
I cannot figure out what I'm doing wrong as the above code results in errors.
EDIT: So the question is.. How do I successfully put those class initializations in an array and then loop through them properly and then put the results in an another array?
EDIT2: Right now I'm getting the following error(s):
TypeError - no implicit conversion of CheckString into Integer
EDIT3: So, I was able to add those to the array by changing url_check_array.insert to url_check_array.push... However, my problem now is that the loop that I have doesn't do much except put the same thing into the return_array (which is the following):
[#<CheckString:0x007ff51e0b5278 #uri_str="https://git.company.com/health_check.json?token=eeMGuv", #pattern="success">, #<CheckString:0x007ff51e0b51b0 #uri_str="https://git.company.com/health_check.json?token=eeMGuv", #pattern="success">, #<CheckString:0x007ff51e0b5110 #uri_str="https://git.company.com/health_check.json?token=eeMGuv", #pattern="success">]
Instead of the actual results.. So, what I really want it to do is actually execute the CheckString.new("#{gitlab_migrations}", 'success') and then put the result into an array.
You put the classes themself in your result array.
Your purpose is to put the results itself in that array?
So in your class CheckString you schould have a method 'check' or something like that that puts out the result. Then in your mapping you should call thatr check method.
url_check_array.each do |check_item|
return_array.insert(check_item.check)
end
class CheckString
def check
# do some checking and return something that indicates a succesful check or not, eg
#gitlab_migrations == 'success'
end
end

Adding odd numbers in an array not providing the correct output

one of my ruby programs that detects odd numbers in an array and adds them together does not provide the correct output. Given that I am learning ruby and this is a logic mistake, I can't easily deduct where I make a mistake.
Here is the Code:
def odd_sum(numbers)
index = 0
result = 0
while index < numbers.length
if (numbers[index] % 2 != 0)
result += 1
end
index +=1
return result
end
end
puts odd_sum([1,2,4,5,7,9]) currently my output is 1 should be 22
puts odd_sum([0,6,4,4]) currently output 0
puts odd_sum([1,2,1]) currently output 1 should be 2
Question: Why is my output wrong? Any way to make this cleaner or better?
I'm running all this in a program called oddball.rb on cloud9.
return result will cause the code to exit right then and there... it will only ever add up the first number, then exit the whole method forever... it will never look at the other elements of the array.
Having now indented your code properly you can see that this line is inside the while loop...
probably you want that to be outside the while loop... it is much easier to see this kind of bug when you properly indent your code. You should always indent your code... it seems unimportant until you come across a bug like this... it's always important. it's a good habit to start now. ;)
have a look at your if-statement: result+=1, don't add 1 but add the the number you are currently testing: result += numbers[index]
SiS
def odd_sum(numbers)
index = 0
result = 0
while index < numbers.length
if (numbers[index] % 2 != 0)
result += 1
end
index +=1
return result
end
end
puts odd_sum([1,2,4,5,7,9]) currently my output is 1 should be 22
puts odd_sum([0,6,4,4]) currently output 0
puts odd_sum([1,2,1]) currently output 1 should be 2
On the line result += 1, you are adding 1 each time there is an odd number, so it's not a sum, but rather a count.
On the line return result, the program will immediately end when it hits the return. So, since the first number in the first array is odd, the program increments result by 1, and then returned result.
What you want to do is result += numbers[index], and return the result at the end of the while loop.
In Ruby, there's often a better way to do things, while loops are meant for when you don't know how many times you are looping. In this case, you know exactly how many times, so I would suggest using an iterator.
def odd_sum(numbers)
result = 0
numbers.each do |num|
result += num if num.odd?
end
end
Or even better
def odd_sum(numbers)
numbers.select(&:odd?).reduce(&:+)
end

Resources