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]
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
Split space separated Numerical String into a List containing Numbers.
I want this:-
A = '5 2 12 4 29'
to be this in single line of code
B = [5,2,12,4,29]
You can also use the lambda function as following:
A = '5 2 12 4 29'
B = list(map(lambda x: int(x), a.split()))
print(B)
where split() returns a list of strings
and then map function iterates over each string where lambda function converts each string to Integer.
Try this
.split() method returns a list of splitted strings. So you can iterate over it and convert it to a integer
A = '5 2 12 4 29'
B = [int(l) for l in A.split()]
['5', '2', '12', '4', '29']
.split() method will return something like this. But you want them in integers. So you can follow the above method
You can use in python3 this style:
A = '5 2 12 4 29'
B = A.split(" ")
In this case, the split method, with the quotes is used to separate with spaces, as the A has number with spaces, then the quotes to separate would be split(" ")
print(B)
# ['5', '2', '12', '4', '29']
Here is a one-liner using a list comprehension:
A = '5 2 12 4 29'
B = [int(x) for x in A.split()]
print(B) # [5, 2, 12, 4, 29]
You can use split( ) to convert the string to a list of individual characters. ['5', '2', '12', '4', '29']
Since you want integers and not characters, you can use map() to convert those individual characters to integers.
A = '5 2 12 4 29'
B = list(map(int,A.split()))
print(B)
[5, 2, 12, 4, 29]
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'}
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)
Edit: Turns out the answer is an emphatic "no". However, I'm still struggling to populate the lists with the right amount of entries.
I've been searching StackOverflow all over for this, and I keep seeing that dynamically setting variable names is not a good solution. However, I can't think of another way to to this.
I have a DataFrame created from pandas (read in from excel) that has columns with string headers and integer entries, and one column that has the numbers (let's call it Week) 1 through 52 increasing sequentially. What I want to do is create separate lists each named for the column headers and the entry is the week number appearing the number of times of the listed integer.
This is simple for a few columns, just manually create lists names, but as the number of columns grows, this could get a little out of hand.
Atrocious explanation, it was the best I could come up with. Hopefully a simplified example will clarify.
week str1 str2 str3
1 8 2 5
2 1 0 3
3 2 1 1
Desired output:
str1_count = [1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3] # eight 1's, one 2, and two 3's
str2_count = [1, 1, 3] # two 1's, one 3
str3_count = [1, 1, 1, 1, 1, 2, 2, 2, 3] # five 1's, three 2's, one 3
What I have so far:
results = {}
df = pd.DataFrame(from_csv(...., sep = ","))
for key in df:
for i in df[key]
results[key] = i # this only creates a list with the int value of the most recent i
So, like this?
import collections
import csv
import io
reader = csv.DictReader(io.StringIO('''
week,str1,str2,str3
1,8,2,5
2,1,0,3
3,2,1,1
'''.strip()))
data = collections.defaultdict(list)
for row in reader:
for key in ('str1', 'str2', 'str3'):
data[key].extend([row['week']]*int(row[key]))
from pprint import pprint
pprint(dict(data))
# Output:
{'str1': ['1', '1', '1', '1', '1', '1', '1', '1', '2', '3', '3'],
'str2': ['1', '1', '3'],
'str3': ['1', '1', '1', '1', '1', '2', '2', '2', '3']}
Note: Pandas is good for crunching data and doing some interesting operations on it, but if you just need something simple you don't need it. This is one of those cases.