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()
Related
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)
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) ).
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
Here is my code:
change = 0
count = 0
value = 0
answer = 0
def numberTest():
if change == 0:
skip()
else:
value = change
def skip():
count + 1
number = value
# Check if the input is valid
if value != number:
print('PLEASE ENTER A VALID NUMBER!!!')
else:
Even = number % 2
if Even == 0:
print('Substituting even number in: x / 2')
print('%s/2=' % number)
answer = number / 2
else:
print('Substituting odd number in: 3x + 1')
print('3' + number + ' + 1=')
answer = number * 3
answer = answer + 1
answer = str(answer)
print(''+ answer +'')
if answer == 1:
finalValue()
else:
check()
def check():
value = answer
skip()
def loop():
value = int(input('Input a number: '))
change = value
skip()
loop()
def finalValue():
print('The number (' + change + ') returned as 1.')
print('A total of (' + count + ') commands were executed.')
change = change + 1
count = 0
print('')
print('')
print('')
numberTest()
Whenever I start the code, I am asked to enter a number (as expected), but then this happens:
Input a number: 1
Substituting even number in: x / 2
0/2=
0.0
I really do not understand why the program is not working as I expected, but there is one part of the code that I am suspicious of:
value = int(input('Input a number: '))
I also wrote this myself, and I am new to Python, I have only previously worked with batch, so transitioning was quite easy, though I am not very familiar with some of the commands...
EDIT
What I was expecting the program to do was ask for a number, store that number, then run it through a series of tests, but when the number gets to the actual tests, it substitutes "x" for "0", even if I type in a number such as "54656". Maybe, when it asks for the number, when I input the number, it just doesn't store it right, or something is wrong with my code...
You are trying to change global variables without declaring them:
a = 'bad'
def bad_fn():
a = 'good'
bad_fn()
print('bad_fn() is'+a)
def good_fn():
global a
a = 'good'
good_fn()
print('good_fn() is'+a)
results in
bad_fn() is bad
good_fn() is good
In general, using global variables in bad practice. Passing parameters explicitly makes debugging and code reuse much less of a headache. Here is rewritten version of your code which should be easier to understand:
# Test the Collatz conjecture:
# http://en.wikipedia.org/wiki/Collatz_conjecture
import profile
# Python 2/3 compatibility shim
import sys
if sys.hexversion >= 0x3000000:
# Python 3.x
inp = input
rng = range
else:
# Python 2.x
inp = raw_input
rng = xrange
# cache of already-seen values
seen = set([1])
def test(n):
visited = set()
while True:
if n in seen: # Ran into an already-seen chain that goes to 1
seen.update(visited)
return len(visited)
elif n in visited: # Closed loop! this should never happen
print('Loop found at n = {}'.format(n))
return None
else:
visited.add(n)
if n % 2: # n is odd?
n = 3*n + 1
else:
n //= 2
def do_profile(upto=1000000):
prof = profile.Profile()
prof.run('for n in rng(2, {}): test(n)'.format(upto))
prof.print_stats()
def main():
while True:
try:
n = int(inp('Enter a number to test (or x to exit): '))
except ValueError:
break
res = test(n)
if res is None:
print("Well, that's odd...")
else:
print("Chain terminated after {} values were tested".format(res))
if __name__=="__main__":
main()
It took 17.7s on my machine to run do_profile(1000000). It looked at a total of 2,168,611 numbers, the highest of which was 56,991,483,520. No loops were found.
Edit: I have added an inp() shim function; the code should now run in both Python 2 or Python 3.
Edit2: moved the profiling code into the main code listing and added range/xrange to the Python 2/3 shims.
If you want to change a global variable, you need to declare it preceded by global in your function, ie:
value = 0
def changeValue():
global value
value += 1
If you do not need to change the variable, global is not required.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I wrote a script to perform a connectivity search in a binary image (the possible values for the array are 0 and 1). For each pixel, the code looks at how many neighbours have intensity 1, and if there are at least 5 neighbours with I=1, it assigns 1 as a value of the considered pixel. I want the code to repeat the process until no new pixels are assigned intensity 1. At present the code is not performing the connectivity search iteratively; do you have any suggestion on how to fix this?
pixel_count = 0
pixel_counter = [0] * 100
for p in range(1, 100):
if p < 3:
continue
else:
if pixel_counter[p-1] > pixel_counter[p-2]:
continue
else:
break
for q in range(1, ran_x-1):
for r in range(1, ran_y-1):
counter = 0
if neighbours_mask_1[q,r] == 1:
counter = counter +1
if neighbours_mask_2[q,r] == 1:
counter = counter +1
if neighbours_mask_3[q,r] == 1:
counter = counter +1
if neighbours_mask_4[q,r] == 1:
counter = counter +1
if neighbours_mask_5[q,r] == 1:
counter = counter +1
if neighbours_mask_6[q,r] == 1:
counter = counter +1
if neighbours_mask_7[q,r] == 1:
counter = counter +1
if neighbours_mask_8[q,r] == 1:
counter = counter +1
if counter > 5:
mask_1[q,r] = 1
pixel_count = pixel_count + 1
print pixel_count
else:
mask_1[q,r] = 0
pixel_counter[p] = pixel_count
This section of the code:
for p in range(1, 100):
...
if pixel_counter[p-2] > pixel_counter[p-1]:
continue
else:
break
... dead code ...
will slurp all of the execution, the part where I've marked dead code, which contains your counters are never executed because they're unreachable.
I'm not quite sure what your trying to do there.
To answer the question in the title: the easiest way to exit a nested loop is to just move the loops into a function and return from that. E.g.
def f():
for i in range(10):
for j in range(10):
if i + j == 9: return