The input for this program are two sets. Each set in a separate line; elements of the set are space separated.
Your program must output the symmetric difference of these sets.
Example
Symmetric difference of the sets {1, 2, 3} and {0, 1, 2} equals to {0, 3}.
Sample Input:
1 2 3
0 1 2
Sample Output:
0 3
My Solution :
set_1 = set(input())
set_2 = set(input())
difference_set1 = set_1 - set_2
difference_set2 = set_2 - set_1
for x in difference_set1:
difference_set2.add(x)
for x in difference_set2:
print(x, end=' ')
Test Results are failing... Can somebody please explain :
You code works fine. Below is the driver test for the same.
IN : 1 2 3
IN : 0 1 2
OUT : 0 3
But, there is a small logical mistake.You are not handling your inputs properly. But in the end, fortunately for you, it cancels out the problem it might create.
They should be :
set_1 = set(map(int,input().split()))
set_2 = set(map(int,input().split()))
#OR just
set_1 = set(input().split())
set_2 = set(input().split())
A quick glance at the workings of your code and the correct code.
>>> s = set(input()) #your code
1 2 3
>>> s
=> {'1', '2', ' ', '3'}
>>> s = set(map(int, input().split())) #should be
1 2 3
>>> s
=> {1, 2, 3}
Let's print your inputs:
input_set = set(input())
print(input_set)
For the input 1 2 3, it prints {' ', '3', '1', '2'}
For the input 1,2,3, it prints {',', '3', '1', '2'}
For the input 123, it prints {'3', '1', '2'}
As you can see, your inputs are problematic.
You can use inputs without spaces such as 123 and 012.
Or, if you want to use space between 2 numbers, you can use split():
input_set = set(input().split())
print(input_set)
Input:
1 2 3
Output:
{'3', '2', '1'}
Related
Could someone, please, explain why .join() behaves in the following way:
input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join(str(input))
print(a)
And the result is:
[ 1 , 0 , 5 , 3 , 4 , 1 2 , 1 9 ]
Not only is there still a list, but also an additional space.
How come?
When I use map() it works:
a = " ".join(list(map(str, input)))
But I would like to know what is wrong with the .join method I'm using.
str(input) returns one string '[1, 0, 5, 3, 4, 12, 19]', so then join uses each character of the string as input (a string is an iterable, like a list), effectively adding a space between each.
The effect is more visible if we join with a -: '[-1-,- -0-,- -5-,- -3-,- -4-,- -1-2-,- -1-9-]'
In contrast, list(map(str, input)) converts each number to string, giving a list of strings (['1', '0', '5', '3', '4', '12', '19']), which join then converts to '1 0 5 3 4 12 19'
See #mozway's answer to understand .join()'s behavior.
To get what you want (using join), you should try this:
input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join([str(i) for i in input])
print(a)
Output:
1 0 5 3 4 12 19
So I have a dictionary with letter values and keys and I want to generate an adjacency matrix using digits (0 or 1). But I don't know how to do that.
Here is my dictionary:
g = { "a" : ["c","e","b"],
"b" : ["f","a"]}
And I want an output like this :
import numpy as np
new_dic = {'a':[0,1,1,0,1,0],'b':(1,0,0,0,0,1)}
rows_names = ['a','b'] # I use a list because dictionaries don't memorize the positions
adj_matrix = np.array([new_dic[i] for i in rows_names])
print(adj_matrix)
Output :
[[0 1 1 0 1 0]
[1 0 0 0 0 1]]
So it's an adjacency matrix: column/row 1 represent A, column/row 2 represent B ...
Thank you !
I don't know if it helps but here is how I convert all letters to numbers using ascii :
for key, value in g.items():
nums = [str(ord(x) - 96) for x in value if x.lower() >= 'a' and x.lower() <= 'z']
g[key] = nums
print(g)
Output :
{'a': ['3', '5', '2'], 'b': ['6', '1']}
So a == 1 b == 2 ...
So my problem is: If a take the keys a with the first value "e", how should I do so that the e is found in the column 5 line 1 and not in the column 2 line 1 ? and replacing the e to 1
Using comprehensions:
g = {'a': ['c', 'e', 'b'], 'b': ['f', 'a']}
vals = 'a b c d e f'.split() # Column values
new_dic = {k: [1 if x in v else 0 for x in vals] for k, v in g.items()}
I just learned that numpy.fromstring() is a handy function:
a = ('1 2 3')
# convert to list of numbers
b = np.fromstring(a, sep=' ')
Now I modified the b and want to convert it back to a list of strings. Is there a built-in function in numpy to do that?
Sorry my original question might be not accurate. What I want to do is to convert b into the same format as a.
In [490]: a='1 2 3'
If you want b elements to be integers, as opposed to float, specify the dtype.
In [491]: b=np.fromstring(a, sep=' ',dtype=int)
In [492]: b
Out[492]: array([1, 2, 3])
In [493]: b += 2 # typical array math
In [494]: b
Out[494]: array([3, 4, 5])
Normal array display string, via print or str. Note that the array str omits the comma; that's just a visual clue distinguishing it from a list.
In [495]: print(b)
[3 4 5]
In [496]: str(b)
Out[496]: '[3 4 5]'
We can strip off the [] to get a display like a
In [497]: str(b)[1:-1]
Out[497]: '3 4 5'
But ' '.join is a good list formatting trick:
In [500]: [str(i) for i in b]
Out[500]: ['3', '4', '5']
In [501]: ' '.join([str(i) for i in b])
Out[501]: '3 4 5'
We could just as easily split a into a list of strings, modify those, and rejoin
In [506]: a1=a.split()
In [508]: a1
Out[508]: ['1', '2', '3']
In [509]: a1[1]='34'
In [510]: a1
Out[510]: ['1', '34', '3']
In [511]: ' '.join(a1)
Out[511]: '1 34 3'
According to these answers ans.1 & ans.2:
You can solve this by python itself or using numpy.
pure python solution:
map(str, b)
# ['1.0' '2.0' '3.0']
numpy solution:
list(np.char.mod('%d', b))
# ['1' '2' '3']
List comprehension solution:
' '.join(str(x) for x in b)
# '1.0 2.0 3.0'
or:
' '.join("%d" % x for x in b)
# '1 2 3'
Just figured (probably) the easiest way:
str(b)
:0)
I am trying to use raw_input in the python code to get user input of lists as below.
input_array.append(list(raw_input()));
User input as:
1 2 3 5 100
But the code is interpreting input as
[['1', ' ', '2', ' ', '3', ' ', '5', ' ', '1', '0', '0']]
Try: If I use plain input() instead of raw_input(), I am facing the issue in console.
"SyntaxError: ('invalid syntax', ('<string>', 1, 3, '1 2 3 4 100'))"
Note: I am not allowed to give the input in list format like
[1,2,3,5,100]
Could somebody please tell me how to proceed further.
>>> [int(x) for x in raw_input().split()]
1 2 3 5 100
[1, 2, 3, 5, 100]
>>> raw_input().split()
1 2 3 5 100
['1', '2', '3', '5', '100']
Creates a new list split by whitespace and then
[int(x) for x in raw_input().split()]
Converts each string in this new list into an integer.
list()
is a function that constructs a list from an iterable such as
>>> list({1, 2, 3}) # constructs list from a set {1, 2, 3}
[1, 2, 3]
>>> list('123') # constructs list from a string
['1', '2', '3']
>>> list((1, 2, 3))
[1, 2, 3] # constructs list from a tuple
so
>>> list('1 2 3 5 100')
['1', ' ', '2', ' ', '3', ' ', '5', ' ', '1', '0', '0']
also works, the list function iterates through the string and appends each character to a new list. However you need to separate by spaces so the list function is not suitable.
input takes a string and converts it into an object
'1 2 3 5 100'
is not a valid python object, it is 5 numbers separated by spaces.
To make this clear, consider typing
>>> 1 2 3 5 100
SyntaxError: invalid syntax
into a Python Shell. It is just invalid syntax. So input raises this error as well.
On an important side note:
input is not a safe function to use so even if your string was '[1,2,3,5,100]' as you mentioned you should not use input because harmful python code can be executed through input.
If this case ever arises, use ast.literal_eval:
>>> import ast
>>> ast.literal_eval('[1,2,3,5,100]')
[1, 2, 3, 5, 100]
I want to create a matrix.
Input:
data = [
{'a': 2, 'g': 1},
{'p': 3, 'a': 5, 'cat': 4}
...
]
Output:
a p cat g
1st 2 0 0 1
2nd 5 3 4 0
This is my code. But I think it's not smart and very slow when data size huge.
Have any good ways to do this one?
Thank you.
data = [
{'a': 2, 'g': 1},
{'p': 3, 'a': 5, 'cat': 4}
]
### Get keyword map ###
key_map = set()
for row in data:
key_map = key_map.union(set(row.keys()))
key_map = list(key_map) # ['a', 'p', 'g', 'cat']
### Create matrix ###
result = []
for row in data:
matrix = [0] * len(key_map)
for k, v in row.iteritems():
matrix[key_map.index(k)] = v
result.append(matrix)
print result
# [[2, 0, 0, 1], [5, 3, 4, 0]]
Edited
By #wwii advice. Use Pandas looks good:
from pandas import DataFrame
result = DataFrame(data, index=range(len(data)))
print result.fillna(0, downcast=int).as_matrix().tolist()
# [[2, 0, 1, 0], [5, 4, 0, 3]]
You can use set comprehension to generate the key_map
key_map = list({data for row in data for data in row})
Here is a partial answer. I couldn't get the columns in the order specified - it is limited by how the keys get ordered in the set, key_map. It uses string formatting to line the data up - you can play around with the spacing to fit larger or smaller numbers.
# ordinal from
# http://code.activestate.com/recipes/576888-format-a-number-as-an-ordinal/
from ordinal import ordinal
data = [
{'a': 2, 'g': 1},
{'p': 3, 'a': 5, 'cat': 4}
]
### Get keyword map ###
key_map = set()
for row in data:
key_map = key_map.union(set(row.keys()))
key_map = list(key_map) # ['a', 'p', 'g', 'cat']
# strings to format the output
header = '{: >10}{: >8}{: >8}{: >8}'.format(*key_map)
line_fmt = '{: <8}{: >2}{: >8}{: >8}{: >8}'
print header
def ordered_data(d, keys):
"""Returns an ordered list of dictionary values.
returns 0 if key not in d
d --> dict
keys --> list of keys
returns list
"""
return [d.get(key, 0) for key in keys]
for i, thing in enumerate(data):
print line_fmt.format(ordinal(i+1), *ordered_data(thing, key_map))
Output
a p g cat
1st 2 0 1 0
2nd 5 3 0 4
It might be worthwhile to dig into the Pandas docs and look at its DataFrame - it might make life easier.
I second the answer using the Pandas dataframes. However, my code should be a bit simpler than yours.
In [1]: import pandas as pd
In [5]: data = [{'a': 2, 'g': 1},{'p': 3, 'a': 5, 'cat': 4}]
In [6]: df = pd.DataFrame(data)
In [7]: df
Out[7]:
a cat g p
0 2 NaN 1 NaN
1 5 4 NaN 3
In [9]: df = df.fillna(0)
In [10]: df
Out[10]:
a cat g p
0 2 0 1 0
1 5 4 0 3
I did my coding in iPython, which I highly recommend!
To save to csv, just use an additional line of code:
df.to_csv('filename.csv')
I am a freshie in python, just suggestions that may be helpful hopefully:)
key_map = []
for row in data:
key_map.extend(row.keys())
key_map = list(set(key_map))
you can change the middle part to this, which will save you some time to find the key_map
In your case union will at least scan through each row to find the different item.