lst=[5,6,7,8,9]
v=10
for item in lst:
if item<v:
lst.insert(0,v)
print(lst)
i want to insert 10, at the index 0 if all the elements in the list are under 10, im not tryning to insert 10 each time
so it should look like this : [10,5,6,7,8,9]
You are inserting the same value of v at the beginning of the original list based on how many of the original values are less than v. In this case, preservation of insertion order is moot.
All inserted values are the same and are prepended to an original list that doesn't change.
So why not use something this
lst = [5, 6, 7, 8, 9]
v = 10
count = 0
for item in lst:
if item < v:
count += 1
new_lst = [v] * count + lst
print(new_lst)
Result
>>> [10, 10, 10, 10, 10, 5, 6, 7, 8, 9]
Edit: Updating answer based on further clarification
i want to insert 10, at the index 0 if all the elements in the
list are under 10, im not tryning to insert 10 each time
lst = [5, 6, 7, 8, 9]
v = 10
for item in lst[:]:
if item < v:
lst.insert(0, v)
break
print(lst)
Result
>>> [10, 5, 6, 7, 8, 9]
The updated code will insert v at index 0 only once if a single item is less than v. When the item < v condition is met the for loop ends without checking any of the remaining items. Otherwise, if None of the values are less than v, you will traverse the entirety of your list without making any changes.
Notice that I used the insert method here since this code will shift all of your lst items only once.
Related
I have a list in the python and I want to find out the search term with conditions one smaller and one bigger number the search term.
list = [2, 3, 5, 7, 9, 12, 19, 22, 34]
search_term = 10
I want to get one smaller and one bigger term next to the search term from the list.
The expected result should be
output = [7, 9]
Edit for [7, 9]
Search up until you are >= search_term, then print last 2 values:
# Don't use class names (list) as variables
lst = [2, 3, 5, 7, 9, 12, 19, 22, 34]
search_term = 10
# Sort list for iterating. lst is now sorted
lst.sort()
index = 0
# Get index of values. Stop when item >= search_term
for i, item in enumerate(lst[1:]):
if item >= search_term:
index = i
break
output = [lst[index-1], lst[index]]
>>> output
[7, 9]
This was for printing value before and after search_term
There was no output, and this was a guess at what OP wanted
You can iterate over your lst and check for > and < search_term:
This works for non-empty lists
# Don't use class names (list) as variables
lst = [2, 3, 5, 7, 9, 12, 19, 22, 34]
search_term = 10
# Sort
lst.sort()
last = lst[0]
index = 0
# Get item before
for i, item in enumerate(lst[1:]):
if item < search_term:
last = item
index = i
else:
break
print(f'Before = {last}')
# Get item after
try:
for item in lst[index+1:]:
if item >= search_term:
last = item
break
except IndexError:
pass
# You don't have any values after the before value
print(f'After = {last}')
Before = 9
After = 12
An exception may be the case of:
>>> lst = [1, 10]
>>> search_term = 10
Which prints
Before = 1
After = 10
Code:
l = [2, 3, 5, 7, 9, 12, 19, 22, 34]
search_term = 10
tmp = [max([t for t in l if t <= search_term])] # smaller than search
tmp.append(min([t for t in l if t >= search_term])) #bigger than search
print("nearest smaller :",tmp[0])
print("nearest bigger :",tmp[1])
Output:
nearest smaller : 9
nearest bigger : 12
I have a list of n numbers. I want to group them in g groups. Also, I want to reverse elements in every odd group. Finally, I would combine all elements in even and odd groups into a new sublist. First I am giving what answer I am expecting and where I went wrong:
Expected answer:
num = 14
grp = 4
# A list of num natural numbers arranged in group (row) of 4 numbers
lst =
[0,1,2,3,
4,5,6,7,
8,9,10,11,
12,13]
lst =
[[0,1,2,3],
[4,5,6,7],
[8,9,10,11],
[12,13]]
# Reverse elements in odd rows
newlst =
[[0,1,2,3],
[7,6,5,4], # reversed here
[8,9,10,11],
[13,12]] # reversed here
# combine elements in all sublists by their position
# combine first element in all sublists into a new sublist
sollst =
[[0,7,8,13],[1,6,9,12],[2,5,10],[3,4,11]]
My solution:
num = 14
grp = 4
#### print
lst= list(range(0,num,1))
newlst= [lst[i:i+grp:1] for i in range(0,num,grp)]
evnlst = newlst[0::2]
oddlst = newlst[1::2]
newoddlst = [oddlst [i][::-1] for i in range(len(oddlst))]
sollst= evnlst + newoddlst
# This gives [[0, 1, 2, 3], [8, 9, 10, 11], [7, 6, 5, 4], [13, 12]]
from itertools import zip_longest
print([[x for x in t if x is not None] for t in zip_longest(fevngps)])
Present answer:
I reached the one step before the final answer and now I have to combine the lists of different lengths and I am running into an error
TypeError: 'int' object is not subscriptable
One approach:
from itertools import zip_longest
num = 14
grp = 4
lst = list(range(0, num, 1))
newlst = [lst[i:i + grp:1] for i in range(0, num, grp)]
# build new list where the sub-list are reversed if in odd indices
revlst = [lst[::-1] if i % 2 == 1 else lst for i, lst in enumerate(newlst)]
# zip using zip_longest and filter out the None values (the default fill value of zip_longest)
result = [[v for v in vs if v is not None] for vs in zip_longest(*revlst)]
print(result)
Output
[[0, 7, 8, 13], [1, 6, 9, 12], [2, 5, 10], [3, 4, 11]]
Given an arbitrary number of lists of integers of arbitrary length, I would like to group the integers into new lists based on a given distance threshold.
Input:
l1 = [1, 3]
l2 = [2, 4, 6, 10]
l3 = [12, 13, 15]
threshold = 2
Output:
[1, 2, 3, 4, 6] # group 1
[10, 12, 13, 15] # group 2
The elements of the groups act as a growing chain so first we have
abs(l1[0] - l2[0]) < threshold #true
so l1[0] and l2[0] are in group 1, and then the next check could be
abs(group[-1] - l1[1]) < threshold #true
so now l1[1] is added to group 1
Is there a clever way to do this without first grouping l1 and l2 and then grouping l3 with that output?
Based on the way that you asked the question, it sounds like you just want a basic python solution for utility, so I'll give you a simple solution.
Instead of treating the lists as all separate entities, it's easiest to just utilize a big cluster of non-duplicate numbers. You can exploit the set property of only containing unique values to go ahead and cluster all of the lists together:
# Throws all contents of lists into a set, converts it back to list, and sorts
elems = sorted(list({*l1, *l2, *l3}))
# elems = [1, 2, 3, 4, 6, 10, 12, 13, 15]
If you had a list of lists that you wanted to perform this on:
lists = [l1, l2, l3]
elems = []
[elems.extend(l) for l in lists]
elems = sorted(list(set(elems)))
# elems = [1, 2, 3, 4, 6, 10, 12, 13, 15]
If you want to keep duplicated:
elems = sorted([*l1, *l2, *l3])
# and respectively
elems = sorted(elems)
From there, you can just do the separation iteratively. Specifically:
Go through the elements one-by-one. If the next element is validly spaced, add it to the list you're building on.
When an invalidly-spaced element is encountered, create a new list containing that element, and start appending to the new list instead.
This can be done as follows (note, -1'th index refers to last element):
out = [[elems[0]]]
thresh = 2
for el in elems[1:]:
if el - out[-1][-1] <= thresh:
out[-1].append(el)
else:
out.append([el])
# out = [[1, 2, 3, 4, 6], [10, 12, 13, 15]]
In my code, returns the position of the smallest element in the list by use index() function, when I run the code, it run nothing. Please help me to figure out problem. Here is what I coded:
def get_index_of_smallest(numbers):
smallest_index = []
for element in range (len(numbers)):
element = numbers.index(min(numbers))
smallest_index = element + 1
return smallest_index
def test_get_index_of_smallest():
list1 = [23, 3, 6, 5, 12, 9, 7, 4]
print(get_index_of_smallest(list1))
Many thanks.
You can use min(list) and builtin function of list(list.index())
list1 = [23, 3, 6, 5, 12, 9, 7, 4]
min_num = min(list1)
index = list1.index(min_num)
One way, it's possible using min, emumerate and lambda
myList = [23, 3, 6, 5, 12, 9, 7, 4]
min(enumerate(myList), key=lambda x:x[1])[0]
#1
Your code looks good, but you forgot to call the function. Add test_get_index_of_smallest(), and it will work!
Input:
def get_index_of_smallest(numbers):
smallest_index = []
for element in range (len(numbers)):
element = numbers.index(min(numbers))
smallest_index = element + 1
return smallest_index
def test_get_index_of_smallest():
list1 = [23, 3, 6, 5, 12, 9, 7, 4]
print(get_index_of_smallest(list1))
test_get_index_of_smallest()
Output:
2
Edit:
You can further cut down your code. Here is a code that does the same thing:
Input:
def get_index_of_smallest(numbers):
return numbers.index(min(numbers))+1
print(get_index_of_smallest([23, 3, 6, 5, 12, 9, 7, 4]))
Output:
2
We can use list comprehension and enumerate here
min_idx = [idx for idx, item in enumerate(list1) if item == min(list1)]
[1]
Here is a expanded version of what is going on here
for idx, item in enumerate(list1):
if item == min(list1):
min_idx = idx
When we enumerate in it iterates for the index and item so what we can do is check each item v min(list1) if we get a match we can set our min_idx variable to the corresponding index of that item, cheers !
I am trying to solve an issue that I am currently running into. I want to have to have a list that is made up of only random integers. Then if i find a duplicate integer within this list i want to minus the rest of the list by one, after the second time the duplicate number appeared. Furthermore if a second pair of duplicate numbers are encountered, it should then minus the rest of the list by two, than if a third by three and etc.
But it should not affect the same duplicate number or any other duplicated number (that differs from the first) that is in the sequence.
For example
mylist = [0 1 2 3 4 5 6 2 8 5 10 11 12 1 14 15 16 17]
I want the end result to look like;
mylist = [0 1 2 3 4 5 6 2 7 5 9 10 11 1 12 13 14 15]
I have some rough code that I created to attempt this, but it will always minus the whole list including duplicated integers (the first pairs and any further pairs).
If someone can shed some light on how to deal with this problem i will be highly grateful!
Sorry forgot to add my code
a = [49, 51, 53, 56, 49, 54, 53, 48]
dupes = list()
number = 1
print (dupes)
while True:
#move integers from a to dupes (one by one)
for i in a[:]:
if i >= 2:
dupes.append(i)
a.remove(i)
if dupes in a:
a = [x - number for x in a]
print (dupes)
print(dupes)
if dupes in a:
a = [x - number for x in a]
number = number+1
break
Forgot to mention earlier, me and friend are currently working on this problem and the code i supplied is our rough outline of what is should look like and now the end result, I know that it does now work so i decided to ask for help for the issue
You need to iterate through your list and when you encounter a duplicate(can use list slicing) then decrement the next item!
List slicing - example,
>>> L=[2,4,6,8,10]
>>> L[1:5] # all elements from index 1 to 5
[4, 6, 8, 10]
>>> L[3:] # all elements from index 3 till the end of list
[8, 10]
>>> L[:2] # all elements from index beginning of list to second element
[2, 4]
>>> L[:-2] # all elements from index beginning of list to last second element
[2, 4, 6]
>>> L[::-1] # reverse the list
[10, 8, 6, 4, 2]
And enumerate
returns a tuple containing a count (from start which defaults to 0)
and the values obtained from iterating over sequence
Therefore,
mylist=[0, 1, 2, 3, 4, 5, 6, 2, 8, 5, 10, 11, 12, 1, 14, 15, 16, 17]
dup=0
for index,i in enumerate(mylist):
if i in mylist[:index]:
dup+=1
else:
mylist[index]-=dup
print mylist
Output:
[0, 1, 2, 3, 4, 5, 6, 2, 7, 5, 8, 9, 10, 1, 11, 12, 13, 14]