Changing values in an list? [duplicate] - list

I want to remove some words from a list of words. I have a list with a recurring word and I want to get rid of it and I have no idea. I don't know whether I need to use a whole loop or regex.
from xlrd import open_workbook,error_text_from_code
book = open_workbook(inp)
sheet0 = book.sheet_by_index(0)
x = 0
y = 0
countr = sheet0.nrows
countc = sheet0.ncols
names = ''
variables = []
"different variables-----------------"
while x < countr -1:
x = x+1
y = y+1
cell = sheet0.cell(y,0)
names = names+ str(cell)
cell = sheet0.cell(y,1)
variables.append(cell)
country_text = names
countries = ', '.join(re.findall("('.*?')", country_text))
countries = countries.split()
print (variables)
print (countries)
What I get :
[number:150000.0, number:140000.0, number:300000.0]
and I need
[150000, 140000, 300000]

If you use a loop you can access to the value of a cell using this function:
sheet0.cell_value(curr_row, curr_cell)

Related

Implementation of Karger's Algorithm in Python Taking too Long

Wondering if you can help me understand where the critical flaw may be with my attempt at implementing Karger's algorithm in python. My program appears to take far too long to run and my computer starts to overwork running large sets of vertices. The purpose of the program is to output the minimum cut of the graph.
from random import choice
from statistics import mode
import math
fhand = open("mincuts.txt", "r")
vertices = fhand.readlines()
d = {}
for index,line in enumerate(vertices):
d["{0}".format(index+1)] = line.split()
def randy(graph, x):
y = str(choice(list(graph)))
if x == y:
y = randy(graph, x)
return y
count = 0
def contract(graph):
global count
if len(graph) == 2:
a = list(graph.keys())[0]
b = list(graph.keys())[1]
for i in range(1, len(graph[a])):
if graph[a][i] in graph[b]:
count = count + 1
#print(graph)
return
x = str(choice(list(graph)))
y = randy(graph, x)
#print(x)
#print(y)
graph[x] = graph[x] + graph[y]
graph.pop(y)
#remove self loops
for key in graph:
#method to remove duplicate entries in the arrays of the vertices. Source: www.w3schools.com
graph[key] = list(dict.fromkeys(graph[key]))
contract(graph)
N = len(d)
runs = int(N*N*(math.log(N)))
outcomes = []
for i in range(runs):
e = d.copy()
count = 0
contract(e)
outcomes.append(count)
print(outcomes)
#returns most common minimum cut value
print(mode(outcomes))
Below is a link to the graph I am running in mincuts.txt:
https://github.com/BigSoundCode/Misc-Algorithm-Implementations/blob/main/mincuts.txt

Django. Using variable in a Queryset

I have a query
variable3 = "Field3"
variable_gte = "flowrate__gte"
x = mytable.objects.filter(Q((variable_gte, variable2))).order_by(variable3)[0:5]
z = x[0].Field3
How can I call this last value z using variable3, something similar to z = x[0].variable3
If it is impossible, I will need to use if/else condition:
if variable3 = "Field3":
z = x[0].Field3
else:
....
Thank you.
You can make use of getattr(…) [Django-doc]:
variable3 = 'Field3'
variable_gte = 'flowrate__gte'
x = mytable.objects.filter(
Q((variable_gte, variable2))
).order_by(variable3)[0:5]
z = getattr(x[0], variable3)
If you write getattr(x, 'y'), this is equivalent to x.y, so you can pass a string with the name of the attribute and obtain the attribute of that name.
It however does not make much sense to first slice, and then obtain the first item. You can remove the …[0:5] part.

count index in a list to x number python

I have a list with like this that goes from 0 to 1000 .
x = ['0_1','0_2','0_3' ..., '1000_1','1000_2','1000_3']
I need it to count every time the char in index changes like I show below.
list_leng = len(x)
for i in range(0, list_leng):
y = x[i]
z = y[0]
print this should iterate through all the list and only print when the z number changes ' # how should I make it print '
If I understood your question well, the answer must be something like this;
comparisonText = ""
for each in x:
preNumber = each.split('_')[0]
if comparisonText != preNumber:
print preNumber, 'is different than previous.'
comparisonText = preNumber #change the comparisonText

Getting "wrong number of bind variables" when I'm trying to write a Rails finder method

I’m using Rails 4.2.3. I’m having trouble passing a variable number of search criteria to my Rails finder method. I have
user = current_user
search_criteria = ["my_objects.user_id = ?"]
search_values = [user.id]
start_date = params[:start_date]
if start_date.present?
start_date_obj = Date.strptime(start_date, "%m/%d/%Y")
search_criteria.push("my_objects.start_date >= ?")
search_values.push(start_date_obj)
else
start_date = my_object.find_user_first_my_object_date(user)
#default_start_date = start_date.to_time.strftime("%m/%d/%Y") if start_date.present?
end
end_date = params[:end_date]
if end_date.present?
end_date_obj = Date.strptime(end_date, "%m/%d/%Y")
search_criteria.push("my_objects.end_date <= ?")
search_values.push(end_date_obj)
else
end_date = my_object.find_user_last_my_object_date(user)
#default_end_date = end_date.to_time.strftime("%m/%d/%Y") if end_date.present?
end
distance = params[:distance]
if distance.present?
distance_parts = distance.split(" ")
search_criteria.push("my_objects.distance = ?")
search_criteria.push("my_objects.distance_unit_id = ?")
search_values.push("#{distance_parts[0]}")
search_values.push("#{distance_parts[1]}")
end
#user_my_objects = MyObjectTime.joins(:my_object).where(search_criteria.join(" AND "), search_values)
.order("my_objects.day")
But this results in the error
wrong number of bind variables (1 for 5) in: my_objects.user_id = ? AND my_objects.start_date >= ? AND my_objects.end_date <= ? AND my_objects.distance = ? AND my_objects.distance_unit_id = ?
I think Rails is treating my “search_values” array as a single value but I want it to pass each value of the array as an argument into the search condition. How do I fix the above?
If I've read the question right, this boils down to
values = ['a', 'b', 'c']
SomeModel.where("foo = ? AND bar = ? AND baz = ?", values)
Throwing an error about an incorrect number of bind variables. To unpack an array and use its values as individual arguments you use the splat operator:
SomeModel.where("foo = ? AND bar = ? AND baz = ?", *values)

web2py append dictionary to list

I create a list of dictionaries from excel. The code is listed below. What happens is the list contains the last row excel values for all the rows. I tried in python shell. It works fine. Why all the rows get updated with last row values?
d = {}
l = []
up = os.path.join(request.folder,'uploads')
workbook = xlrd.open_workbook(os.path.join(request.folder,'uploads','meas.xls'))
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
num_cells = worksheet.ncols - 1
curr_row = -1
while curr_row < num_rows:
curr_row += 1
row = worksheet.row(curr_row)
#print 'Row:', curr_row
curr_cell = -1
while curr_cell < num_cells:
curr_cell += 1
# Cell Types: 0=Empty, 1=Text, 2=Number, 3=Date, 4=Boolean, 5=Error, 6=Blank
cell_type = worksheet.cell_type(curr_row, curr_cell)
cell_value = worksheet.cell_value(curr_row, curr_cell)
#print ' ', cell_type, ':', cell_value
if curr_cell == 0:
d['loc_of_work'] = cell_value
if curr_cell == 1:
d['n'] = cell_value
if curr_cell == 2:
d['t'] = cell_value
if curr_cell == 3:
d['l'] = cell_value
if curr_cell == 4:
d['b'] = cell_value
if curr_cell == 5:
d['d'] = cell_value
print 'dict'
print d.items()
l.append(d)
print 'len of list:'
print len(l)
print 'list:'
for i,j in enumerate(l):
print i,j
The issue is you are declaring d outside the while loop, which means within the loop you are simply overwriting the same dict with new values on every iteration. Your list simply contains multiple references to the same dict object, which contains the values from the last row because those are the last values to be written to the dict (all previous values are overwritten)
moveoing:
d = {}
inside the first while loop should fix your issue