I don't know if this is a simple question or not, but I couldn't find anything on it so I figured I would ask it.
I try to call a function in a while loop but it keeps on returning the same result until the condition is completed. The function main() is imported from another file and return a list with two elements [a,b].
Those two elements are generated randomly, therefor they should change after every step. The function works perfectly fine if I call it on its own.
Here is my code so far, I hope someone can help me:
I thought there was something wrong with my list x so I tried to delete it after every step, but it doesn't change anything.
from some_module import main
def loop(variable):
i = 0
while i <= 5 :
x = main(variable)
a ,b = x[0], x[1]
print a, b
del x[:]
i += 1
The code for main() is :
def main(file):
iniciate(file)
obtain_neighbours(initial_solution())
get_all_costs(get_all_solutions())
return get_best_solution()
And the random choice appears in the function initial_solution() :
#those list are being updated at every step
So = []
I_assign = []
I_available = ['1','2','3','4',...,'n']
def initial_solution():
while len(I_available) != 0:
update_I_assign()
random_task = random.choice(I_assign)
So.append(random_task)
I_available.remove(random_task)
return So
def get_best_solution():
if min(i for i in all_cost) < calculate_cost(fill_station(So)):
best_solution = solutions[all_cost.index(min(i for i in all_cost))]
return [min(i for i in all_cost),best_solution]
else:
best_solution = fill_station(So)
return [calculate_cost(fill_station(So)),best_solution]
It's pretty hard for me to show the rest of the code here because it's quite long. Hope the update helps you understand.
Related
I have this error when executing my code. I looked around on other posts about this, but all these posts mention the use of () or [] where they should not be used. However, in my case I do not see that being the issue as the only thing I am trying to do is overwrite the value of an index of one list with another item of another list. This is the code I am trying to call it in:
def reproduce(boardx, boardy, nqueens):
boardChild = [-1] * nqueens
n = random.randint(0, nqueens - 1) #percentage of how much of one parent is reproduced and how much of the other parent
d = 0
for d in range(n): # the first n part of parent x
boardChild[d] = boardx[d]
s = d + 1
for s in range(nqueens - 1): # the last n-(len(board)-1) part of parent y
boardChild[s] = boardy[s]
return boardChild
Python currently only gives an error about this line:
boardChild[s] = boardy[s]
but not the similar line in the loop above it. This is how I call the function (population[j] and population[k] are lists for reference):
childx = population[j].copy
childy = population[k].copy
child = reproduce(childx, childy, nqueens)
I also tried to find out if any of the used variables were known functions, but that does not seem to be true either. I am completely lost with this one. Is anyone able to help?
childx = population[j].copy
childy = population[k].copy
If you are trying to use the copy method of a list, this will not do that. You are accessing the method, but not calling it so childx and childy are functions.
I admit I am not sure why the first loop doesn't raise this error though.
The problem here is that your variable boardy seems to be a variable. If you change that variable name to anything else it should work fine. Something like:
def reproduce(boardX, boardY, nqueens):
boardChild = [-1] * nqueens
n = random.randint(0, nqueens - 1) #percentage of how much of one parent is reproduced and how much of the other parent
d = 0
for d in range(n): # the first n part of parent x
boardChild[d] = boardX[d]
s = d + 1
for s in range(nqueens - 1): # the last n-(len(board)-1) part of parent y
boardChild[s] = boardY[s]
return boardChild
I am new to Python functions and am just practicing on my end. I wrote some basic code that asks user for a number input, 9 times, and then outputs either True or False based on > 100 or < 100.
This code works fine:
list_1 = []
count = 0
while count < 10:
text = int(input('list a number:'))
if text < 100:
list_1.append(True)
else:
list_1.append(False)
count = count + 1
print(list_1)
Now I want to convert that into a function (using For loop instead, for something different). I tried a few versions and can't get it, nothing happens when i run this:
def foo():
list_1 = []
text = int(input('list a number:'))
for x in range(10):
if text > 100:
list_1.append(True)
else:
list_1.append(False)
return()
2 questions:
How do I write that function so it is actually useful and returns True or False?
Can someone show me a basic example of how using a function in this instance could be worthwhile? Like how could I separate it from the first piece of code so it's actually useful in a different way?
I'd like to branch out from just writing pieces of code, to organizing it in a more efficient way
Thanks
It looks like you have an error in your return value for foo().
Make sure you return the list out of your function. for example:
def foo():
list_1 = []
for x in range(10):
text = int(input('list a number:'))#this should be inside the loop
if text > 100:
list_1.append(True)
else:
list_1.append(False)
return(list_1) #you are passing list_1 after your for loop
bool_list = foo() #will pass return value in function
#print(list_1) this will throw an error!
print(bool_list) #bool_list was list_1 in foo()
Reading up on namespaces, it is critical for understanding funcitons. When you launch foo(), it will run its own code, but if you don't pass objects with a return value, you can't use it in other places.
Functions are absolutely essential for well maintained code. Anytime an operation is needed repeatedly, functions cut down on unnecessary lines of code. They also offer versatility when the same operation needs to be run many times but in slightly different ways. You could pass an argument through foo() specifying how many times you want to run through your for loop, for example.
There's an almost unlimited number of ways that you can use functions. The main driver in your decision is whether or not you can reuse functionality or if it simplifies your code. So in essence, can I build this into a building block is the question you should ask yourself.
So in your example, say you have to take input in several different scenarios or you have to maybe evaluate a number of lists and provide print output.
You could separate things based on that:
def take_input(list):
count = 0
while count < 5:
inputlist.append(int(input('list a number:')))
count += 1
def print_output(list):
outputlist = []
for input in list:
if input < 100:
outputlist.append(True)
else:
outputlist.append(False)
print(outputlist)
inputlist = []
take_input(inputlist)
print_output(inputlist)
possibleRequests = ['test', 'test1']
def inboxReader():
global inbox
tempInbox = []
tempInbox = inbox.inboxMessage #inboxMesage remains filled?
print(inbox.inboxMessage, 'inboxReader')
i = 0
while (i < len(tempInbox)):
if (tempInbox[i] in possibleRequests):
print('THIS IS WORKING')
#print(i)
i+=1
I want to be able to have possible requests point towards a method to run rather than have a long list of if statments. What am I able to do in order to have a variable point towards and run a method.
Cheers,
Marc
You can first create a dictionary of functions then refer to it with tempInbox[i]. Example code below:
def func_a(x):
return x
def func_b(x):
return x*10
tempInbox = (2,3)
fn_dict = {"a":func_a,"b":func_b}
print fn_dict["a"](tempInbox[0]) # returns 2
print fn_dict["b"](tempInbox[1]) # returns 30
Basically, my question is about how to run this code? Finding the second smallest number from the given list using divide-and-conquer. I tried with print..But it gives me nothing. Just wanna see how this code works. Sorry for simple question, totally New in Python.
Well, just use a function call to run it, and a print to print it:
def two_min(arr):
n = len(arr)
if n==2: # Oops, we don't consider this as comparison, right?
if arr[0]<arr[1]: # Line 1
return (arr[0], arr[1])
else:
return (arr[1], arr[0])
(least_left, sec_least_left) = two_min(arr[0:n/2])
(least_right, sec_least_right) = two_min(arr[n/2:])
if least_left < least_right: # Line 2
least = least_left
if least_right < sec_least_left: # Line 3
return (least, least_right)
else:
return (least, sec_least_left)
else:
least = least_right
if least_left < sec_least_right: # Line 4
return (least, least_left)
else:
return (least, sec_least_right)
print two_main([12,2])
If you'd like to know how this works, you can take a look at the online python visualizer. Link.
I am currently working on a BASIC simulator in Python, as the title suggests. Here is my code for this problem:
def getBASIC():
l = []
x = 1
while x == 1:
i = input()
l.append(i)
if len(i.split()) != 3:
x = 0
return l
def findLine(prog, target):
for l in range(0, len(prog)):
progX = prog[l].split()
if progX[0] == target:
return l
def execute(prog):
location = 0
visited = [False] * len(prog)
while True:
T = prog[location].split()[2]
location = findLine(prog, T)
visited[location] = True
if visited[len(visited)-1] == False:
return "infinite loop"
else:
return "success"
The first function does what it is intended to do -- convert input of BASIC code into a list. The second function, findLine also does what it is intended to do, in that it finds the item which contains the string equal to the input. The last function, however, I cannot get to work. I know what I have to do, and that is to check whether or not a part of it has been visited twice. I cannot figure out how to do this, due to the existence of the while loop. As a result of this, the second half of that function is just placeholder. If you could help me figure out how to solve this, it would be greatly appreciated. Thanks.
You keep a list of places that have been visited (you already do this) and then when you encounter a goto, you check if it does to a line that already have been visited, and if it has been visited, you exit.
One mistake right now is that you make a list that is as long as the program is. That's pretty pointless. Just keep a list of the visited line numbers instead, and check with
if current_line in visited:
Try adding an if statement declaring a line in the visited list to be true when it is encountered in the loop. This is my solution:
def execute(prog):
location = 0
visited=[False]*len(prog)
while True:
if location==len(prog)-1:
return "success"
if visited[location]==True:
return "infinite loop"
if visited[location]==False:
visited[location]=True
line2strings=prog[location].split()
T=line2strings[-1]
location=findLine(prog, T)