I am trying to get space separated inputs. while the first method works completely fine, the second method throws an error saying:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
what is wrong with the second method?
Method 1:
x = [int(j) for j in input().split()]
Method 2:
x = [j for j in int(input().split())]
Because you are using split() to a string which will return a list, then you are passing this list to int() that's why you are getting error. for changing datatype of list you need to use map() as below or first approach of your's.
Try Below code
x = [j for j in map(int,input().split())]
Related
I have this code:
def function_factory(x,y,o):
d = {'+':x+y,'-':x-y,'*':x*y,'/':x/y,'%':x%y}
for k,v in d.items():
if o == k:
return v
So if I input print(function_factory(3,4,'*')) then what I would expect to get is 12 but instead I get this error:
Traceback (most recent call last):
File "main.py", line 4, in <module>
Test.assert_equals(function_factory(2,3,'+')(), 5)
TypeError: 'int' object is not callable
I tried a different way of doing it but I still get this error. Thank you very much in advance.
first you should not call your function result and insted assert the it: function_factory(2,3,'+') and not function_factory(2,3,'+')() just as #Sayse said in comments
second, your function will tell you what is the operation to get the result.. not the result of a operation:
if this is your intention, you should use it like this:
function_factory(2,5,10)
>>> '*'
function_factory(2,5,7)
>>> '+'
function_factory(2,5,-3)
>>> '-'
function_factory(2,5,2/5)
>>> '/'
in case you want to make it work as you expect,and not as i showed you how it is already working, you should change your function:
def function_factory(x,y,o):
d = {'+':x+y,'-':x-y,'*':x*y,'/':x/y,'%':x%y}
return d[o]
and then the result would be :
function_factory(3,4,'*')
>>> 12
Can anyone help me fix this error I keep getting please. I have tried to look for a solution but I can't find any. Below is the error message and also part of my coding
Please enter your class Y or X or Z: Y
Traceback (most recent call last):
File "/Volumes/LIAM'S USB/DEV6 FINAL.py", line 118, in <module>
score=int(items[1])
IndexError: list index out of range
results={
start=True
while (start):
pupil_class=input("\nPlease enter your class Y or X or Z: ")
if pupil_class == ("Y"):
classfile="Class_Y_results.txt"
elif pupil_class == ("X"):
classfile="Class_X_results.txt"
elif pupil_class == ("Z"):
classfile="Class_Z_results.txt"
f=open(classfile,'r')
for line in f:
items=line.split(',')
name=items[0]
score=int(items[1])
if name in results:
results[name].append(score)
else:
results[name]=[]
results[name].append(score)
f.close()
A certain line in your Class_Y_Results.txt only has one entry (not separated by commas), hence the list returned by items=line.split(',') only has a length of 1 (or maybe 0), causing score=int(items[1]) to throw an IndexError.
Sample:
>>> a = "foo,bar"
>>> b = "foo"
>>> len(a.split(','))
2
>>> len(b.split(','))
1
>>> a.split(',')[1]
'bar'
>>> b.split(',')[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
There is probably an empty like in one of your files. This will not contain a comma, so you will not have an item[1], and this produces the error message you see.
Check how many fields you get back from the split to solve this.
I have written this code:
def reclen(n):
for i in range(1,n):
if (10**i)%n==1:
return(i)
for j in range(1,20):
if reclen(j)==6:
print(j)
And it will run, outputting the integers between 1-20 satisfying 1/n=has 6 recurring digits. If i change the clause in the second loop to:
for j in range(1,20):
if reclen(j)>6:
print(j)
I would expect to get the integers between 1-2 satisfying 1/n=has 6 or more recurring digits, but instead, i get an error, telling me there's a type error. I have tried plastering int() functions in all the outputs, but it seems I'm not allowed to compare the output as anything but exact equal to a value.
In the case where n is 1 in reclen, there will be nothing for your for loop to iterate over so it returns None. e.g.:
>>> def reclen(n):
... for i in range(1,n):
... if (10**i)%n==1:
... return(i)
...
>>> print(reclen(1))
None
None is neither greater than or less than any integer (on python3.x where comparisons of different types are disallowed by default) which is why you get an error.
>>> None > 6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: NoneType() > int()
I need to sample k numbers in [-n,-1] union [1,n] without replacement. Why doesn't this code work?
random.sample(range(-n,n+1).remove(0),k)
I get
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python2.7/random.py", line 319, in sample
n = len(population)
TypeError: object of type 'NoneType' has no len()
remove is an inplace operation. It modifies the list, and returns none. That's why you are seeing the error. You should create the list separately and pass it to sample:
>>> l = range(-n, n+1)
>>> l.remove(0)
>>> random.sample(l, k)
If you want to do it in one statement, you could create the two parts of the range separately and add them.
>>> random.sample(range(-n, 0) + range(1, n+1), k)
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.