I am getting the error "TypeError: range() integer end argument expected, got list." Not sure what to do about it. Thanks for the help!
if iput == 1:
numresistors = [input("Number of resistors?")]
if numresistors == [2]:
r1 = raw_input("Enter first resistor:")
r2 = raw_input("Enter second resistor:")
R1 = Parsing(r1)
R2 = Parsing(r2)
req = R1.valueParsing() + R2.valueParsing()
req2 = fmtnum(req)
print "The value of the series resistors is %s." % req2
else:
sumr = 0
for x in range (numresistors):
sumr = sumr + x
print "The value of the series resistors is %s." % sumr
numresistors is being stored as a list containing a single value
numresistors = [input("Number of resistors?")]
The error you are getting is saying that the range function doesn't know what to do with a list. You could either call range with the only item in the list (range(numresistors[0])) or not store it as a list in the first place.
numresistors = input("Number of resistors?")
Related
the result looks like this:
[([[17, 11], [57, 11], [57, 61], [17, 61]], '2', 1.0)]
I just want the 2 printed (second element of the list?) but keep getting "list index out of range" error.
Here is the code I am trying to use to print the list element:
print (result[1][0])
full code snippit:
number = 1
sresult = ''
reader = easyocr.Reader(['en'])
for number in range (1,82):
result = reader.readtext(datadrop+ str(number)+'.png')
print (result[1][0])
sresult = str(result) +sresult
print (sresult)
The list has only one tuple in it ([(...)]) so accessing result[1][0] will give an IndexError. You can solve by changing your code to this -
number = 1
sresult = ''
reader = easyocr.Reader(['en'])
for number in range (1,82):
result = reader.readtext(datadrop+ str(number)+'.png')
print (result[0][1][0])
sresult = str(result) +sresult
print (sresult)
I assume you want to access the second item in the tuple.
this worked:
number = 1
sresult = ''
reader = easyocr.Reader(['en'])
for number in range (1,82):
result = reader.readtext(datadrop+ str(number)+'.png')
if len(result) != 0:
print (result[0][1][0])
sresult = str(result) +sresult
print (sresult)
I had to add a way to handle empty results and used the [0][1][0] solution from sr0812
I'm trying the list comprehension method to find items in my list that are larger than one of my variables.
However, I get this error message:
TypeError: '>' not supported between instances of 'list' and 'float'
I don't know how to get around it. Any tips?
Here is my Program:
def read_points():
global alfa
alfa = []
alfa.append([])
alfa.append([])
a = 0
b = 0
a = float(a)
b = float(b)
print("Input the points, one per line as x,y.\nStop by entering an empty line.")
while a == 0:
start = input()
if start == '':
a = a + 1
if b == 0:
print("You did not input any points.")
else:
alfa[0].append(int(start.split(",")[0]))
alfa[1].append(int(start.split(",")[1]))
b = b + 1
else:
print(alfa)
def calculate_midpoint():
midx = sum(alfa[0]) / len(alfa[0])
global midy
midy = sum(alfa[1]) / len(alfa[1])
print("The midpoint is (",midx,",",midy,").")
def above_point():
larger = [i for i in alfa if i > midy] ### PROBLEM IS HERE :) ###
number_above = len(larger)
print("The number of points above the midpoint is", number_above)
def main():
read_points()
calculate_midpoint()
above_point()
main()
alfa is a list of lists.
this:
larger = [i for i in alfa if i > midy]
compares one of the inner lists list i against a float midy
which is not supported. Thats the exact meaning of your error message “not supported between instances of 'list' and 'float”.
I would join your coords from two inner lists holding all x and all y to a list of points(x,y) and filter those that lie above your midy value:
points = [ (x,y) for x,y in zip(*alfa) ]
larger = list(filter( lambda p: p[1] > midy, points)) # get all points that have y midy
I have a dataframe:
import pandas as pd
df = pd.DataFrame({'start' : [5, 10, '$%%', 20], 'stop' : [10, 20, 30, 40]})
df['length_of_region'] = pd.Series([0 for i in range(0, len(df['start']))])
I want to calculate length of region only for non-zero numeric row values and skip function for the row with an error note if the value is not right. Here is what I have so far:
df['Notes'] = pd.Series(["" for i in range(0, len(df['region_name']))])
for i in range(0, len(df['start'])):
if pd.isnull(df['start'][i]) == True:
df['Notes'][i] += 'Error: Missing value for chromosome start at region %s, required value;' % (df['region_name'][i])
df['critical_error'][i] = True
num_error = num_error+1
else:
try:
#print (df['start'][i]).isnumeric()
start = int(df['start'][i])
#print start
#print df['start'][i]
if start == 0:
raise ValueError
except:
df['Notes'][i] += 'Error: Chromosome start should be a non zero number at region %s; ' % (df['region_name'][i])
#print df['start'][i]
df['critical_error'][i] = True
num_error = num_error+1
for i in range(0, len(df['start'][i])):
if df['critical_error'][i] == True:
continue
df['length_of_region'][i] = (df['stop'][i] - df['start'][i]) + 1.0
However, pandas converts df['start'] into a str variable and even if I use int to convert it, I get the following error:
df['length_of_region'][i] = (df['stop'][i] - df['start'][i]) + 1.0
TypeError: unsupported operand type(s) for -: 'numpy.int64' and 'str'
What am I missing here? Thanks for your time!
You can define a custom function to do the calculation then apply that function to each row.
def calculate_region_length(x):
start_val = x[0]
stop_val = x[1]
try:
start_val = float(start_val)
return (stop_val - start_val) + 1.0
except ValueError:
return None
The custom function accepts a list as input. The function will test the start value to see if it can be converted into a float. If it cannot then None will be returned. This way if '1' is stored as a string the value can still be converted to float and won't be skipped whereas '$%%' in your example cannot and will return None.
Next you call the custom function for each row:
df['length_of_region'] = df[['start', 'stop']].apply(lambda x: calculate_region_legnth(x), axis=1)
This will create your new column with (stop - start) + 1.0 for rows where start is not a non-convertible string and None where start is a string that cannot be converted to a number.
You can then update the Notes field based on rows where None is returned to identify the regions where a start value is missing:
df.loc[df['length_of_region'].isnull(), 'Notes'] = df['region_name']
After staring at the code for quite some time, found a simple and elegant fix to reassign df['start'][i] to start that I use in try-except as follows:
for i in range(0, len(df['start'])):
if pd.isnull(df['start'][i]) == True:
df['Notes'][i] += 'Error: Missing value for chromosome start at region %s, required value;' % (df['region_name'][i])
df['critical_error'][i] = True
num_error = num_error+1
else:
try:
start = int(df['start'][i])
df['start'][i] = start
if start == 0:
raise ValueError
except:
df['Notes'][i] += 'Error: Chromosome start should be a non zero number at region %s; ' % (df['region_name'][i])
#print df['start'][i]
df['critical_error'][i] = True
num_error = num_error+1
for i in range(0, len(df['start'][i])):
if df['critical_error'][i] == True:
continue
df['length_of_region'][i] = (df['stop'][i] - df['start'][i]) + 1.0
Re-assigning the start variable, converts it into int format and helps to calculate length_of_region only for numeric columns
I am trying to fetching data from sqllite db which has data. But i dont know why this is throwing error. This D = self.con.execute('select length from googlepagelength where urlid = {0}'.format(row[0])).fetchone()[0] is printing 3 values but on next iteration it gives error.
code:
def bm25scoreresultsfromGoogle (self, rows, wordids, k = 2.0, b = 0.75):
# Find total number of documents in the collection
#print 'row',rows
#print 'wordids',wordids
N = self.con.execute ('select count(*) from googleurllist').fetchone()[0]
N = float(N)
# Find the length for all documents in collection (not only the retrieved ones)
ids = [id for id in self.con.execute ('select rowid from googleurllist')]
alldoclengths = dict([(id[0], self.con.execute ('select length from googlepagelength').fetchone()[0]) for id in ids])
# Calculate avgdl (average doc length)
avgdl = 0.0
for i in range(len(alldoclengths)):
avgdl += alldoclengths.values()[i]
avgdl = avgdl*1/len(alldoclengths)
scores = dict([(id[0], 0.0) for id in ids])
# Calculate |D| -> Document length
i=0
#print 'row',rows
for row in rows:
i=i+1
#print i,'rowww',row[1]
D = self.con.execute('select length from googlepagelength where urlid = {0}'.format(row[0])).fetchone()[0] # error appearing
#print 'D',D #
tempscore = 0.0
for wordid in wordids:
wordfreq = self.con.execute('select count (*) from googlewordlocation where urlid = %i and wordid = %i' %(row[0], wordid)).fetchone()[0]
print 'wf',wordfreq
num = wordfreq*(1.0 + k)
den = b*D*1/avgdl
den += (1.0 - b)
den *= k
den += wordfreq
# Calculate the right part of the equation
rscore = num*1/den
# Find number of documents containing wordid
nq = self.con.execute('select distinct urlid from googlewordlocation where wordid = %i' %wordid)
nq = len([id for id in nq])
# Calculate IDF
IDF = log10((N - nq + 0.5)*1/(nq + 0.5))
tempscore += IDF*rscore
scores[row[0]] = tempscore
#print 'IDF',scores[row[0]]
return self.normalizescores(scores)
Error:
in bm25scoreresultsfromGoogle
D = self.con.execute('select length from googlepagelength where urlid = {0}'.format(row[0])).fetchone()[0]
TypeError: 'NoneType' object has no attribute '__getitem__'
is anything which i am doing wrong?
10.5.8 MySQLCursor.fetchone() Method
This method retrieves the next row of a query result set and returns a single sequence, or None if no more rows are available. By default, the returned tuple consists of data returned by the MySQL server, converted to Python objects. If the cursor is a raw cursor, no such conversion occurs; see Section 10.6.2, “cursor.MySQLCursorRaw Class”.
source: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchone.html
You're trying to retrieve information from a NoneType since the function returns that when no more rows are available. (You reach the ending of your query results)
A quick, but ugly 'fix':
D = self.con.execute('select length from googlepagelength where urlid = {0}'.format(row[0])).fetchone()
if D:
D = D[0]
This would fail afterwards since D is no the same type you're expecting(if any), hence why I don't recommend to use this code directly but just as a reference of how to fix the error.
6174 is known as Kaprekar's constant[1][2][3] after the Indian mathematician D. R. Kaprekar. This number is notable for the following property:
Take any four-digit number, using at least two different digits. (Leading zeros are allowed.)
Arrange the digits in descending and then in ascending order to get two four-digit numbers, adding leading zeros if necessary.
Subtract the smaller number from the bigger number.
Go back to step 2.
Dattaraya Ramchandra Kaprekar
number="0011"
print(" helo world, lets do this: " , number)
i = 0
while number != "6174":
sortedS = sorted(number)
String[] sortedString = array[4] av strangen number
reversed = sorted(number, reverse=True)
sortedIntMin = int(sortedS[0]+sortedS[1]+sortedS[2]+sortedS[3])
reversedIntMax = int(reversed[0]+reversed[1]+reversed[2]+reversed[3])
i += 1
number = str(reversedIntMax - sortedIntMin)
reversedIntMax - sortedIntMin
print("det behovdes " , i , "iterationer for processen")
This is my unsuccessful attempt
def Kaprekar(number, i):
if number == 6174:
return
elif number != 6174:
sortedString = sorted(number)
reversedString = sorted(number, reverse=True)
sortedIntMin = int(sortedString[0]+sortedString[1]+sortedString[2]+sortedString[3])
reversedIntMax = int(reversedString[0]+reversedString[1]+reversedString[2]+reversedString[3])
num = reversedIntMax - sortedIntMin
print("processen kors", num )
return 1 + Kaprekar(str(num), i)
print(" helo world, lets do this: ")
print("det behovdes " , Kaprekar("1547", 0) , "iterationer for processen")
there are three things that are wrong: -
You don't need i. remove it from function definition.
The variable you are passing is a string and you are comparing it with an integer, convert it to a string while comparing.
You need to return 1 when number='6174', while you are returning None.
Also, it can be done a bit clearer if list is joined after sorted and it can be directly converted to integer, (thanks endzior for the edit)
try this : -
def Kaprekar(number):
if number == '6174':
return 1
elif number != '6174':
sortedString = ''.join(sorted(number))
reversedString = ''.join(sorted(number, reverse=True))
sortedIntMin = int(sortedString)
reversedIntMax = int(reversedString)
num = reversedIntMax - sortedIntMin
print("processen kors", num )
return 1 + Kaprekar(str(num))
print(" helo world, lets do this: ")
print("det behovdes " , Kaprekar("1547") , "iterationer for processen")
number is a string, so in the first 2 if statements :
if number == '6174':
return 1
else:
And as in another answer i variable is not needed here.