def list_num_checker(num_list):
for x in num_list:
if x%2==0:
return x
else:
continue
I just began learning Python and this is the code I have written to create a function to return all the even values in a list. However, It breaks down after checking the first even number.E.g.
list_num_checker([1,2,3,4,5,6])
2
Any and all help is appreciated.
return will cause a function to exit... if you use yield you can make it a generator
def list_num_checker(num_list):
for x in num_list:
if x%2==0:
yield x # yield makes this a generator instead
# else: # you don need the else
# continue
for evennum in list_num_checker([1,2,3,4,5,6,7,8]):
print(evennum)
you could also make a list comprehension
print([x for x in num_list if x%2 == 0])
or you could use the builtin filter function
def is_even(num):
return num % 2 == 0
list(filter(is_even,num_list)) # its a generator so you need to call list on it
I think you can use yield instead of return since return will break the for loop and immediately returns the give value
def list_num_checker(num_list):
for x in num_list:
if x%2==0:
yield x
else:
continue
divisible2 = list(list_num_checker([1,2,3,4,5,6]))
Some possible alternative approaches would be to use list comprehension or filter
def list_num_checker(num_list):
return [x for x in num_list if x % 2 == 0]
def list_num_checker(num_list):
return filter(lambda x: x % 2 == 0, num_list)
return will immediately terminate the function. To produce multiple values in one function, use yield instead.
def list_num_checker(num_list):
for x in num_list:
if x%2==0:
yield x
else:
continue
Related
My code:
def shorter(lst):
if len(lst) == 0:
return []
if lst[0] in lst[1:]:
lst.remove(lst[0])
shorter(lst[1:])
return lst
print shorter(["c","g",1,"t",1])
Why does it print ["c","g",1,"t",1] instead of ["c","g","t",1]
For a recursive method, what you can do is check a specific index in the again as you have it. If we remove the current element, we want to stay at the same index, otherwise we want to increase the index by one. The base case for this is if we are looking at or beyond the last element in the array since we don't really need to check it.
def shorter(lst, ind=0):
if ind >= len(lst)-1: #Base Case
return lst
if lst[ind] in lst[ind+1:]:
lst.pop(ind)
return shorter(lst,ind)
return shorter(lst, ind+1)
#Stuff to test the function
import random
x = [random.randint(1,10) for i in range(20)]
print(x)
x = shorter(x)
print(x)
Another way to solve this in a single line is to convert the list into a set and then back into a list. Sets have only unique values, so we can use that property to remove any repeating elements.
import random
x = [random.randint(1,10) for i in range(20)]
print(x)
x = list(set(x)) #Converts to set and back to list
print(x)
A possible recursive solution could be:
def shorter(lst):
if lst:
if lst[0] in lst[1:]:
prefix = [] # Skip repeated item.
else:
prefix = [lst[0]] # Keep unique item.
return prefix + shorter(lst[1:])
else:
return lst
The previous code can also be compacted to:
def shorter(lst):
if lst:
return lst[0:(lst[0] not in lst[1:])] + shorter(lst[1:])
else:
return lst
and the function body can also be reduced to a one-liner:
def shorter(lst):
return (lst[0:(lst[0] not in lst[1:])] + shorter(lst[1:])) if lst else lst
or even:
def shorter(lst):
return lst and (lst[0:(lst[0] not in lst[1:])] + shorter(lst[1:]))
I am trying to append values (x) to a list if the numbers are divisible by 2 and then print out that list. Seems pretty simple. The following runs but returns None:
x = []
def test():
while x in range(0,100):
if x % 2 == 0:
x.append()
print(test())
Use for to iterate a range - not while.
You have ambiguous meaning to x - both as iteration variable and as a list.
You need to pass the value to append.
You need to return a value so it would be printed through the print statement - otherwise None is the default.
Fixed:
x = []
def test():
for i in range(0,100):
if i % 2 == 0:
x.append(i)
return x
print(test())
Other notes:
You can only use this once. The next call for test would return a list twice the size, since x is a global variable. I believe this is unintended and can be solved by putting the x = [] inside the function.
A list comprehension like [x for x in range(100) if x % 2 == 0] would be much better.
Problems and Fixes
Your have several problems with your code:
You named your list x and your iterate variable x.
You never append a value to your list.
You never return a list from test. Rather than appending to a global list, make a local list in test and return that list.
You're using a while loop when you should be using a for loop.
After the above changes, you code look likes:
def test():
even_numbers = []
for number in range(0, 100):
if number % 2 == 0:
even_numbers.append(number)
return even_numbers
print(test())
Improvements
Note there are better ways to do this. In this case, a list comprehension is a better choice. List comprehensions can be used to avoid the common pattern of building a list of values - such as your case:
def test():
return [n for n in range(0, 100) if n % 2 == 0]
print(test())
Generally you should pass the variable to the function and return it from the function instead of relying on global variables:
def test(x):
...
return x
However while x in range(0, 100) won't work because it will check if x (an empty list) is contained in the range object. But the range only contains numbers so the while loop body will never execute. So you could use a for-loop instead:
def test(x):
for i in range(0, 100):
if i % 2 == 0:
x.append(i)
return x
But you could also use the fact that range supports a step and remove the if by just using step=2:
def test(x):
for i in range(0, 100, 2):
x.append(i)
return x
At this point you could even just extend (append an iterable to) the list:
def test(x):
x.extend(range(0, 100, 2))
return x
You could also use a step of 2 to avoid if tests :
x = []
def test():
for i in range(0,100,2):
x.append(i)
return x
Or use a list comprehension :
x = []
def test():
x = [i for i in range(0,100,2)]
return x
Or use the range it's self as a list:
x = []
def test()
x = list(range(0,100,2))
return x
Rename your inner x variable for simplicity. Use x.append(n) instead of x.append(). Finally, print the variable not the method.
You should either change the list variable or the iteration variable(x in while loop) . and append function works like this list.append(value).
when I run the following code, I did not get the correct answer. It returns [4] when it should return [4, 4].
def purify(y):
new_numbers = []
for x in y:
if x%2 ==0:
new_numbers.append(x)
return new_numbers
print(purify([4,5,5,4]))
Your indent is off, place the return after the for loop runs
def purify(y):
new_numbers = []
for x in y:
if x%2 ==0:
new_numbers.append(x)
return new_numbers
Use some elegant expressions like list comprehension combined with if something like this
def purify(y):
return [x for x in y if x%2 == 0]
You should be careful with indentation when working with Python as below code is good but there is an issue with indentation on return new_numbers.
return new_numbers is aligned with if condition due to which for loop only runs once and returns the first 4. If you indent return statement with for loop it will work perfectly.
def purify(y):
new_numbers = []
for x in y:
if x%2 ==0:
new_numbers.append(x)
return new_numbers
print(purify([4,5,5,4]))
You can do this in just one line:
def purify(y):
return [x for x in y if not x%2]
just use lamda :
def purify(y):
filter(lambda i: not i%2==0, y)
Here is a problem that I am having trouble solving:
Write a function naturalNumbers which takes a positive integer n as input, and returns a list [1, 2, ...] consisting of the first n natural numbers.
Here is the code that I have so far:
def naturalNumbers(x):
x = input()
myList = []
for i in range (0, x):
return myList = myList + [i]
print(myList)
I'm really confused as to when to put return for functions.
you are working very hard
the function range() returns a an object castable to list, so all you need to do is
def naturalNumbers(x):
return list(range(1,x + 1)) #didnt notice we are in python 3
0 is not considered a natural number
Your are mixing both your 'main' code and the function that you are being asked to write.
let your function be only for your list generating function naturalNumbers.
and use a different main function.
you can ignore the main method and the if __name__ = '__main__'
this is just to run correctly with good form.
# this method outputs a list from 0 to x
def naturalNumbers (x):
l = list[]
for i in range(0, x+1):
list.append(i)
return l
def main():
x = input()
# should check if x is an integer (defensive programming)
print (naturalNumbers(x))
if __name__ = "__main__"
main()
also depending on the definition used natural numbers can start form 0 or 1
Return is the output from a function. Without the return the function doesn't 'give back' anything to where it was called.
def naturalNumbers(n):
return [x for x in range(0,n)]
print(naturalNumbers(5))
The above print statement uses the output of natural numbers and will print [0,1,2,3,4].
Say we remove the return and just assign it to a value.
def naturalNumbers(n):
numbers = [x for x in range(0,n)]
#assignment rather than return, we could do other operations.
print(naturalNumbers(5))
#returns None
The above print statement prints 'None' as this is the default return value in Python
def naturalNumbers(n):
n = input()
myList = []
for i in range(1, n + 1):
myList.append(i)
return myList
Or use list comprehension:
def naturalNumbers(n):
n = input()
myList = [i for i in range(1, n + 1)]
return myList
return is the end of a function, it should be outside of a loop.
Try this simple method:
def naturalNumbers(n):
myList = []
for i in range(0,n):
myList = myList+[i+1]
return myList
I'm trying to define a method to check whether or not every element of a list is a factor of the parameter.
Here's what I have:
def factorall(x):
if all(x % num for num in nums) == 0:
return True
else:
return False
(In this case nums is a list of the integers from 1 to 10)
However, this returns true for any number. I'm assuming this happens because it is only checking 1 and then returning True, but shouldn't all() be checking for every element of the list before returning True?
I'm a bit unfamiliar with all() so I probably implemented it incorrectly. Can someone point me in the right direction?
Thanks!
you should use not any instead of all
def factorall(x):
return not any(x%num for num in nums) #if any of these is a value other than 0
or if you want it like you currently have it
def factorall(x):
return all(x%num==0 for num in nums)
You should do the comparison inside the all function, or simply remove it, and use negation of the result x % num:
def factorall(x):
return all(not x % num for num in nums)
The return statement works same as:
return all(x % num == 0 for num in nums)
I agree that the 2nd one seems clearer.
def factorall(x):
if all(x % num == 0 for num in nums):
return True
else:
return False