How can I substitute a list by index in python? - python

I need to write a function that contains 3 input parameters:
A list called randome containing random integer numbers
A list called indexes that contains (non-negative) indexes of items that need substitution by the third parameter. It is possible that indexes contains non-existent indexes for source. Check if the index actually exists in source before you substitute. Perhaps using the len of randome?
A value new_value that we use to overwrite the items in source. Assign True as default value.
For example: substitution_function([1, 2, 3, 4, 5], [0, 2], True) must return this list: [True, 2, True, 4, 5]
Anyone have any ideas?
def substitution_function(randome, indexes, new_value=True):
result = []
for data in indexes:
if data <= len(source):
result.append(new_value)
else:
for i in range(len(source)):
result.append(source[i])
return result
But this code can be greatly improved

The way you started is strange, let's start from scratch. There is 2 ways
Replace with the given value, at the given indexes
def substitution_function(source, indexes, new_value=True):
for index in indexes:
if index < len(source):
source[index] = new_value
return source
Build a whole new list, and conditionally use original value or replacement one
# that solution is safe-proof to invalid index
def substitution_function(source, indexes, new_value=True):
result = []
indexes = set(indexes) # can be added in case of large list
for i, data in enumerate(source):
if i in indexes:
result.append(new_value)
else:
result.append(data)
return result

I think it's better to you read the Stack Overflow Guidelines 😎
def overwriteArr(arr, idxs, val):
for idx in idxs:
try:
arr[idx] = val
except:
pass
return arr
print(overwriteArr([1, 2, 3, 4, 5], [0, 2], True)) # [True, 2, True, 4, 5]

It runs for loop on randome with getting item's index by enumerate(). If index is in indexes it returns new_value to listcomp's list if it's not it returns item. The possible problem of spare indexes in indexes is solved by just not touching them at all.
def substitution_function(randome, indexes, new_value=True):
return [new_value if e in indexes else i for e,i in enumerate(randome)]

Related

How to find compare two array based on the minimum length of the array python

I want to compare two array such that i have to compare two arrays based on the index position such that arr2[i] in arr1[i:]. If the lenght of the array is equal it is easy, both the arrays can have the minimum length, could you please help me how to dynamically find the minimum lenght of the array in the loop?
arr1 = [1,2,3,4,5,7,8,9]
arr2 = [4,5,6]
for i in range(min(arr1,arr2)):
if minimum_arr[i] in max_arr[i:].
---> how to dynamically solve this issue, please help.
As I can understand your problem, you better set the minimum_arr and the max_arr before the for loop. I would like to notice that the indexing of lists starts with 0, which means that the statement you gave will never be True with these lists, so I fixed the issue in the if statement (you do not need to get an nth element of the max_arr, since you want to check if the given element is in that list or not).
arr1 = [1, 2, 3, 4, 5, 7, 8, 9]
arr2 = [4, 5, 6]
minimum_arr = arr1 if len(arr1) < len(arr2) else arr2
max_arr = arr1 if len(arr1) > len(arr2) else arr2
for i in range(len(minimum_arr)):
if minimum_arr[i] in max_arr:
# ...
I would determine which list is the shorter before entering the loop. You can do this by sorting a list of the two lists by there length, using the built-in sorted setting the key argument to the len function.
Then you code would look like:
arr1 = [1,2,3,4,5,7,8,9]
arr2 = [4,5,6]
# Sort the two arrays by length
short_arr, long_arr = sorted([arr1, arr2], key=len)
for i in range(len(short_arr)):
if short_arr[i] in long_arr[i:]:
pass
You can use enumerate instead of range to get the current object and the index you're at currently as you iterate the smaller list. As for getting the smaller list you need to use the key argument and I also suggest using sorted instead of using min and max.
list1 = [1,2,3,4,5,7,8,9]
list2 = [4,5,6]
min_list, max_list = sorted([list1, list2], key=len)
for i, n in enumerate(min_list):
if n in max_list[i:]:
...

How to check if an element is an empty list in pandas?

One of the column in my df stores a list, and some of the raws have empty items in the list. For example:
[]
["X", "Y"]
[]
etc...
How can only take the raw whose list is not empty?
The following code does not work.
df[df["col"] != []] # ValueError: Lengths must match to compare
df[pd.notnull(df["col"])] # The code doesn't issue an error but the result includes an empty list
df[len(df["col"]) != 0] # KeyError: True
You can do this:
df[df["col"].str.len() != 0]
Example:
import pandas as pd
df = pd.DataFrame({"col": [[1], [2, 3], [], [4, 5, 6], []]}, dtype=object)
print(df[df["col"].str.len() != 0])
# col
# 0 [1]
# 1 [2, 3]
# 3 [4, 5, 6]
This is probably the most efficient solution.
df[df["col"].astype(bool)]
Try this:
df[df['col'].apply(len).gt(0)]
bool
An empty list in a boolean context is False. An empty list is what we call falsey. It does a programmer well to know what objects are falsey and truthy.
You can also slice a dataframe with a boolean list (not just a boolean series). And so, I'll use a comprehension to speed up the checking.
df[[bool(x) for x in df.col]]
Or with even less characters
df[[*map(bool, df.col)]]
You could check to see if the lists are empty using str.len() and then negate:
df[df["col"].str.len() != 0]
...
str.len is for the Python built-in function returning the length of an object.
And your output should be the expected one.

How can I figure out which arbitrary number occurs twice in a list of integers from input? (Python)

Say I'm receiving a list of arbitrary numbers from input, like
[1,2,3,4,5,6,7,8,8,9,10]
My code doesn't know what numbers these are going to be before it receives the list, and I want to return the number that appears twice automatically. How do I go about doing so?
Thank you.
You could do:
input = [1,2,3,4,5,6,7,8,8,9,10]
list_of_duplicates = []
for i in input:
if i not in list_of_duplicates:
list_of_duplicates.append(i)
input.pop(i)
print(input)
Now input will have all the numbers that were in the list multiple times.
You can use Counter By defualt Method in python 2 and 3
from collections import Counter
lst=[1,2,3,4,5,6,7,8,8,9,10]
items=[k for k,v in Counter(lst).items() if v==2]
print(items)
Hope this helps.
input = [1,2,3,4,5,6,7,8,8,9,10]
unique = set(input)
twice = []
for item in unique:
if input.count(item) == 2:
twice.append(item)
I've created something monstrous that does it in one line because my brain likes to think when it's time for bed I guess?
This will return a list of all duplicate values given a list of integers.
dupes = list(set(map(lambda x: x if inputList.count(x) >= 2 else None, inputList))-set([None]))
How does it work? The map() function applies a function every value of a list, in your case our input list with possible duplicates is called "inputList". It then applies a lambda function that returns the value of the integer being iterated over IF the iterated value when applied to the inputList via the .count() method is greater than or equal to two, else if it doesn't count as a duplicate it will return None. With this lambda function being applied by the map function, we get a list back that contains a bunch of None's and the actual integers detected as duplicates via the lambda function. Given that this is a list, we the use set to de-duplicate it. We then minus the set of duplicates against a static set made from a list with one item of None, stripping None values from our set of the map returned list. Finally we take the set after subtraction and convert it to a list called "dupes" for nice and easy use.
Example usage...
inputList = [1, 2, 3, 4, 4, 4, 5, 6, 6, 7, 1001, 1002, 1002, 99999, 100000, 1000001, 1000001]
dupes = list(set(map(lambda x: x if inputList.count(x) >= 2 else None, inputList))-set([None]))
print(dupes)
[1000001, 1002, 4, 6]
I'll let someone else elaborate on potential scope concerns..... or other concerns......
This will create a list of the numbers that are duplicated.
x = [1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10]
s = {}
duplicates = []
for n in x:
try:
if s[n]:
duplicates.append(n)
s[n] = False
except KeyError:
s[n] = True
print(duplicates)
Assuming the list doesn't contain 0

Restricting a Change to Only 1 List

I have nested lists (ie. [[list1],[list2]] and I want to make a change to only the first list.
My function is given as below:
function_name(data, list_number, change)
should return a change to only the list_number provided in the data
So my overall question is, how do I restrict this change to only the list_number given? If this is unclear please feel free to ask and clarify.
Ex:
Where the 'change' is already known which index it is going to replace, in this case it's going to replace the 2nd index of the first list (ie. 2)
data = [[1,2,3],[4,5,6]]
function_name(data, 1, 6)
data = [[1,6,3],[4,5,6]]
I have no idea where to even begin as the index is 'unknown' (ie. given by the user when the function is called)
List items are referenced via their index and nested lists can work the same way.
If your list were:
list = [['nest1_1', 'nest1_2']['nest2_1', 'nest2_2']]
You could change it in the following ways:
list[0] = ['nesta_1', 'nesta_2']
list[1][0] = 'second_1'
This would make your list now be:
[['nesta_1', 'nesta_2']['second_1', 'nest2_2']]
Try this code:
data = [[1,2,3],[4,5,6]]
def element_change(data, index_list, element_to_change, change):
a =''.join([ str(i) for i in data[index_list]])
data[index_list][a.find(str(element_to_change))] = change
return data
print(element_change(data, 0, 2, 6))
Input:
[[1, 2, 3], [4, 5, 6]]
Output:
[[1, 6, 3], [4, 5, 6]]
Simply what it does is casting list to string and merging them in order to be able to use find() method to find the index.

Meaning of list[-1] in Python

I have a piece of code here that is supposed to return the least common element in a list of elements, ordered by commonality:
def getSingle(arr):
from collections import Counter
c = Counter(arr)
return c.most_common()[-1] # return the least common one -> (key,amounts) tuple
arr1 = [5, 3, 4, 3, 5, 5, 3]
counter = getSingle(arr1)
print (counter[0])
My question is in the significance of the -1 in return c.most_common()[-1]. Changing this value to any other breaks the code as the least common element is no longer returned. So, what does the -1 mean in this context?
One of the neat features of Python lists is that you can index from the end of the list. You can do this by passing a negative number to []. It essentially treats len(array) as the 0th index. So, if you wanted the last element in array, you would call array[-1].
All your return c.most_common()[-1] statement does is call c.most_common and return the last value in the resulting list, which would give you the least common item in that list. Essentially, this line is equivalent to:
temp = c.most_common()
return temp[len(temp) - 1]

Categories

Resources