Error in python code - python

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))

Related

How can I throw TypeError with message inside if statement in Python?

What I want to do
I would like to fix my current code to pass the coding challenge, Codewars Prefill an Array.
I hope to learn how to throw TypeError with message with if statement in this case.
Create the function prefill that returns an array of n elements thatall have the same value v. See if you can do this without using a loop.
You have to validate input: v can be anything (primitive orotherwise) if v is ommited, fill the array with undefined if n is 0, return an empty array if n is anything other than an integer or integer-formatted string (e.g. '123') that is >=0, throw a TypeError
When throwing a TypeError, the message should be n is invalid, where
you replace n for the actual value passed to the function.
Code Examples
prefill(3,1) --> [1,1,1]
prefill(2,"abc") --> ['abc','abc']
prefill("1", 1) --> [1]
prefill(3, prefill(2,'2d'))
--> [['2d','2d'],['2d','2d'],['2d','2d']]
prefill("xyz", 1)
--> throws TypeError with message "xyz is invalid"
Problem
I have passed 4 sample tests among 5 sample tests, but I cannot pass the below one.
prefill("xyz", 1)
--> throws TypeError with message "xyz is invalid"
Error Message
Traceback (most recent call last): File "main.py", line 8,
in <module> prefill('xyz', 1) File "/home/codewarrior/solution.py",
line 3, in prefill if int(n): ValueError: invalid literal for int() with base 10: 'xyz'
Current code
def prefill(n,v):
if int(n):
result = [0] * int(n)
for i in range(len(result)):
result[i] = v
return result
else:
return TypeError, str(n) + "is invalid"
Developing Environment
Python 3.4.3
You can use a try-except to catch the error, and throw for example another one:
def prefill(n,v):
try:
n = int(n)
except ValueError:
raise TypeError("{0} is invalid".format(n))
else:
return [v] * n
For example:
>>> prefill(3,1)
[1, 1, 1]
>>> prefill(2,"abc")
['abc', 'abc']
>>> prefill("1", 1)
[1]
>>> prefill(3, prefill(2,'2d'))
[['2d', '2d'], ['2d', '2d'], ['2d', '2d']]
>>> prefill("xyz", 1)
Traceback (most recent call last):
File "<stdin>", line 1, in prefill
ValueError: invalid literal for int() with base 10: 'xyz'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in prefill
TypeError: xyz is invalid
You do not per se need to specify an exception to raise. In case you want to re-raise the exception, simply writing raise is sufficient. You can furthermore specify a tuple of exceptions to catch, and make v optional here, for example:
def prefill(n,v=None):
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("{0} is invalid".format(n))
else:
return [v] * n
Use the raise keyword to raise an exception, rather than return it. raise is used to generate a new exception:
>>> raise TypeError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError
In this example I raised the TypeError by using the exception class directly. You can also create instances of the error like this:
>>> t=TypeError()
>>> raise t
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError
Doing it that way allows various properties to be set on the object before using raise. The problem posted includes this requirement:
When throwing a TypeError, the message should be n is invalid, where you replace n for the actual value passed to the function.
That is an example of a situation where it is necessary to create an instance of the error and set a message property on it before using raise. That can still be done in one line:
>>> raise TypeError("foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo
To catch exceptions, use a try-except block, rather than an if block:
x = 'hello, world!'
try:
y = x / 2
except TypeError as e:
e.args = (*e.args, str(x) + " is not valid")
raise
This will raise an error:
TypeError: ("unsupported operand type(s) for /: 'str' and 'int'", 'hello, world! is not valid')
note that you can check the datatype of a variable using type():
>>> x = 5
>>> type(x)
<class 'int'>
>>> if type(x) == int:
... print("it's an int")
...
it's an int
Also, the code sample could be simplified to:
return [v for _ in range(n)]

TypeError: list indices must be integers, not float (Python2)

import math
a=[100,4,5,10,3,1]
def swap(a,b):
temp=a
a=b
b=temp
for i in range(len(a),int(len(a)/2),-1):
l=i
print l
print int(math.ceil(int((l)/2.0)))
print a[int(math.ceil(int((l)/2.0)))]
print math.ceil(a[int((l)/2.0)])
print a[l-1]
while(l>1 and a[l-1] < a[int(math.ceil(int((l)/2.0)))]):
swap(a[l-1],a[int(math.ceil(int((l)/2.0)))])
print l
l= math.ceil(int((l))/2.0)
print a
Output:
6
3
10
10.0
1
6
Traceback (most recent call last):
File "heap.py", line 15, in <module>
while(l>1 and a[l-1] < a[int(math.ceil(int((l)/2.0)))]):
TypeError: list indices must be integers, not float
I have checked many questions on stackoverflow with same query, I
tried using the // as well but the error is persistent. I am using the
int value as I printed and tested. Can anyone redirect me to a
question with similar issue( if this duplicate) or help me with this
error?

list index out of range in my coding

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.

Python sample without 0

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)

TypeError: argument of type 'int' is not iterable

#!/usr/bin/python
import time
from array import *
THINKING = 0
HUNGRY = 1
EATING = 2
class Philosopher:
def __init__(self):
self.ph = array('i',[1, 2, 3, 4, 5])
self.sleeptime = array('i',[30, 30, 30, 30, 30])
def initialization_code(self):
for i in range(self.ph.__len__()):
self.ph[i] = THINKING
def pickup(self,i):
self.ph[i] = HUNGRY
self.test(i)
if(EATING not in (self.ph[i])):
while(EATING not in (self.ph[i])):
time.sleep(self.sleeptime[i])
def putdown(self,i):
self.ph[i] = THINKING
self.test((i+4)%5)
self.test((i+1)%5)
def test(self,i):
if((2 not in (self.ph[(i+4)%5]))and(2 not in (self.ph[(i+1)%5]))and(self.ph[i]==HUNGRY)):
self.ph[i] = EATING
def start_process(self):
for i in range(self.ph.__len__()):
self.pickup(i)
self.putdown(i)
def display_status(self):
for i in range(self.ph.__len__()):
if (self.ph[i] == 0):
print "%d is THINKING" % i+1
elif (self.ph[i] == 1):
print "%d is WAITING" % i+1
elif (self.ph[i] == 2):
print "%d is EATING" % i+1
phil = Philosopher()
phil.initialization_code()
phil.start_process()
phil.display_status()
The above is my piece of code in which i'm trying to implement dining philosopher problem in python.
when i run this code it shows me this error:
Traceback (most recent call last):
File "dining.py", line 59, in <module>
phil.start_process()
File "dining.py", line 43, in start_process
self.pickup(i)
File "dining.py", line 27, in pickup
self.test(i)
File "dining.py", line 38, in test
if((2 not in (self.ph[(i+4)%5]))and(2 not in (self.ph[(i+1)%5]))and(self.ph[i]==HUNGRY)):
TypeError: argument of type 'int' is not iterable
Can anyone please help me at this, why is it showing this error. I searched about it but couldn't resolve.
Thanks in advance!!
Your equations result in integers. You can't use in on integers.
>>> 'foo' in 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'int' is not iterable
Besides the problem with in, which only can applied to iterables and to objects having __contains__ in its class definition, you probably are going to run into the next problem: You don't have parallelization. So you either should use threads or replace the
if(EATING not in (self.ph[i])):
while(EATING not in (self.ph[i])):
time.sleep(self.sleeptime[i])
lines - which are an endless loop, because no one sets the EATING status.
Or you should do the timing by other means, by constantly checking wall clock time or by creating an event scheduling system which takes care of the actions which have to be done.
BTW: The print "%d is THINKING" % i+1 are broken as well, because there are no () around the i+1 and % has higher precedence.
I think you are generally using:
in / not in
incorrectly. It looks like you are trying to compare integers which should be done with
==
!=
>
>=
<
<=
operators instead.

Categories