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)
Related
I am trying to get better at writing more 'clean' and/or elegant code. I have seen examples around but I can't make them work for this particular example. Logic is very simple and I'm hoping that with some pointers on punctuation or syntax I can pick up the habit.
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
elist = []
evenlist = [i for i in a if a % 2 == 0]
print(evenlist)
I have only been able to make this work on the longer format here below:
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
elist = []
for i in a:
if i % 2 == 0:
elist.append(i)
print(elist)
Should be this:
evenlist = [i for i in a if i % 2 == 0]
evenlist = [i for i in a if a % 2 == 0]
# ^
# Hmmm!
You probably wat to be checking i (an element) for evenness, rather than a (the entire list). Checking a list for evenness doesn't make much sense unless there's some magic happening in the background that ensures every element in the list is even. But there's not:
>>> [1,2,3] % 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'list' and 'int'
As an aside, there's another way to do this, specifically:
list(filter(lambda x: x % 2 == 0, a))
I think this is less readable myself but I suspect it may be more space-efficient if you just want to process them rather than create a list from them:
for item in filter(lambda x: x % 2 == 0, a):
do_something_with(item)
That doesn't create a whole new list, instead simply retrieving values from the existing list that match the filter criteria. Probably won't matter unless your lists tend to get large.
What I am attempting to accomplish is to create a union of two dictionaries (consisting of single integers i.e. 1, 2, 3, 4, etc.) by taking the keys out of the dictionary, putting them into two lists, joining the two lists and then putting them back into a new dictionary that contains both lists. However, I am running into the
TypeError: unsupported operand type(s) for +:
'builtin_function_or_method' and 'builtin_function_or_method'
How would I get around this error?
Here are the relevant pieces of code.
class DictSet:
def __init__(self, elements):
self.newDict = {}
for i in elements:
self.newDict[i] = True
def union(self, otherset):
a = self.newDict.keys
b = otherset.newDict.keys
list1 = a + b
new = DictSet(list1)
return new
def main():
allints = DictSet([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
odds = DictSet([1, 3, 5, 7, 9])
evens = DictSet([2, 4, 6, 8, 10])
Why not use dict.update()?
def union(self, otherset):
res = DictSet([])
res.newDict = dict(self.newDict)
res.newDict.update(otherset.newDict)
return res
You must call the keys() method. Try this:
a = self.newDict.keys()
b = otherset.newDict.keys()
EDIT: I see you are using Python3. In that case:
a = list(self.newDict)
b = list(otherset.newDict)
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]))
Of course I get it you use sum() with several numbers, then it sums it all up, but I was viewing the documentation on it and I found this:
sum(iterable[, start])
What is that second argument "[, start]" for? This is so embarrasing, but I cannot seem to find any examples with google and the documentation is fairly cryptic for someone who tries to learn the language.
Is it a list of some sort? I cannot get it to work. Here is an example of one of my attempts:
>>> sum(13,4,5,6,[2,4,6])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum expected at most 2 arguments, got 5
The start indicates the starting value for the sum, you can equate this:
sum(iterable, start)
with this:
start + sum(iterable)
The reason for your error is that you're not encapsulating the numbers to sum in an iterable, do this instead:
sum([13, 4, 5, 6])
This will produce the value of 28 (13+4+5+6). If you do this:
sum([13, 4, 5, 6], 25)
You get 53 instead (13+4+5+6 + 25).
Also, please keep in mind that if you create a nested list (like you sortof have above) sum will give you an error (trying to add an integer to a list, isn't clear - are you trying to append or add it to the sum of the list or what?). So will trying to use two lists, + is overloaded and would just normally concatenate the two lists into one but sum tries to add things so it wouldn't be clear what you're asking.
It's easier to explain with examples:
>>> mylist = [13, 4, 5, 6, [2,4,6]]
>>> sum(mylist)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> a = [13, 4, 5, 6]
>>> b = [2,4,6]
>>> c = [a,b]
>>> c
[[13, 4, 5, 6], [2, 4, 6]]
>>> sum(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> c = a+b
>>> c
[13, 4, 5, 6, 2, 4, 6]
>>> sum(c)
40
>>> sum(c, 23)
63
Hope this helps.
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)]