create a function that adds to a list - python-3.x

I have en assignment about lists that goes like this,
Create a global variable called myUniqueList. It should be an empty list to start.
Next, create a function that allows you to add things to that list. Anything that's passed to this function should get added to myUniqueList, unless its value already exists in myUniqueList. If the value doesn't exist already, it should be added and the function should return True. If the value does exist, it should not be added, and the function should return False;
Finally, add some code below your function that tests it out. It should add a few different elements, showcasing the different scenarios, and then finally it should print the value of myUniqueList to show that it worked.
Add another function that pushes all the rejected inputs into a separate global array called myLeftovers. If someone tries to add a value to myUniqueList but it's rejected (for non-uniqueness), it should get added to myLeftovers instead."
This is the code I have wrote to create the lists and add value to the list but I dont get the output I want from this code, can someone help me explain what I do wrong how do I write so my list get filled with elements? The Output I get from the code now, you can see below.
myUniqueList = []
myLeftovers = []
def addList(newThing):
if newThing in myUniqueList:
myLeftovers.append(newThing)
return False
else:
myUniqueList.append(newThing)
return True
print(myUniqueList) # []
print(addList("Meliodas")) # returns 'True' since it's a new item
print(addList("Escanor")) # returns 'True' since it's a new item
print(addList("Meliodas")) # returns 'False' since it's already been added
print(myUniqueList) # This includes the new entries
print(myLeftovers) # This includes any repeated entries
I get
[]
False
False
False
[]
[]
Can you explain why the list dont get the words added and why I get Syntax Error on the else statement

According to your question, you were asked to create a global variable called myUniqueList. Since myUniqueList is a global list, in other to use it in a function, we have to tell the function we are using a global list by adding "global" before myUniqueList; hence your code will be as follows:
myUniqueList = []
myLeftovers = []
def add(newValue):
global myUniqueList
if newValue in myUniqueList:
addToLeftovers(newValue)
return False
else:
myUniqueList.append(newValue)
return True
def addToLeftovers(newValue):
myLeftovers.append(newValue)
# Testing the code:
print(add("Hello"))
print (myUniqueList)
print(add("Hello"))
print(myUniqueList)
print(myLeftovers)
Your Result will be as follows:
True
['Hello']
False
['Hello']
['Hello']
The first "Hello" came out TRUE while the second "Hello" came out FALSE. Then the third "Hello" was from the second hello which was rejected and now, pushed to the "myLeftovers" as stated in your question.

Related

.get_dummies() works alone but doesnt save within function

I have a dataset and I want to make a function that does the .get_dummies() so I can use it in a pipeline for specific columns.
When I run dataset = pd.get_dummies(dataset, columns=['Embarked','Sex'], drop_first=True)
alone it works, as in, when I run df.head() I can still see the dummified columns but when I have a function like this,
def dummies(df):
df = pd.get_dummies(df, columns=['Embarked','Sex'], drop_first=True)
return df
Once I run dummies(dataset) it shows me the dummified columsn in that same cell but when I try to dataset.head() it isn't dummified anymore.
What am I doing wrong?
thanks.
You should assign the result of the function to df, call the function like:
dataset=dummies(dataset)
function inside them have their own independent namespace for variable defined there either in the signature or inside
for example
a = 0
def fun(a):
a=23
return a
fun(a)
print("a is",a) #a is 0
here you might think that a will have the value 23 at the end, but that is not the case because the a inside of fun is not the same a outside, when you call fun(a) what happens is that you pass into the function a reference to the real object that is somewhere in memory so the a inside will have the same reference and thus the same value.
With a=23 you're changing what this a points to, which in this example is 23.
And with fun(a) the function itself return a value, but without this being saved somewhere that result get lost.
To update the variable outside you need to reassigned to the result of the function
a = 0
def fun(a):
a=23
return a
a = fun(a)
print("a is",a) #a is 23
which in your case it would be dataset=dummies(dataset)
If you want that your function make changes in-place to the object it receive, you can't use =, you need to use something that the object itself provide to allow modifications in place, for example
this would not work
a = []
def fun2(a):
a=[23]
return a
fun2(a)
print("a is",a) #a is []
but this would
a = []
def fun2(a):
a.append(23)
return a
fun2(a)
print("a is",a) #a is [23]
because we are using a in-place modification method that the object provided, in this example that would be the append method form list
But such modification in place can result in unforeseen result, specially if the object being modify is shared between processes, so I rather recomend the previous approach

Python Try Except when a list is null

I've been searching for my problem here, but i can't find the exact answer to my problem.
I call a sympy function ( solve() ). This function can return a full list or an empty list.
I call this piece of code inside a while:
try:
sol = solve([eq1,eq2],[r,s])
rB = bin(abs(sol[0][0]))
sB = bin(abs(sol[0][1]))
stop = True
r = rB[2:len(rB)]
s = sB[2:len(sB)]
P = int("0b"+r+s,2)
Q = int("0b"+s+r,2)
print(P*Q == pubKey.n)
print("P = {}".format(P))
print("Q = {}".format(Q))
break
except ValueError:
pass
What i want is:
if the solve() returns an empty list, just pass. And if the solve() returns a full list, keep with the execution. The solve will be returning empty list until i find the right value.
This can be reached by checking sol[0][0], if there's a non-empty list this will work, but if the list is empty, this will throw an error (null pointer) i want try to flag it and pass.
What i'm having now is that when sol is empty, it tries to get sol[0][0], and ofc this throws an error that's not being catched by the try, and the whole code stops.
Anyone knows a solution for that? I'm not using try correctly?
Set sol in the beginning of each loop to some value and check it in the except clause
about else
try/except has an else which will be run the try block did not raise an Exception
and for has an else clause for when it was not broken out of!
for foo in iterable:
# set value so the name will be available
# can be set prior to the loop, but this clears it on each iteration
# which seems more desirable for your case
sol = None
try:
"logic here"
except Exception:
if isinstance(sol, list):
"case where sol is a list and not None"
# pass is implied
else: # did not raise an Exception
break
else: # did not break out of for loop
raise Exception("for loop was not broken out of!")

Applying the change of list at the start of a function

I have been trying to create a word search generator by using list within list. However, one of the things that I've been trying to do is that the list must preserve the word that it append before rather than start a blank list. The method that I did was to simply call on a previous function for this.
initial= list()
def board ():
inital = add()
test = list()
for a in range(5):
test.append(a)
initial = test.copy()
return initial
def add():
initial = board()
for a in range(5,10):
initial.append(a)
initial = initial.copy()
return initial
initial = add()
inital = board()
print(initial)
When I tried running it in the terminal, an error message appeared saying that the maximum recursion depth has exceeded. What does this means and how do I achieve the goal (having a list that prints 5,6,7,8,9,0,1,2,3,4)?

Using loops to call recursive function

I am trying to create a recursive function that takes three parameters: name of the dictionary, name of the original (This will be the key in the dict), and name of the final (trying to determine if it is possible to reach the final from the original)
My code functions well and enters the correct if statements and everything (tested using print statements) however, instead of the function returning True or False, it returns None every time.
I determined that this is because rather than calling my recursive function with "return" I only call the name of the function. However, if I include return in my code, the function only runs with the first value from the dictionary's key.
Any and all help on this would be appreciated.
def evolve(dictname, babyname, evolvedname):
if babyname == evolvedname:
return True
elif babyname in dictname.keys():
if dictname[babyname]:
for i in dictname[babyname]:
evolve(dictname,i,evolvedname)
else:
return False
else:
return False
Collect all recursive call's results, and return True if any of them is true.
Something like:
def evolve(dictname, babyname, evolvedname):
if babyname == evolvedname:
return True
elif babyname in dictname.keys():
if dictname[babyname]:
results = [] #To collect results
for i in dictname[babyname]:
results.append(evolve(dictname,i,evolvedname))
#Check if any of them is True
for res in results:
if res==True: return True
return False #No true among childs
else:
return False
else:
return False
But I think this code can be simplified to just:
def evolve(dictname, babyname, evolvedname):
if babyname == evolvedname:
return True
return any(evolve(dictname,i,evolvedname) for i in dictname.get(babyname,[]))
Lastly, although I don't know what you are trying to do, you might get an infinite loop, this is like doing dfs but without marking any node as already explored(black) or currently exploring(gray).

Access element of list by variable name

How can I access a list element using the name of the list?
I would like to allow a user to edit the code in determine a single variable to be inputted into a function. For example:
blah = [1,2]
blah2 = 5
toBeChanged = "blah2"
def foo():
print(blah)
def changeVariable():
globals()[toBeChanged] += 1
for time in range(5):
changeVariable()
simulate
This works for blah2 since it is a simple variable, however it will not work for blah[0] since it is part of a list. I've also tried placing my variables into a dictionary as other answers have suggested, but I still am unable to change list elements through a simple string.
Is there a way to do this that I am missing? Thanks!
Rather than using globals() and altering directly it would be much, much better to use a dictionary to store the variables you want the user to alter, and then manipulate that:
my_variables = {
'blah': [1,2]
'blah2': 5
}
toBeChanged = "blah2"
def foo():
print(my_variables['blah'])
def changeVariable():
my_variables[toBeChanged] = my_variables.get(toBeChanged,0) + 1
for time in range(5):
changeVariable()
This has the added advantage that if a user enters a variable that doesn't exist a default is chosen, and doesn't override any variables that might be important for future execution.

Resources