I have this assignment:
Define a function that takes in an arbitrary number of arguments, and returns a list containing only those arguments that are even. Don't run the function simply provide the definition.
What I've tried:
def myfunc(*args):
return list(args%2==0)
It should be as follows:
def a (*args):
l = []
for i in args:
if i%2 == 0:
l.append(i)
return l
def myfunc(*args):
a=[]
for num in args:
if (num%2 == 0):
a.append(num)
return a `
I think this should work.
def a (*args):
l = []
for i in args:
if i%2 == 0:
l += [i]
return l
Not sure if it is requires to be as arguments like in range(), iba4read's post shuld work just fine. Just in case i'll give you an examplie with a list, note that a ´tuple´ not alwais works as a list.
import random
array = []
for r in range(random.randint(2, 10)):
array.append(r)
def even_numbers_of(array):
new_array = []
for i in array:
if i % 2 == 0:
new_array.append(i)
return new_array
print(even_numbers_of(array))
Related
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
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'm learning python and in an exercise I need to write a function that takes an arbitrary number of arguments and returns a list containing only those arguments that are even.
My code is wrong I know: (But what is wrong with this code ?)
def myfunc(*args):
for n in args:
if n%2 == 0:
return list(args)
myfunc(1,2,3,4,5,6,7,8,9,10)
Do a list-comprehension which picks elements from args that matches our selection criteria:
def myfunc(*args):
return [n for n in args if n%2 == 0]
print(myfunc(1,2,3,4,5,6,7,8,9,10))
# [2, 4, 6, 8, 10]
This also could be helpful, however, the previous comment looks more advanced:
def myfunc(*args):
lista = []
for i in list(args):
if not i % 2:
lista.append(i)
return lista
Pick evens
def myfunc(*args):
abc = []
for n in args:
if n%2==0:
abc.append(n)
return abc
def myfunc(*args):
mylist = []
for x in list(args):
if x % 2 == 0:
mylist.remove(x)
return mylist
def myfunc(*args):
even=[]
for n in args:
if n %2==0:
even.append(n)
else:
pass
return even
myfunc(1,2,3,4,8,9)
def myfunc(*args):
#solution 1
# Create an empty list
mylist = []
for number in args:
if number %2 == 0:
mylist.append(number)
else:
pass
# return the list
return mylist
#solution 2
# Uses a list comprehension that includes the logic to find all evens and the list comprehension returns a list of those values
# return [n for n in args if n%2 == 0]
You need to create an empty list to contain the even numbers. Also convert your arguments to a list. Then append the even numbers to the newly created list.
def myfunc(*args):
new_list = []
for num in list(args):
if num % 2 == 0:
new_list.append(num)
else:
pass
return new_list
def myfunc(*args):
return [x for x in args if not x&1]
def myfunc(*args):
x=[]
for i in list(args):
if i%2==0:
x.append(i)
return x
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).
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