I have the following piece of code where I take in an integer n from stdin, convert it to binary, reverse the binary string, then convert back to integer and output it.
import sys
def reversebinary():
n = str(raw_input())
bin_n = bin(n)[2:]
revbin = "".join(list(reversed(bin_n)))
return int(str(revbin),2)
reversebinary()
However, I'm getting this error:
Traceback (most recent call last):
File "reversebinary.py", line 18, in <module>
reversebinary()
File "reversebinary.py", line 14, in reversebinary
bin_n = bin(n)[2:]
TypeError: 'str' object cannot be interpreted as an index
I'm unsure what the problem is.
You are passing a string to the bin() function:
>>> bin('10')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an index
Give it a integer instead:
>>> bin(10)
'0b1010'
by turning the raw_input() result to int():
n = int(raw_input())
Tip: you can easily reverse a string by giving it a negative slice stride:
>>> 'forward'[::-1]
'drawrof'
so you can simplify your function to:
def reversebinary():
n = int(raw_input())
bin_n = bin(n)[2:]
revbin = bin_n[::-1]
return int(revbin, 2)
or even:
def reversebinary():
n = int(raw_input())
return int(bin(n)[:1:-1], 2)
You want to convert the input to an integer not a string - it's already a string. So this line:
n = str(raw_input())
should be something like this:
n = int(raw_input())
It is raw input, i.e. a string but you need an int:
bin_n = bin(int(n))
bin takes integer as parameter and you are putting string there, you must convert to integer:
import sys
def reversebinary():
n = int(raw_input())
bin_n = bin(n)[2:]
revbin = "".join(list(reversed(bin_n)))
return int(str(revbin),2)
reversebinary()
Related
I was trying to pass input into an array but it throws an error.
I already defined the value type in the array. I assigned the array with 'i' and also passed the int type value.
>>> import array as arr
>>> a = arr.array('i', [int(input())])
print(a)
Here's the error that I'm getting:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
a = arr.array('i', [int(input())])
ValueError: invalid literal for int() with base 10: 'print(a)'
You're typing this into a REPL environment, so each time you type a line, it runs (more or less), so when you enter the line:
a = arr.array('i', [int(input())])
The line after that is expecting the input for input, not the next line of code. Because you then type print(a) you're passing the value "print(a)" to int, essentially:
a = arr.array('i', [int("print(a)")])
Obviously "print(a)" is not a base 10 number so int is failing because "p" is not a character in base 10 (the digits 0 to 9 are the only valid digits).
To resolve this you need to pass a value for the input before continuing with your code:
>>> import array as arr
>>> a = arr.array('i', [int(input())])
5
>>> print(a)
array('i', [5])
I'm new to run-length coding and need help. I've been given a run-length string of a series of integer followed by characters that include letters/characters.
For example, I have a string:
1-4c8k2)
And I need to convert it into:
-cccckkkkkkkk))
What I've done is convert the run-length string into a list of tuples:
[('1','-'),('4','c'),('8','k'),('2','c')]
And tried creating a function which would convert it into a string however I get a TypeError: can't multiply sequence by non-int of type 'str'.
def decode(lst):
q = ''
for count, character in lst:
q += count * character
return q
I'm trying to think of a way to improve space complexity instead of creating a new list of tuples and more so, trying to resolve this TypeError.
I suspect that what has happened is you forgot to convert the counts into ints:
>>> 3 * 'a'
'aaa'
>>> '3' * 'a'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
>>> int('3') * 'a'
'aaa'
You try through this way :
lst = [('1','-'),('4','c'),('8','k'),('2','c')]
def decode(lst):
q = ''
for count, character in lst:
q += int(count) * character
return q
print(decode(lst))
Output :
-cccckkkkkkkkcc
Check this code here
Is there a concise way of formatting a number, that on occasion can also be a string?
The number would normally be a float, but occasionally it's also denoted as the string "n/a".
I would like to format the float with a fixed number of decimals, but print the entire string in case it is not a number.
For instance:
var=3.145623
print("This is {0:.2f}".format(var))
>>>This is 3.14
,but
var = "n/a"
print("This is {0:.2f}".format(var))
>>> File "<stdin>", line 1, in <module>
>>> ValueError: Unknown format code 'f' for object of type 'str'
I am not surprised by the ValueError, but wonder if there is a concise way around it, ideally without an explicit if-statement.
Indeed, the f format specifier only works on actual float values. You can't avoid having to special-case your n/a value.
You can format the float separately, and conditionally, then interpolate the result into the larger template:
var_formatted = format(var, '.2f') if var != 'n/a' else var
print("This is {0:4}".format(var_formatted))
If you are really averse to if, you can use exception handling too:
try:
var_formatted = format(var, '.2f')
except ValueError:
var_formatted = 'n/a'
print("This is {0:4}".format(var_formatted))
Another option would be for you to wrap the value in a class with a __format__ method:
class OptionalFloat(object):
def __init__(self, value):
self.value = value
def __format__(self, fmt):
try:
return self.value.__format__(fmt)
except ValueError:
return self.value
print("This is {0:.2f}".format(OptionalFloat(var)))
This moves the requirement to detect the type into another class method, keeping your output code a little cleaner and free of all those pesky conditionals or exception handlers:
>>> var = 3.145623
>>> print("This is {0:.2f}".format(OptionalFloat(var)))
This is 3.15
>>> var = 'n/a'
>>> print("This is {0:.2f}".format(OptionalFloat(var)))
This is n/a
Python supports not-a-number as float('nan') and it may be more useful than the string "n/a" in your code. It works with formatting and produces more sane results than a string if you use it in computations.
NaN:
>>> n = float('nan')
>>> n
nan
>>> "{0:.2f}".format(n)
'nan'
>>> n == 3
False
>>> n * 2
nan
>>> n < 5
False
String:
>>> n = 'n/a'
>>> "{0:.2f}".format(n)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'f' for object of type 'str'
>>> n == 3
False
>>> n * 2
'n/an/a'
>>> n < 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() < int()
maybe something like this
str = "{0:.2f}".format(var) if isinstance(var, float) else var
print(str)
I have a problem that I am working on. The goal of the problem is to take the string placeholder i. If i is an even placeholder, replace the letter at i with the letter at i -1. If the i place holder is odd, then replace the letter i with the letter at i +1.
Here is my code so far:
def easyCrypto (s):
for i in range (0,len(s)-1):
if i % 2 == 0:
str(s).replace(i,((i-1)))
if i % 2 != 0:
str(s).replace(i,((i+2)))
print (s)
My error:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
easyCrypto('abc')
File "C:/Python/cjakobhomework7.py", line 4, in easyCrypto
str(s).replace(i,((i-1)))
TypeError: Can't convert 'int' object to str implicitly
update!!
New code based on answers:
def easyCrypto (s):
for i in range (0,len(s)-1):
if i % 2 == 0:
s = str(s).replace(s(i),(s(i-1)))
else:
s = s.replace(s(i), s(i + 1))
print (s)
However I still have the following errors:
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
easyCrypto('abc')
File "C:/Python/cjakobhomework7.py", line 4, in easyCrypto
s = str(s).replace(s(i),(s(i-1)))
TypeError: 'str' object is not callable
Any ideas? thank you
Use s[i] instead of s(i), and likewise for the other indexes.
There are two things here:
str.replace does not automatically stringify its arguments. You need to manually convert them into strings. Remember that: "Explicit is better than implicit."
str.replace does not work in-place because strings are immutable in Python. You need to reassign s to the new string object returned by str.replace.
Your code should be:
s = s.replace(str(i), str(i-1))
Also, you can replace if i % 2 != 0: with else: since the condition of the second if-statement can only be true if the first is false:
if i % 2 == 0:
s = s.replace(str(i), str(i-1))
else:
s = s.replace(str(i), str(i+1))
Regarding your edited question, you are trying to call the string s as a function by placing parenthesis after it. You need to use square brackets to index the string:
>>> 'abcde'[0]
'a'
>>> 'abcde'[3]
'd'
>>>
In your case it would be:
s = s.replace(s[i], s[i-1])
As a general rule of thumb, parenthesis (...) are for calling functions while square brackets [...] are for indexing sequences/containers.
I'm trying to store a time value in an array, but it gives me an error every time, even when I try to cast the float into an int. Here is the portion of my code:
EndTimes = [0,0,0,0]
...
EndTimes[TakenSlots] = int(time.time() + n)
But it just gives this error:
[error] TypeError ( list indices must be integers )
[error] --- Traceback --- error source first
line: module ( function ) statement
44: main ( craftTime ) EndTimes[TakenSlots] = tempInt
I tried this code just to see what it thought the value was:
tempInt = int(time.time() + n)
print tempInt
EndTimes[TakenSlots] = tempInt
And it just outputted 1412046180 (no decimal places, which seems like it should be an int)
Does anyone know what's happening? Is it a problem with the int() or the type of array I'm using? Thanks in advance!
This occurs because the list index ( list[index] = value ) must be an integer. It is probable that TakenSlots is not an int.
>>> l = [1,2,3]
>>> l[1.3] = 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not float