This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 1 year ago.
I have made 2 functions: one to generate random values from 0 to 20, and another to check if the value generated by function random matches the value of list. If the value matches then random should start again to produce new value
My code is:
import random
mylist=[6,2,4]
y=int()
def randoom():
str=random.randint(0,20)
return str
def checklist():
y=randoom()
print(y,"Generated value y")
if y in mylist:
print(y,"already exist in list")
checklist()
if y not in mylist:
return y
for b in range(1,10):
x=checklist()
print(x," X got the value")
mylist.append(x)
print(mylist)
My output is: [6, 2, 4, 5, 12, 7, 16, 13, None, 17, 19, None]
Why is None getting appended?
I tried everything in last 3 days to figure out why None is getting appended in list even when I made sure the function runs again to produce a new value of y if it matches the list.
Your checklist function can return None if y is in mylist:
if y in mylist:
print(y,"already exist in list")
checklist() # Executes checklist again, but discards the return value
There is no path after this that can return a value, so the function returns None. You can fix this by returning checklist():
if y in mylist:
print(y,"already exist in list")
return checklist() # Executes checklist again, but returns the value
The return value of checklist is not being saved in your variable after being executed. Fixing this should make your Code work.
Still, you have at the very top of your program a variable named str. Since str is also a function in python, this could cause issues down the road. I would recommend to change this.
Related
This question already has answers here:
"Least Astonishment" and the Mutable Default Argument
(33 answers)
Why does using `arg=None` fix Python's mutable default argument issue?
(5 answers)
Closed 2 years ago.
I'm trying to check number of "stopping times" of Collatz sequence. The script appends result of every function "step" in a list which length I use to figure out overall number of "steps". the script is ok, but! Whenever I use several times it returns wrong length of a list. I don't know wht but it keeps previous length of a list and adds it to the next function result.
def stopping_time(n, l=[]):
if n == 1:
return
elif n % 2 == 0:
n = n // 2
l.append(n)
stopping_time(n)
else:
n = n * 3 + 1
l.append(n)
stopping_time(n)
return len(l)
a = stopping_time(4)
b = stopping_time(13)
c = stopping_time(19)
d = stopping_time(27)
print(a, b, c, d)
# 'a' shoulb be 2, 'b' should be 9, 'c' should be 20 and 'd' should be 111
# instead its 2, 11, 31, 142
Any thoughts?
It's not a bug, but a feature. Python indeed memorizes mutable values passed as default arguments between calls (cf. https://docs.quantifiedcode.com/python-anti-patterns/correctness/mutable_default_value_as_argument.html).
The solution may be passing the sentinel value as an argument, something like:
def foo(bar=None):
if bar is None:
bar=[]
...
In general, you set your list argument to None by default and then set it inside the function to [] if no other value was passed by the caller.
This question already has answers here:
What's the canonical way to check for type in Python?
(15 answers)
Closed 3 years ago.
I need to check if a value is a list before carrying out the rest of the code. The for loop should only be run if my_list is a list.
sum=0
if not list:
print("The input is not a list or is empty.")
exit()
for item in (list):
sum+=1
print("The length of the list is ",sum)
my_list = "Hello";
list_length(my_list)
The code works as expected when my_list is an actual list, but if I set it equal to a string, "Hello" at the moment in my code, the output is 5, I want it to not have an output.
you can use
if isinstance([], list):
print("this is list")
to check.
and if you want to check is subclass, you can use
if issubclass(sub_class, your_class):
print(f"this is subclass of {your_class}")
This question already has answers here:
What is the difference between `sorted(list)` vs `list.sort()`?
(7 answers)
Closed 4 years ago.
I was trying to sort list elements inside a function without return when I try to print the list by its name it does not get sorted, but it is sorted inside a function.
I have to update the list inside the function without returning
def sort(n):
n.append(10)
sorted(n)
n = [5,1,2,3]
print(n)
Expected : [1,2,3,5]
actual: [5,1,2,3]
I'm sorry, I made a series of mistakes myself. It's a lesson for me too.
def isort(n):
n.append(10)
n.sort() #I used n[:] = sorted(n), but it's superfluous.
n = [5,1,2,3]
isort(n)
print(n)
m = [7,9,3,13]
isort(m)
print(m)
output:
[1, 2, 3, 5, 10]
[3, 7, 9, 10, 13]
sort is an existed fuction in python, need to change it to other name. I changed to isort.
We have to call the function isort to let it do its work.
We need to update the elements in the list to make the list update. [:] Slice notation here.
It's better to use different name between function argument and the call. (n and m here).
Many thanks to DYZ, Primusa, and Tomothy32 :)
This question already has answers here:
Basics of recursion in Python
(5 answers)
Closed 4 years ago.
I'm quite new to recursion and I have to solve a problem for my homeworks which asks to define a recursive function to get the next element on a given item of a list.
I made the iterative version but I don't understand how to write the recursive one.
def next_value(lst,v):
ind = lst.index(v)
list1_result = lst[ind+1]
return list1_result
a = [4, 2, 10, 3, 2, 5]
print(next_value(a,10))
# output: 3
Your solution seems okay but if it absolutely has to be recursive, here's an example implementation:
def next_value(lst, v):
if (len(lst) < 2):
return None
if (lst[0] == v):
return lst[1]
return next_value(lst[1:], v)
Basically we pass slices from the same list until we find an element with the given value. If the length is less than 2, the list is either empty or we have looked through it all. In that case we return None to denote that there is no valid answer.
This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
Closed 7 months ago.
Very new to programming.
Wondering why does this example print all the items in the list, while the second example prints only the first?
def list_function(x):
for y in x:
print(y)
n = [4, 5, 7]
list_function(n)
def list_function(x):
for y in x:
return y
n = [4, 5, 7]
print(list_function(n))
Your first example iterates through each item in x, printing each item to the screen. Your second example begins iterating through each item in x, but then it returns the first one, which ends the execution of the function at that point.
Let's take a closer look at the first example:
def list_function(x):
for y in x:
print(y) # Prints y to the screen, then continues on
n = [4, 5, 7]
list_function(n)
Inside the function, the for loop will begin iterating over x. First y is set to 4, which is printed. Then it's set to 5 and printed, then 7 and printed.
Now take a look at the second example:
def list_function(x):
for y in x:
return y # Returns y, ending the execution of the function
n = [4, 5, 7]
print(list_function(n))
Inside the function, the for loop will begin iterating over x. First y is set to 4, which is then returned. At this point, execution of the function is halted and the value is returned to the caller. y is never set to 5 or 7. The only reason this code still does print something to the screen is because it's called on the line print list_function(n), so the return value will be printed. If you just called it with list_function(n) as in the first example, nothing would be printed to the screen.
For functions return terminates the execution, therefore nothing will be executed after return.
In your case the first function will print all the items because there is nothing that breaks the process. However in the second function it will return and end the process.