How can you join int and list together?

129 Views Asked by At

But I still can't find the join function anywhere else on the internet. The main problem is that the head(items) is int and tail(items) is list, and I can't combine head and tail together. Here is the code I tried:

def head(items):  
    return items[0]  
def tail(items):
    return items[1:]  
def isEven(x):  
     return x % 2 == 0  
def extractEvens(items):  
    if (items == None):  
        return None  
    elif (isEven(head(items))):  
        return join(head(items),extractEvens(tail(items)))  
    else:  
        return extractEvens(tail(items)) 



a = [4,2,5,2,7,0,8,3,7]  
print(extractEvens(a))  

Here is the link for the page I tried to study: The is the code for filter pattern: link_of_code

4

There are 4 best solutions below

1
On

Please, provide an example of the desired output.

If you want to create a new list, merging a list with an int, it should be:

return [head(items)] + tail(items)
1
On

what you need is append

>>> a=6
>>> b=[1,2,3,4]
>>> b.append(a)
>>> b
[1, 2, 3, 4, 6]

here you just cant concanate list and int:

>>> a=6
>>> b=[1,2,3,4]
>>> a+b
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> list(a)+b
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

but if you do str, it will concanated as str not int:

>>> list(str(a))+b
['6', 1, 2, 3, 4]
0
On

You can also try insert which is even more useful as the head must be in the starting.

l = extractEvens(tail(items))
l.insert(0,head(items))
return l
0
On

There are multiple errors in your code:

def isEven(x):
    return x % 2 == 0 # x % 2 not x % ==


def extractEvens(items):
    if not items:
        return [] # return empty list not None
    elif isEven(head(items)):
         # convert ints to strings and put head(items) in a list 
        return "".join(map(str,[head(items)]) + map(str,extractEvens(tail(items)))) 
    else:
        return extractEvens(tail(items))

You can also do this in a single list comprehension:

a = [4, 2, 5, 2, 7, 0, 8, 3, 7]
print("".join([str(x) for x in a if not x % 2]))