Python function/lists - python

how do i create a function that adds something to an empty list, but if the value already exists on that list it cant be added, and has to go to another empty list. I tried this but this doesn't takes into account if a value other than x is already on the list
List = []
leftover = []
x = 2
def add(x):
if myUniqueList[0:] == []:
myUniqueList.append(x)
print("True")
print(myUniqueList)
elif myUniqueList[0:] == [x]:
leftover.append(x)
print("False")
print(leftover)
add(x)

This may work. By using the if x not in syntax, we can easily check to see if the number is in the existing list.
If it is not in the list, we then append it. If it is in the list, we append it to the leftover list.
mylist = []
leftover = []
x = 2
def add(x):
if x not in mylist:
mylist.append(x)
print('True')
print(mylist)
else:
leftover.append(x)
print('False')
print(leftover)
add(x)
Set vs List:
There are some performance ramifications if you are using massive sequences of numbers. In which case, storing the numbers in a Python set() will greatly speed up any lookups to see if the number already exists. This is due to the way that Python stores numbers in sets vs lists.
myset = set()
leftover = []
x = 2
def add(x):
if x not in mylist:
mylist.add(x) # sets use .add() instead of .append()
print('True')
print(myset)
print(list(myset)) # IF you need to print out a list, you can
# convert sets to lists by encapsulating
# the myset with the list() factory function
# BUT if you do this every cycle you prolly
# start to lose the performance benefits.
else:
leftover.append(x)
print('False')
print(leftover)
add(x)

List = []
leftover = []
x = 2
def add(x):
if x in myUniqueList:
print("False")
print(leftover)
leftover.append(x)
else:
myUniqueList.append(x)
print("True")
print(myUniqueList)
add(x)

Related

How can I make my list return each element only once in a list?

So I wrote this code to return back every string in the given lst: list once. Here is my code
def make_unique(lst: list[str]):
s = []
for x in lst:
if lst.count(x) == 1:
s.append(x)
else:
return(x)
return s
When I put in the input:
print(make_unique(lst=['row','mun','row']))
The output returns
row
but I want my output to return
['row','mun']
which is basically all the strings in the list printed once.
How can I do this??
Why not you try this one line short code to remove duplicates from your list and make it unique
def make_unique(lst):
return list(dict.fromkeys(lst))
print(make_unique(['row','mun','row'])) #['row','mun']
Easy way to do this is turn the list into a set. A set only shows each item once and thats what you want.
lst=['row','mun','row']
setLst = set(lst)
for elem in setLst:
print(elem)
You can use set.
lst=['row','mun','row']
print(set(lst))

How to delete an item from a list by python only using recursion

How do I write a code in python by only using the recursion without loops and any build in methods or functions? I tried:
def myRemove(x, cont): # x is a string inside of the list cont
if x == cont:
return None
elif len(x) > len(cont):
return None
else:
if "x" not in cont[0]:
return myRemove(x,cont[1:])
else:
return cont
Some problems I see in your code:
1. Difference between a string and a variable
You have the following line in your code which is semantically wrong:
if "x" not in cont[0]:
...
Here "x" is the string 'x' and not the value of x. To fix this remove the quotation marks.
if x not in cont[0]:
...
2. Difference between list and variable
To check if a variable is in a list use in. e.g.
>>> "test" in ["test", "wow", "u"]
true
To check if a variable is equal to another variable use ==. e.g.
>>> "test" == ["test", "wow", "u"][0]
true
The fixed part of your code: (Because cont[0] returns a value and not a list)
if x == cont[0]:
...
3. Returns in recursion
You have to concatenate the returned list with the list part before the other list.
Otherwise, you are always returning the last part of the list.
One possible solution
def remove(string, string_list):
if string_list[0] == string:
return string_list[1:]
else:
return string_list[:1] + remove(string,string_list[1:])
def recursive_remove(x: str, cont: list):
""" removes items equal to x using recursion only
cont: list of strings
x: string to remove from list
"""
if len(cont) == 0:
return []
if cont[0] != x:
return [cont[0]] + recursive_remove(x=x, cont=cont[1:])
else:
return recursive_remove(x=x, cont=cont[1:])
list_without_banana = recursive_remove(x='banana', cont=['apple', 'banana', 'strawberry', 'peanut'])
print(list_without_banana)
>>>['apple', 'strawberry', 'peanut']

Simple list function in Python

I am trying to append values (x) to a list if the numbers are divisible by 2 and then print out that list. Seems pretty simple. The following runs but returns None:
x = []
def test():
while x in range(0,100):
if x % 2 == 0:
x.append()
print(test())
Use for to iterate a range - not while.
You have ambiguous meaning to x - both as iteration variable and as a list.
You need to pass the value to append.
You need to return a value so it would be printed through the print statement - otherwise None is the default.
Fixed:
x = []
def test():
for i in range(0,100):
if i % 2 == 0:
x.append(i)
return x
print(test())
Other notes:
You can only use this once. The next call for test would return a list twice the size, since x is a global variable. I believe this is unintended and can be solved by putting the x = [] inside the function.
A list comprehension like [x for x in range(100) if x % 2 == 0] would be much better.
Problems and Fixes
Your have several problems with your code:
You named your list x and your iterate variable x.
You never append a value to your list.
You never return a list from test. Rather than appending to a global list, make a local list in test and return that list.
You're using a while loop when you should be using a for loop.
After the above changes, you code look likes:
def test():
even_numbers = []
for number in range(0, 100):
if number % 2 == 0:
even_numbers.append(number)
return even_numbers
print(test())
Improvements
Note there are better ways to do this. In this case, a list comprehension is a better choice. List comprehensions can be used to avoid the common pattern of building a list of values - such as your case:
def test():
return [n for n in range(0, 100) if n % 2 == 0]
print(test())
Generally you should pass the variable to the function and return it from the function instead of relying on global variables:
def test(x):
...
return x
However while x in range(0, 100) won't work because it will check if x (an empty list) is contained in the range object. But the range only contains numbers so the while loop body will never execute. So you could use a for-loop instead:
def test(x):
for i in range(0, 100):
if i % 2 == 0:
x.append(i)
return x
But you could also use the fact that range supports a step and remove the if by just using step=2:
def test(x):
for i in range(0, 100, 2):
x.append(i)
return x
At this point you could even just extend (append an iterable to) the list:
def test(x):
x.extend(range(0, 100, 2))
return x
You could also use a step of 2 to avoid if tests :
x = []
def test():
for i in range(0,100,2):
x.append(i)
return x
Or use a list comprehension :
x = []
def test():
x = [i for i in range(0,100,2)]
return x
Or use the range it's self as a list:
x = []
def test()
x = list(range(0,100,2))
return x
Rename your inner x variable for simplicity. Use x.append(n) instead of x.append(). Finally, print the variable not the method.
You should either change the list variable or the iteration variable(x in while loop) . and append function works like this list.append(value).

Python: Functions and Lists?

I have a function that, when inputting a list and a specific string in that list, removes any duplicates of that specific string from the list. (find_start and find_end are separate functions that determine the first and last position of a certain string)
def remove_duplicates(sorted_list, item):
i = 0
real_list = []
for x in range(len(sorted_list)-1):
if(sorted_list[i] == item):
a = find_start(sorted_list, item)
b = find_end(sorted_list, item)
real_list = real_list + [item]
i = i+(b-a)
else:
real_list = real_list + [sorted_list[i]]
i+=1
return real_list
So for example, remove_duplicates(['a','a','b','b','c','c'], 'a') would return ['a','b','b','c','c']
I'm trying to define another function that uses this function in it for each iteration, like so
def remove_all_duplicates(sorted_list):
i = 0
list_tru = []
for x in range(len(sorted_list)):
list_tru = remove_duplicates(sorted_list, sorted_list[i])
i+=1
return list_tru
but if I input remove_all(['a','a','b','b','c','c']), it outputs ['a','a','b','b','c']. What am I doing wrong?
def remove_all_duplicates(L):
# NOTE: this modifies L IN-PLACE. Tread carefully
i = 1
while i<len(L):
if L[i] == L[i-1]:
del(L[i])
continue
i += 1
Usage:
In [88]: L = ['a','a','b','b','c','c']
In [89]: remove_all_duplicates(L)
In [90]: L
Out[90]: ['a', 'b', 'c']
With every iteration, you just keep going back to the original sorted_list. I would recommend copying it and then operating on that copy:
def remove_all_duplicates(sorted_list):
list_tru = sorted_list[:] # copy it
for x in set(sorted_list): # just use a set
list_tru = remove_duplicates(list_tru, x) # remove this character from your list
return list_tru
I've also turned the sorted list into a set so that you don't try to remove duplicates of the same letter multiple times, and removed the unnecessary i counter.
Of course, if all you really want to do is remove the duplicates from a sorted list of strings and you're not attached to the algorithm you're developing, that's particularly simple:
new_list = sorted(set(old_list))
def remove_duplicates(sorted_list):
for item in sorted_list:
hits = sorted_list.count(item)
while hits > 1:
sorted_list.remove(item)
hits = sorted_list.count(item)
return sorted_list
print(remove_duplicates(["a","a", "b", "b"]))
this is the simplest method I could come up with on the spot uses .count to tell if there are duplicates returns ["a", "b"]
You can use this too:
A = ['a','a','b','c','c'] #example of input list with duplicates
value = remove_duplicates(A) #pass the list to the function
print value #prints ['a','b','c']
def remove_duplicates(A):
B = [] #empty list
for item in A:
if item in B:
pass
else:
B.append(item) #Append the list
return B
Hope that this helps. Have a nice day.

Python cycling through pairs of items while at the same time removing already checked items

Problem: I have a list of unique items and a comparison_tool to compare a certain property of item-pairs.
I want to store all items that return 1 for the comparison_tool for any other item without unnecessary comparisons.
Is there an efficient way to cycle through the list?
I have tried figuring it out with itertools.combinations(list_of_items, 2) and also failed with the example below:
def comparison_tool(a, b):
'''Checks if prop matches (this is simplified for this example
and i can't break it out of this function)
'''
if a.prop == b.prop:
return 1 # this is bad
else:
return 0
list_of_items = [...]
faulty_items = set()
for a in list_of_items:
for b in list_of_items:
if comparison_tool(a,b):
faulty_items.add(a,b)
list_of_items.remove(b)
# Here is where i go wrong. I would like to remove 'b' from list_of_items
# so that 'a' doesn't cycle through 'b' in its upcoming loops
Or am i just going about this the wrong way?
You should use list comprehension and do:
newlist = [i for i in list_of_items if i.prop=1]
It is simpler to create a new list containing good values :
list_of_items = [...]
faulty_items = set()
new_list = []
for i in list_of_items:
for j in new_list:
if comparison_tool(i, j):
faulty_items.add(i)
break
else:
new_list.append(i)
list_of_items = new_list

Categories