How can you join int and list together? - python

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

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

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)

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]

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]))

Related

Add a list of multisets in python

What is the pythonic way to merge a list of multisets into a single multiset?
For example,
from multiset import Multiset
set1 = Multiset('aab')
set2 = Multiset('abc')
ls = [set1, set2]
Based on using sets my guess was:
Multiset.add(*ls)
This gives an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.7/site-packages/multiset.py", line 931, in add
self._elements[element] += multiplicity
TypeError: unhashable type: 'Multiset'
Is there a better way than a for loop, as below?
def add_multisets(ls):
result = Multiset()
for i in ls:
result += i
return result
>>> add_multisets(ls)
Multiset({'a': 3, 'b': 2, 'c': 1})
You can use Multiset.combine(*ls)
i.e
from multiset import Multiset
set1 = Multiset('aab')
set2 = Multiset('abc')
ls = [set1, set2]
x = Multiset.combine(*ls)
print(x) # Multiset({'a': 3, 'b': 2, 'c': 2})

Recursively determining if a sequence is nondecreasing

I want to use recursion here but my code is not fully correct. It is correct for some of the test cases. Help me where I'm wrong. I have to return recursive statement. Basically, I don't want to expand my code.
def nondecreasing(l):
if l==[] or len(l) == 1:
return(True)
else:
return(nondecreasing(l[1:-1]) if (l[1]<=l[2]) else False)
This code should check if the list is non-decreasing or not. A list is a non-decreasing if each element is at least as big as the preceding one. For instance [], [7], [8,8,11] and [3,19,44,44,63,89] are non-decreasing, while [3,18,4] and [23,14,3,14,3,23] are not.
The longer nondecreasing test case fails:
>>> nondecreasing([3,19,44,44,63,89])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in nondecreasing
File "<stdin>", line 5, in nondecreasing
File "<stdin>", line 5, in nondecreasing
IndexError: list index out of range
You are doing two things wrong:
You seem to assume Python indexing is 1-based. It's not, you are ignoring the value of l[0]. This also causes an issue with trying to access l[2]; that index doesn't exist when your list only contains 2 elements.
>>> def nondecreasing(l):
... if l==[] or len(l) == 1:
... return(True)
... else:
... return(nondecreasing(l[1:-1]) if (l[1]<=l[2]) else False)
...
>>> nondecreasing([1, 2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in nondecreasing
IndexError: list index out of range
You are ignoring the last value of the list when recursing; slicing to [...:-1] removes the last element, causing you to fail to detect a single last decreasing value:
>>> nondecreasing([1, 2, 3, 4, 0])
True
The following code corrects both errors:
def nondecreasing(l):
if len(l) < 2:
return True
return nondecreasing(l[1:]) if l[0] <= l[1] else False
The l[1:] slice copies all elements except the first one.
Personally, I'd probably not use the conditional expression on the last line. The following is a little clearer:
def nondecreasing(l):
if len(l) < 2:
return True
if l[0] > l[1]:
return False
return nondecreasing(l[1:])
Demo:
>>> def nondecreasing(l):
... if len(l) < 2:
... return True
... if l[0] > l[1]:
... return False
... return nondecreasing(l[1:])
...
>>> nondecreasing([])
True
>>> nondecreasing([7])
True
>>> nondecreasing([8, 8, 11])
True
>>> nondecreasing([3, 19, 44, 44, 63, 89])
True
>>> nondecreasing([3, 18, 4])
False
>>> nondecreasing([23, 14, 3, 14, 3, 23])
False
Maybe it should be
def nondecreasing(l):
if len(l) <= 1:
return True
else:
# the l[1] <= l[2] should be l[0] <= l[1], and l[1:-1] should be l[1:]
return nondecreasing(l[1:]) if (l[0] <= l[1]) else False

Working with lists and slicing

This seems like an easy task and I honestly don't know what the problem is. I have a list such as [0,1,2,3,4,5,6] and such and I need to pick and index, lets say 3, and the output should look like [4,5,6,3,0,1,2] and here is my code
def cut_list(listA, index):
return listA[index+1:] + listA[index] + listA[0:index]
Yet the listA[index] function isn't working properly and giving an error, however if I take out the other parts and only do "return listA[index]" it will output 3
listA[index] is a scalar value which can't be concatenated with a list. You're doing something akin to:
>>> 3 + []
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Lists can only be concatenated with other lists, so the solution is to simply change listA[index] into a list with that as the only element. e.g. [listA[index]]:
def cut_list(listA, index):
return listA[index+1:] + [listA[index]] + listA[0:index]
To make it work for most sequence types, we can do a little clever slicing:
def cut_list(listA, index):
return listA[index+1:] + listA[index:index+1] + listA[0:index]
This works because the slice x[idx:idx+1] should return a sequence of the same type as x that has only the idx'th element from x.
>>> cut_list(range(10), 3)
[4, 5, 6, 7, 8, 9, 3, 0, 1, 2]
>>> cut_list('foo3bar', 3)
'bar3foo'
>>> cut_list(tuple(range(10)), 3)
(4, 5, 6, 7, 8, 9, 3, 0, 1, 2)

TypeError: 'itertools.combinations' object is not subscriptable

When I try to run:
temp = (twoset2[x][i][0]-twoset[x][i][1])
I get:
TypeError: 'itertools.combinations' object is not subscriptable
My code:
for x in range(0,64):
for i in range(0,1):
temp = (twoset2[x][i][0]-twoset[x][i][1])
DSET[counter2]= temp
temp = 0
counter2 += 1
Basically what I am trying to do is: I have a list (twoset2) of 2 element subsets of coordinates (so an example: ((2,0) (3,3)). I want to access each individual coordinate, and then take the difference between x and y and place it into DSET, but I get the above error when trying to run.
Please help!
itertools.combinations returns a generator and not a list. What this means is that you can iterate over it but not access it element by element with an index as you are attempting to.
Instead you can get each combination like so:
import itertools
for combination in itertools.combinations([1,2,3], 2):
print combination
This gives:
(1, 2)
(1, 3)
(2, 3)
twoset2 is not a list; it is an itertools.combinations object (which does not support indexing):
>>> import itertools
>>> itertools.combinations([1, 2, 3], 2)
<itertools.combinations object at 0x01ACDC30>
>>>
>>> twoset2 = itertools.combinations([1, 2, 3], 2)
>>> twoset2[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'itertools.combinations' object is not subscriptable
>>>
You will need to explicitly convert this into a list if you want a list:
twoset2 = list(itertools.combinations(...))

Strange error with range type in list assignment

r = range(10)
for j in range(maxj):
# get ith number from r...
i = randint(1,m)
n = r[i]
# remove it from r...
r[i:i+1] = []
The traceback I am getting a strange error:
r[i:i+1] = []
TypeError: 'range' object does not support item assignment
Not sure why it is throwing this exception, did they change something in Python 3.2?
Good guess: they did change something. Range used to return a list, and now it returns an iterable range object, very much like the old xrange.
>>> range(10)
range(0, 10)
You can get an individual element but not assign to it, because it's not a list:
>>> range(10)[5]
5
>>> r = range(10)
>>> r[:3] = []
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
r[:3] = []
TypeError: 'range' object does not support item assignment
You can simply call list on the range object to get what you're used to:
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> r = list(range(10))
>>> r[:3] = [2,3,4]
>>> r
[2, 3, 4, 3, 4, 5, 6, 7, 8, 9]
Try this for a fix (I'm not an expert on python 3.0 - just speculating at this point)
r = [i for i in range(maxj)]

Categories