How to remove the following error? - python

The question was to find the symmetric difference between two sets without using the the corresponding method !
from future import print_function
M=int(raw_input())
X=map(int,raw_input().split())
N=int(raw_input())
Y=map(int,raw_input().split())
mys=set()
mys1=set()
for i in X:
mys.add(i)
for i in Y:
mys1.add(i)
un=mys.union(mys1)
inx=mys.intersection(mys1)
sd=un.difference(inx)
w=list(sd)
w=w.sort()
for i in (w):
print(w[i],end=' ')
Error occured is:
Traceback (most recent call last): File "hackset.py", line 18, in
<module>
for i in len(w): TypeError: object of type 'NoneType' has no len()**

list.sort does not return a new sorted function. It just sort the list (return None).
If you want to get a new list sorted, use sorted instead.
There's another issue. Iterating a list yields elements, you don't need to index them to get items; Just iterate without indexing.
for item in w:
print(item, end=' ')

Your error is here:
w=w.sort()
The return type for w.sort() is 'None'. The sort() method is in-place. Change it to just:
w.sort()

Related

Sorting list of strings by a character

I got the following assignment:
For a given list of strings write a function that returns a sorted list with all strings starting with the character x at the beginning (define two lists)
I stuck here:
set_words_list = ["argentinax", "football", "ss", "poxland", "axmerica"]
set_words_list.sort(key=str("x"))
print(set_words_list)
And then error pops out:
Traceback (most recent call last):
File "/5SortList/main.py", line 7, in <module>
set_words_list.sort(key=str("x"))
TypeError: 'str' object is not callable
It is my first time coding in Python, and I have no clue where to go from there.
On top of that, according to the task one needs to use 2 lists, yet I don't know how it can help me.
The simplest way is to split the input into two lists. One contains the elements that start with x, the other contains the rest. That's what the instructions meant by "define two lists".
Then sort each of these lists and concatenate them.
x_words = []
nox_words = []
for word in set_words_list:
if word.startswith("x"):
x_words.append(word)
else:
nox_words.append(word)
result = sorted(x_words) + sorted(nox_words)
list.sort(reverse=True|False, key=myFunc)
reverse --> Optional. reverse=True will sort the list descending. Default is reverse=False
key--> Optional. A function to specify the sorting criteria(s)
In below code we are passing myFunc to the key part of the sort function.
Function returns not e.startswith('x') since True == 1. This will sort the words starting with 'x'.
def myFunc(e):
return not e.startswith('x')
set_words_list = ["argentinax", "football", "ss", "poxland", "axmerica", 'xx']
set_words_list.sort(key=myFunc)
print(set_words_list)
set_words_list = ["argentinax", "football", "ss", "poxland", 'xamerica' ,"axmerica"]
x_first_letter = sorted([x for x in set_words_list if x[0]=='x'])
nox_first_letter = sorted([x for x in set_words_list if not x[0]=='x'])

Convert String to Dictionary

I have a string
str = "Name John"
I want to change it to a dictionary.
{"Name":"John"}
How do I achieve this?
I Have tried using comprehension but I get an error.
str = "Arjun 23344"
Name = {str.split()}
Error
Traceback (most recent call last):
File "/home/daphney/Python/AGame.py", line 2, in <module>
Name = {x.split()}
TypeError: unhashable type: 'list'
You can split:
my_dict = {str.split(" ")[0]:str.split(" ")[1]}
Note: If you have, say, Name John Smith and want the dict to be Name:Smith, then you can just change the [1] to [-1] to get the last indexed item.
You can create a dictionary using dict function by providing list of [key,value] lists (or (key,value) tuples):
my_str = "Arjun 23344"
Name = dict([my_str.split()])
print(Name) # output: {'Arjun': '23344'}
Name = dict([str.split()])
This would only work if your string always splits into exactly two words. This works because the split call returns a list of two elements, which is then stored inside a containing list, and passed to the dict constructor. The latter can work properly with a sequence (list or other) of pairs (lists or other).
This works in this particular case, but is not robust or portable.
As there are only two strings in your variable.
string = "Name Shivank"
k,v = string.split()
d = dict()
d[k] = v
print(d) #output: {'Name':'Shivank'}
you can provide a second parameter to the split function to limit the number of separations (to 1 in this case):
dict([string.split(" ",1)])

How to get values from a list of dictionary?

How to get the values from a list of dictionary??
For example: I want to get the output as 2?
data = [{'a':1,'b':2,'c':3}]
Below is the error am observing.
data['b']
Traceback (most recent call last):
File "", line 1, in
data['b']
TypeError: list indices must be integers, not str
The dictionary is the first element in data, so you can access it with:
data[0]['b']
If you have multiple dictionaries and you aim want to use them in a fallback order, you can use:
def obtain_value(list_of_dicts,key):
for dict in list_of_dicts:
if key in dict:
return dict[key]
raise KeyError('Could not find key \'%s\''%key)
and then call it with obtain_value(data,'b').

converting tuple to dictionary in python

I am trying to convert a line of string to dictionary where i am facing an error.
here is what i have and what i did:
line="nsd-1:quorum"
t=tuple(line.split(":"))
d=dict(t)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
d=dict(t)
ValueError: dictionary update sequence element #0 has length 5; 2 is required
Basically, what i want to achieve is to have a key value pair.
So if i have set of values separated by a ":", i want to have it as a key whatever is before the colon and after the colon needs to be the value for the key.
example: if i take the above string, i want "nsd-1" as my key and "quorum" as value.
Any help is appreciated.
Thanks
Wrap it in a list:
>>> dict([t])
{'nsd-1': 'quorum'}
There's also no need to convert the return value of split to a tuple:
>>> dict([line.split(':')])
{'nsd-1': 'quorum'}
Put t inside an empty list, like this:
d=dict([t])

Python List Index out of Range when Appending a List

When appending to a list in Python, I am getting the error:
Traceback (most recent call last):
File "/Volumes/HARDRIVE/Java/Python/Test.py", line 16, in <module>
cities.append([1][i])
IndexError: list index out of range
The list cities is initialized here:
cities = [[0 for x in range(math.factorial(CITIES)+3)] for x in range(math.factorial(CITIES)+3)]
Why is it producing this error when there is obviously enough space for the append operation (I gave the list three more than it needed)? What should I do to fix it? This is the loop that contains the line of code:
for i in range(0,CITIES):
cities.append([1][i])
cities.append([1][i])
holder=cities[0][i]
cities[0][i]=cities[CITIES+1][i]
cities[CITIES+1][i]=holder
Thanks
I think maybe you might want to append a new list onto your existing lists
cities.append([1,i,0])
as an aside you can reproduce the issue easily as mentioned in the comments without anything to do with appending
for i in range(3):
try: print i, [1][i]
except IndexError: print "LIST:[1] has no index", i

Categories

Resources