Python 3, list.append not working - python

New here and have been hunting around for the answer to this question. Working on a Project Euler question and attempting to add values of a function to a list using list.append, however nothing is being added to the list and I'm unsure why. Any help appreciated.
import math
import logging
%config Application.log_level="INFO"
input = 600851475143
factlist = []
def factors(i):
for i in range(1, int(math.sqrt(input)) + 1):
if(input%i == 0):
factlist.append()
print(i)
Have tried defining the list inside and outside of the loop but to no avail.

As I said in a comment, you need to actually call the function somewhere, and you also need to give an argument to append :
import math
import logging
%config Application.log_level="INFO"
input_ = 600851475143
def factors(input_):
factlist = []
for i in range(1, int(math.sqrt(input_)) + 1):
if(input_%i == 0):
factlist.append(i)
factlist = factors(input_)
Moreover, don't use the name input for a variable since it's a Python function.

You need to pass the element you want to append as a parameter to append.

Pass the right argument:
if(input%i == 0):
factlist.append(i) #<- i added
print(i)
And of course, you need to call your function somewhere

Related

TypeError: 'builtin_function_or_method' object is not subscriptable (while not using a function)

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

Omit in for loop in Python

I have a function to move between the given range of values, but I would like to add in my function a parameter that will be an array which would contain the numbers which must be skipped while my function run iteration
my function:
nums = []
def loopIteration(minValue, maxValue):
minValue += 1
for i in range(maxValue-minValue+1):
num = i+minValue
nums.append(Num('numbers_{}'.format(i)))
#function call
loopIteration(4,25)
i want to add in my function call an parameter like this:
loopIteration(4,25,[8,9,16])
thanks for any answers :)
You can use continue to skip certain is:
def loopIteration(minValue, maxValue, skip=set()):
for i in range(minValue + 1, maxValue + 1):
if i in skip:
continue
cells.append(Cell("numbers_{}".format(i)))
Continue is a Python syntax which would allow you to pass iteration in a for loop. Usually, continue can make it quite hard to follow flow later on, if you ever wish to look back on your script. Here is what you could do:
def loopInteration(minValue, maxValue, skipNums):
for number in range(maxValue-minValue+1):
if number in skipNums:
continue
num = i+minValue
nums.append(Num("numbers_{}".format(i)))
loopIteration(4,25,[NUMBERS HERE])

Turning Python code into a function

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)

Number of Odds and Evens in a List Function - Python

I am trying to create a function called "odd_even" which takes my already created list (named "nums") and determines the number of odd and even numbers, and then returns the variables to me. However when I run this code I get:
NameError: name 'odd' is not defined
How do I fix this? If you can give me any useful pointers on the "return" function that would also be greatly appreciated.
import random
def main():
nums = []
for x in range(10):
nums.append(random.randrange(1,26))
def odd_even(given_list):
odd = 0
even = 0
for x in given_list:
if x % 2 == 0:
even += 1
else:
odd += 1
return odd
return even
odd_even(nums)
print("List had ", odd, "odds and ", even, "evens.")
main()
You are doing 2 things wrong.
First, you are trying to return two values but on different lines. You cant do this, to do this, do so as a tuple:
def odd_even(given_list):
odd = 0
even = 0
for x in given_list:
if x % 2 == 0:
even += 1
else:
odd += 1
return odd, even
Second, you call the function but dont store the value(s) of return. So you need change:
odd_even(nums) to odd, even = odd_even(nums)
By trying to execute:
print("List had ", odd, "odds and ", even, "evens.")
The main() is looking for variables odd and even, but they dont exist in main(), they exist locally in odd_even() (hence why you are calling return as to return them to the calling function. The reason you only see an error with respect to odd is because it is the first variable in that print() that the interpreter encounters an error on.
The only way around this without correct use of return is to declare them as global. But that is a bad idea so don't do that, keep things local on the stack!
You have some syntactic errors. Python...unlike many programming languages is whitespace conscious. This means you need to be careful with your indentation and spacing. More traditional languages like Java and C use brackets {} to define a scope, and semicolons ; to figure out line termination.
Perhaps you copied it poorly, but from what I see, it appears as though you are defining the function odd_even() within the function main(). That is, the definition of odd_even() is tabbed to the right, which means that its definition is within the function main. I assume that you want main to call the function odd_even(). Thus, you must tab it back over to the left so that it is at the same indentation level as main().
For this reason I use horizontal lines (see below) to clearly outline the scope of functions. This is good for me when I write in Python because otherwise it can be very unclear where one function ends, and where another begins.
Also, it appears as though you have 2 return statements. If you want to return 2 values, you should encompass it within an object. To get around this, there are two simple solutions that come to mind. You can make the odd_even() function access global variables (not recommended)...or you can return an array (any number of values back) or a tuple (exactly 2, but this is python specific).
Below is an implementation of both:
import random
# Declare global variables outside the scope of any function
odd = 0
even = 0
#-------------------------------------------------------------------------------
def main():
nums = [1,2,3,4,5,6,7,8,9,10]
return_value = odd_even(nums)
# Get the individual values back
o = return_value[0]
e = return_value[1]
# You can use the global variables
print("List had ", odd, "odds and ", even, "evens.")
# Or you can get the array back
print("List had ", o, "odds and ", e, "evens.")
#-------------------------------------------------------------------------------
def odd_even(given_list):
# This means we are referencing the variables odd and even that are global
global odd
global even
# Loop through the array
for x in given_list:
if x % 2 == 0:
even += 1
else:
odd += 1
return [odd, even]
#-------------------------------------------------------------------------------
main()

Issue with calling a function inside a while loop

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.

Categories