math.pow (base/exponent) requires comma separated values...working fine for pre-assigned values, but having trouble with user-submitted values (experimenting in command line). Help appreciated as I want to develop this kind of thing eventually making a basic math test.
exp = int(raw_input())
while exp:
print math.pow(int(raw_input))
The errors I'm getting are
ValueError: invalid literal for int() with base 10: '2,3' (which seems weird as this is an exponent, not log function...)
When I try:
exp = (raw_input())
while exp:
print math.pow(exp)
I get error:
pow expected 2 arguments, got 1
Even though I'm submitting 2,3 for example (with comma).
I also tried concatenating the input with .split, but got error regarding pow requiring integers, not "list."
When you enter an input with a comma, you get a tuple. You can either use
eval(raw_input())
Or just
input()
To get this from a string to a usable format. Once you have a tuple, you can use * notation to "unpack" the tuple. So instead of calling math.pow((2, 3)), where the one argument is the tuple (2, 3), you will be calling math.pow(2, 3).
>>> exp = input()
2, 3
>>> math.pow(*exp)
8.0
"2,3" is a string, passing this to a function won't make it act like two different parameters separated by ,(as you expected).
>>> def func(arg):
... print arg
...
>>> func('a, b')
a, b # arg is a variable that stores the passed string
You should convert that string into two numbers first by splitting it at comma first and then applying int() to each if it's item.
>>> import math
>>> math.pow(*map(int, '2,3'.split(',')))
8.0
First split the string at ',' using str.split:
>>> '2,3'.split(',')
['2', '3'] #str.split returns a list
Now as we need integers so apply int() to each value:
>>> map(int, '2,3'.split(',')) #apply int() to each item of the list ['2', '3']
[2, 3]
Now as pow expects two arguments so you can use * notation to unpack this list and pass
the items to math.pow.
>>> math.pow(*[2 , 3])
8.0
A even simpler way would be to use sequence unpacking:
>>> a, b = [2, 3]
>>> math.pow(a, b)
8.0
There's another tool in python library that can convert comma separated items in a string into a tuple:
>>> from ast import literal_eval
>>> literal_eval('1, 2')
(1, 2)
>>> a,b = literal_eval('1, 2')
>>> a
1
>>> b
2
Related
I have just started to learn python and following the docs on tuples, I came across this snippet,
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
Following this I ran following snippet,
>>> foo=1,2,3,
>>> len(foo)
3
>>> foo
(1, 2, 3)
Why does singleton prints with an trailing comma , where as foo seems to trim it ?
Beacause ("Hello") is not a tuple, it is same as "Hello".
>>> ("Hello")
'Hello'
in order to distinguish tuple with single element from a simple expression in () a , is necessary. Whereas (1,2,3) is clearly a collection of items, and as they are enclosed by () it can easily be inferred as a tuple, hence no need for a trailing ,.
because you define variable"singleton" as ("hello",), you don't need comma to end it, and for "foo", you define it, so it shows as what you defined
This question already has answers here:
Joining multiple strings if they are not empty in Python
(3 answers)
Closed 5 years ago.
Given:
a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'
list = (a, b, c, d, e)
How can I get a string using all the non empty elements of the list ?
Desired output:
'aaa,ccc,eee'
Using a generator expression:
",".join(string for string in lst if len(string) > 0)
The ",".join() part is using the join() method of strings, which takes an iterable argument and outputs a new string that concatenates the items using "," as delimiter.
The generator expression between parenthesis is being used to filter empty strings out of the list.
The original list doesn't change.
The shortest thing you can do is
','.join(filter(None, mytuple))
(I renamed list to mytuple in oder to not shadow the builtin list.)
You can use a generator-expression:
','.join(s for s in list if s)
which outputs:
'aaa,ccc,eee'
Why?
This takes advantage of the fact that an empty string evaluates to False.
This can be seen clearer through some examples:
>>> if "a":
... print("yes")
...
yes
>>> if " ":
... print("yes")
...
yes
>>> if "":
... print("yes")
...
>>>
So the generator says: for each string in list, keep 'if string' - i.e. if the string is not empty.
We then finally use the str.join method that will take each string in the iterator that is passed into it (here a generator) and concatenate them together with whatever the str is. So here we use a ',' as the string to get the desired result.
A little example of this:
>>> ','.join(['abc', 'def', 'ghi'])
'abc,def,ghi'
**As a side note, you shouldn't name your variable list as it overrides the built-in list() function:
>>> list((1, 2, 3))
[1, 2, 3]
>>> list = 1
>>> list((1, 2, 3))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
You can try this one too:
a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'
tup = (a, b, c, d, e)
res = ",".join(filter(lambda i: not i=='', tup))
print(res)
The output will be:
aaa,ccc,eee
It is also a good practice not to use list as a variable name, as it is a reserved keyword from Python.
So I'm supposed to create a function that takes any sort of iterable input and converts it into a string of that input separated by spaces. For example, if you were to call iteration_to_string("abcd") it would return "a b c d " (the space at the end is allowed). or if [1, 2, 3, 4] is the input, it should return "1 2 3 4 ". All I have so far is how to turn the input into a set and Im confused where to go to turn it into a string. I assume it would be adding something into the for loop that would somehow concatenate the inputs together with a space but Im not sure how to do that. Any help is appreciated!
def iteration_to_string (data):
new = set()
for i in range (len(data)):
new.add(data[i])
return " ".join(new)
your code might not work for list containing element int like [1,2,3,4] because join takes string
so you can convert them to int before join like this:
>>> def my_join(x):
... return " ".join(map(str, x))
...
>>> my_join([1, 2, 3, 4])
'1 2 3 4'
you can use list comprehension, if you dont want to use map
>>> def my_join(x):
... return " ".join(str(element) for element in x))
>>> my_join(['a', 'b' ,'c', 'd'])
'a b c d'
for any iterable
' '.join(iterable)
will return a string with all the elements in iterable separated by a space. refer to str.join(iterable).
if the elements in iterable are not strings you need to
' '.join(str(item) for item in iterable)
(you can do this with any other string as well; ''.join(iterable) if you do not want any spaces in between).
Below code works. However I cannot re-create it/not understand it. Could someone pls help to write all lines to complete the code.
value = #something
var1, var2 = unpack("b8s",value)
That means, here one value is being put into two variables. Can someone give an example, how its possible?
Many thanks in advance.
You're over complicating it by having a loop at all.
var1, var2 = tuple
This is just a syntax thing you can do in python. Note that you must unpack the entire tuple; the number of variables on the left-hand side must be equal to the number of values in the tuple.
Example
myTuple = ("hi","i","am","tuple")
first,second,third,fourth = myTuple
print first
>>hi
print second
>>i
print third
>>am
print fourth
>>tuple
Not allowed
myTuple = ("hi","i","am","tuple")
first,second = myTuple
>>Exception
The unpack method is coming from the struct module, which is lets you treat a Python string like packed binary data. The unpack('b8s', value) call is telling unpack to treat value like a binary string containing one unsigned char (using 'b'), which will be unpacked as the integer value of the char, followed by a char[8] (using '8s'), meaning a char string of length 8. That gets unpacked as a Python string. So a full example would look like this:
>>> from struct import unpack
>>> s = "abcdefgty"
>>> int_char, my_str = unpack("b8s", s)
>>> print int_char
97 # 97 is the ascii code of 'a'
>>> print my_str
bcdefgty
If you have a tuple as
t = (1, 2, "a")
you can unpack it like this:
a, b, c = t
print "a=", a
which prints
a= 1
What is happening is: unpack process the contents of elem and returning a tuple with 2 items. Each item is assigned to a different variable.
it's the same:
unpacked_value = unpack("b8s",elem)
var1 = unpacked_value[0]
var2 = unpacked_value[1]
Using diffentd values and variables:
my_tuple = (1, 2)
var1, var2 = my_tuple
print var1 #outputs 1
print var2 #outputs 2
If you have the following code, how exactly is it following the documentation: map(function, iterable,...)?
x = sorted(map(int, dat[0].split()))
Is int a function and if so, why isn't it expressed as such?
int is a constructor so it's callable so you can use it with map
In your case dat[0] is as string, and split() generates a list of strings, by splitting the input string at whitespaces.
Eg
"1 11".split()
returns
["1", "11"]
The map function has two input arguments:
The first argument is something which can be called (in Python you say it is a callable), eg a function. int is not realy a function but such a thing (Python slang: it is an object).
Eg int("3") return 3. So int when applied to a string tries to convert this string to an integer, and gives the integer value back.
The second argument is something you can iterate over, in your case it is a list.
If you then call the map function, the first argument is applied to all elements from the second argument.
So
map(int, ["1", "11"])
returns
[1, 11]
If you combine what I explained you understand that
map(int, "1 11".split())
returns
[1, 11]
When you ask "why isn't it expressed as such" I suppose you mean, why doesn't it have brackets like a function? The answer is that if you put the brackets in then you get what the function does instead of the function itself. Compare what happens when you enter int() versus int.
Think of it like this
def map( function, iterable ):
return ( function(x) for x in iterable )
In x = sorted(map(int, dat[0].split())) the function, int, is being named, not evaluated. This code provides a function object to the map function. The map function will evaluate the given function.
The syntax of map in the simplest form is:
map(func, sequence)
It will apply the function "func" on each element of the sequence and return the sequence. Just in case you don't know, int() is a function.
>>> int(2.34)
2
>>> int("2")
2
>>> a = ["1", "101", "111"]
>>> map(int, a)
[1, 101, 111]
Now, I will give you my implementation of map().
>>> for index in range(len(a)):
... a[index] = int(a[index])
...
>>> a
[1, 101, 111]
If you have understood the concept, let's take a step further. We converted the strings to int using base 10 (which is the default base of int() ). What if you want to convert it using base 2?
>>> a = ["1", "101", "111"]
>>> for index in range(len(a)):
... a[index] = int(a[index], 2) # We have an additional parameter to int()
...
>>> a
[1, 5, 7]
To get the same result using map(), we will use a lambda function
>>> a = ["1", "101", "111"]
>>> map(lambda x: int(x, 2), a)
[1, 5, 7]