Why can't I use a counter in recursion? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I want to know why this code won't run. I am trying to code a Fibonacci sequence using recursion.
def fib(z):
counter = 1
nTwo = 0
nOne = 1
n = nTwo + nOne
if counter == z:
return n
else:
counter = 1 + counter
fib(counter)
counter += 1
nTwo = nOne
nOne = n
n = nTwo + nOne
fib(z)
z = 10
fib(z)
Why does this not work?
I want to know what is wrong with the 'logic' behind it.

If you want an example of how to do the Fibonacci sequence in Python recursively, here is something:
def fib(z)
if z == 0:
return 0
if z == 1:
return 1
return fib(z-1) + fib(z-2)
When you call fib(z), it only knows of the variable 'z', the 'counter' variable of one function call is independent from another function call (you could do fib(z, counter), but that's unnecessary.

It's more simple using while, and using 3 variables.
EXAMPLE:
while True:
num0=1
num1=num0 + num0
num2=num1+num0
while num0 > num1:
num1 += num2
num2 += num1

Related

How to compare all elements of a list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This code in under is will let the user enter the number of elements of list and the user need enter the elements ( User will need type number_of_elements_of_list times) and then count how many positive number, negative number, zero number. The code is like this:
the_number_of_elements_of_the_list = int(input())
number_list = []
for i in range(1, the_number_of_elements_of_the_list + 1):
number_list.append(int(input()))
positive_number_count = 0
negative_number_count = 0
zero_number_count = 0
if number_list == 0:
zero_number_count += 1
elif number_list == 1 or number_list > 1:
positive_number_count += 1
elif number_list < 0:
negative_number_count += 1
print(positive_number_count, negative_number_count, zero_number_count)
The code have a problem: The list can not compare like that. It will be error but i don't know how to compare the elements of list. Can you help me solve this problem?
Firstly, as teambob pointed out, add indent to the for-loop block.
Secondly, as DarkKnight pointed out, put the count variables outside the for-loop.
Thirdly, for each iteration, in order to use that value alone, use number_list[i-1] instead of number_list. (The index is i-1 rather than i because the range in your code starts from 1 rather than 0)
The final code would look like:
the_number_of_elements_of_the_list = int(input())
positive_number_count = 0
negative_number_count = 0
zero_number_count = 0
number_list = []
for i in range(1, the_number_of_elements_of_the_list + 1):
number_list.append(int(input()))
if number_list[i-1] == 0:
zero_number_count += 1
elif number_list[i-1] == 1 or number_list[i-1] > 1:
positive_number_count += 1
elif number_list[i-1] < 0:
negative_number_count += 1
print(positive_number_count, negative_number_count, zero_number_count)

counting number of steps to reduce integer to 0 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
so I'm new to learning def function() in python. And I'm implementing a code that counts the number of steps to reduce an integer to zero.
I have defined a function that makes a list of the integer input by the user, and another function that counts the steps.
the problem is in the second function: currentlynumberOfSteps only takes the first input, but it needs to take all user inputs listed by the first function UserEntryList
def UserEntryList ():
integerEntry = input("Please enter: ")
integerEntry = integerEntry.split()
listOfInt = []
for i in integerEntry:
try:
listOfInt.append(int(i))
except ValueError:
continue
return(listOfInt)
def numberOfSteps():
counter = 0
listofnumbers = UserEntryList()
for i in listofnumbers:
while i > 0:
if i % 2 == 0:
i /= 2
else:
i -= 1
counter += 1
return counter
desired output:
Please enter a set of space-separated positive integers: 10 15 59
[(10, 5), (15, 7), (59, 10)]
First off, couple of things:
always use snake_case in Python, instead of camelCase or PascalCase. More on naming conventions in Python here
return statement in Python should not be enclosed by brackets, unless you're returning a tuple. More on this here.
in the function numberOfSteps(), you have entered the return statement within the for loop. this will not work, as the program will terminate after processing the first item in your loop. So, append your results from each iteration to a list/dict (dict example is shown below.) and return it in the end after the for loop has completed.
def numberOfSteps():
counter = 0
listofnumbers = UserEntryList()
counter_dict = {}
for i in listofnumbers:
temp = i
while i > 0:
if i % 2 == 0:
i /= 2
else:
i -= 1
counter += 1
counter_dict[temp] = counter
return counter_dict
And to answer your question, you can just do append this at the end of your code:
if __name__ == "__main__":
counter = numberOfSteps()
print("Counter = " + str(counter))
Here is a proper way of defining the main function and call sub-function from main function. You will not need to pass any arguments to any functions since you are directly calling UserEntryList from numberOfSteps, which gets executed from the main function.
def UserEntryList ():
integerEntry = input("Please enter: ")
integerEntry = integerEntry.split()
listOfInt = []
for i in integerEntry:
try:
listOfInt.append(int(i))
except ValueError:
continue
return(listOfInt)
def numberOfSteps():
counter = 0
listofnumbers = UserEntryList()
for i in listofnumbers:
while i > 0:
if i % 2 == 0:
i /= 2
else:
i -= 1
counter += 1
return counter
def main():
counter = numberOfSteps()
print("Counter = " + str(counter))
if __name__ == "__main__":
main()

I need to make a function that counts how many odds are in a range of numbers [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
def my_n_odds(a):
num = 0
for num in a:
if num % 2 != 0:
num += 1
return num
my_n_odds(np.arange(100))
this is currently what I have, and it keeps returning 100 while the true value should be 50. Does anyone know how to help?
There are more efficient ways to do this, but if you want to solve it with your original approach, modify the function to:
def my_n_odds(a):
n_odds = 0
for num in a:
if num % 2 != 0:
n_odds += 1
return n_odds
my_n_odds(np.arange(100))
The name conflict gave you a logical error.
You have used the variable num in your for loop as well as the counter of odd numbers. See this correction.
def my_n_odds(a):
num = 0
for n in a:
if n % 2 != 0:
num += 1
return num
def my_n_odds(a):
num = 0 # here is your problem
for num in a:
if num % 2 != 0: # this num is shadowed by the num outside the for loop
num += 1 # here you're incrementing num of the array a, and not the num outside the loop
return num
Solution
def my_n_odds(a):
num = 0 #RENAME THIS VARIABLE TO SOMETHING LIKE count or to any other name except num
for num in a:
if num % 2 != 0:
num += 1 outside the loop
return num
Your approach is very C-like. A more Pythonic solution is to use sum over a predicate applied listexpression (Python's equivalent to map). This is a Functional Programming (FP) solution.
def is_odd(num):
return num % 2 != 0
def n_odds_in_range(*args, **kwargs): # arguments exactly like for range
return sum([is_odd(x) for n_odds_in_range(100)x in range(*args, **kwargs)])
n_odds_in_range(100)
## 50
## or:
def is_odd(num):
return num % 2 != 0
def n_odds(l):
return sum([is_odd(x) for x in l])
n_odds(np.arange(100))
## 50
def my_n_odds(a):
count = 0
for num in a:
if num % 2 != 0:
count += 1
return count
my_n_odds(numpy.arange(100))
Modify the function like this
def my_n_odds(a):
num = 0
for i in a:
num += (i%2)
return num
here num is used as the count for odds. and i take each element from a. we can calculate is the number is odd as if(i%2!=0) which returns true. then we can increment num. But I did it in a different method. In Above function my_n_odds()**, (i%2) returns 1 if it is odd. So we can increment numby avoiding if statement ( num+=(i%2) ).

Writing a Loop to see if a number in a list is even or odd (python) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to write a loop that goes through a list of numbers and prints whether each number is even or odd. It seemed pretty simple, but it just infinitely prints odd. What is the fallacy?
samplenumber = [1,2,3,4,5,6,7,8,9,10]
o = 0
f1 = samplenumber[o]
while f1 < 11:
if f1%2 == 0:
print ("EVEN")
else:
print ("ODD")
o += 1
You have an infinite while loop because you're incrementing the wrong variable. The while loop condition has to equal false at some point, but yours will never equal false (so it keeps running over and over again). See my comment in your code for further explanation:
samplenumber = [1,2,3,4,5,6,7,8,9,10]
o = 0
f1 = samplenumber[o]
while f1 < 11: #f1 will always equal 1 (samplenumber[o] = samplenumber[0] = 1), and 1 is always <11
if f1%2 == 0:
print ("EVEN")
else:
print ("ODD")
o += 1
You should either increment f1 in your while loop or use o as your counter variable.
Have a nice day!
you need to read up on for-loops, friend!
samplenumber = [1,2,3,4,5,6,7,8,9,10]
for i in samplenumber:
if i%2 == 0:
print ("EVEN")
else:
print ("ODD")
best of luck, cheers.
ans:
def test2():
samplenumber = [1,2,3,4,5,6,7,8,9,10]
for item in samplenumber:
if item%2 == 0:
print("EVEN")
else:
print("ODD")
Output:
ODD
EVEN
ODD
EVEN
ODD
EVEN
ODD
EVEN
ODD
EVEN

Trying to code a function with one numeric input. If the number <= 0, return -1. If the number > 0, divide that integer over-and-over by 2 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am new to Python and coding. This is what I have so far, but can't get it to work.
def halve_to_2( num ):
while True:
num = num /2
if num < 2:
else:
if num <=0:
print ("-1")
return num
k = int(input("Enter a number"))
print(halve_to_2(k))
def halve_to_2( num ):
while True:
if num <= 0:
print("-1")
return -1
else:
num = num / 2
k = int(input("Enter a number"))
print(halve_to_2(k))
def divisibleByTwo( num) :
if num <=0 :
return - 1
else :
divisibleByTwo (num/2)
Its called recursion. The break point is the return - 1 for this recursive loop
def divisibleByTwo( num) :
print ( num)
if int(num) > 0 :
divisibleByTwo (num/2)
return num/2
This one print the values that fall within integers not scientific decimals

Categories