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)
Related
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())]
i am getting error in the below python code
a=[1,2,3,4,5,6,7,8,9]
c,d=divmod(len(a),2)
i=iter(a).next
print ''.join('%s\t%s\n' % (i(),i())
for i in xrange(c))\
+ ('%s\t\n' % (i()) if b==1
else '')
i need to print output is
1 2
3 4
5
i am getting error:
Traceback (most recent call last):
File "dhsgj.py", line 5, in <module>
for i in xrange(c))\
File "dhsgj.py", line 5, in <genexpr>
for i in xrange(c))\
TypeError: 'int' object is not callable
You do not need to split the array, try to iterate two items at a time.
I've updated your code to make it little bit easier to follow. This should work:
a=[1,2,3,4,5,6,7,8,9]
iterator = iter(a)
for first in iterator:
try:
second = next(iterator)
except StopIteration:
print first
else:
print('%s\t%s\n' % (first, second))
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 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.
Here is my code so far:
def code_block(text, key):
itext = int(text)
rkey = int(key)
res= itext + rkey
def last():
return res[-1:]
if res>=11111111:
last()
return res
Here is the task I've been set:
Now we need a function to take a block of code and a key as input, where both are assumed to be 8 digits long, and encrypts each digit of the number with the corresponding digit of the key:
>>> code_block('12341234','12121212')
'24462446'
>>> code_block('66554433','44556677')
'00000000'
Where am I going wrong? Could you point me in the right direction and indicate me how I was wrong?
You are going about this the wrong way. Treat this character by character:
def code_block(text, key):
res = [str(int(c) + int(k))[-1:] for c, k in zip(text, key)]
return ''.join(res)
which gives me:
>>> code_block('12341234','12121212')
'24462446'
>>> code_block('66554433','44556677')
'00000000'
The code sums each and every character separately, turning it back into a string and only using the last character of the result; 9 + 9 is 18, but the result would be '8'.
Your code would sum the whole numbers, but that would result in:
>>> 66554433 + 44556677
111111110
which is not the correct result. Neither did you ever turn your sum back into a string again, so your code, attempting to treat the sum result as a string by slicing it, gave an exception:
>>> code_block('12341234', '12121212')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in code_block
File "<stdin>", line 6, in last
TypeError: 'int' object has no attribute '__getitem__'