How to see if the list contains consecutive numbers - python

I want to test if a list contains consecutive integers and no repetition of numbers.
For example, if I have
l = [1, 3, 5, 2, 4, 6]
It should return True.
How should I check if the list contains up to n consecutive numbers without modifying the original list?
I thought about copying the list and removing each number that appears in the original list and if the list is empty then it will return True.
Is there a better way to do this?

For the whole list, it should just be as simple as
sorted(l) == list(range(min(l), max(l)+1))
This preserves the original list, but making a copy (and then sorting) may be expensive if your list is particularly long.
Note that in Python 2 you could simply use the below because range returned a list object. In 3.x and higher the function has been changed to return a range object, so an explicit conversion to list is needed before comparing to sorted(l)
sorted(l) == range(min(l), max(l)+1))
To check if n entries are consecutive and non-repeating, it gets a little more complicated:
def check(n, l):
subs = [l[i:i+n] for i in range(len(l)) if len(l[i:i+n]) == n]
return any([(sorted(sub) in range(min(l), max(l)+1)) for sub in subs])

The first code removes duplicates but keeps order:
from itertools import groupby, count
l = [1,2,4,5,2,1,5,6,5,3,5,5]
def remove_duplicates(values):
output = []
seen = set()
for value in values:
if value not in seen:
output.append(value)
seen.add(value)
return output
l = remove_duplicates(l) # output = [1, 2, 4, 5, 6, 3]
The next set is to identify which ones are in order, taken from here:
def as_range(iterable):
l = list(iterable)
if len(l) > 1:
return '{0}-{1}'.format(l[0], l[-1])
else:
return '{0}'.format(l[0])
l = ','.join(as_range(g) for _, g in groupby(l, key=lambda n, c=count(): n-next(c)))
l outputs as: 1-2,4-6,3
You can customize the functions depending on your output.

We can use known mathematics formula for checking consecutiveness,
Assuming min number always start from 1
sum of consecutive n numbers 1...n = n * (n+1) /2
def check_is_consecutive(l):
maximum = max(l)
if sum(l) == maximum * (maximum+1) /2 :
return True
return False

Once you verify that the list has no duplicates, just compute the sum of the integers between min(l) and max(l):
def check(l):
total = 0
minimum = float('+inf')
maximum = float('-inf')
seen = set()
for n in l:
if n in seen:
return False
seen.add(n)
if n < minimum:
minimum = n
if n > maximum:
maximum = n
total += n
if 2 * total != maximum * (maximum + 1) - minimum * (minimum - 1):
return False
return True

import numpy as np
import pandas as pd
(sum(np.diff(sorted(l)) == 1) >= n) & (all(pd.Series(l).value_counts() == 1))
We test both conditions, first by finding the iterative difference of the sorted list np.diff(sorted(l)) we can test if there are n consecutive integers. Lastly, we test if the value_counts() are all 1, indicating no repeats.

I split your query into two parts part A "list contains up to n consecutive numbers" this is the first line if len(l) != len(set(l)):
And part b, splits the list into possible shorter lists and checks if they are consecutive.
def example (l, n):
if len(l) != len(set(l)): # part a
return False
for i in range(0, len(l)-n+1): # part b
if l[i:i+3] == sorted(l[i:i+3]):
return True
return False
l = [1, 3, 5, 2, 4, 6]
print example(l, 3)

def solution(A):
counter = [0]*len(A)
limit = len(A)
for element in A:
if not 1 <= element <= limit:
return False
else:
if counter[element-1] != 0:
return False
else:
counter[element-1] = 1
return True

The input to this function is your list.This function returns False if the numbers are repeated.
The below code works even if the list does not start with 1.
def check_is_consecutive(l):
"""
sorts the list and
checks if the elements in the list are consecutive
This function does not handle any exceptions.
returns true if the list contains consecutive numbers, else False
"""
l = list(filter(None,l))
l = sorted(l)
if len(l) > 1:
maximum = l[-1]
minimum = l[0] - 1
if minimum == 0:
if sum(l) == (maximum * (maximum+1) /2):
return True
else:
return False
else:
if sum(l) == (maximum * (maximum+1) /2) - (minimum * (minimum+1) /2) :
return True
else:
return False
else:
return True

1.
l.sort()
2.
for i in range(0,len(l)-1)))
print(all((l[i+1]-l[i]==1)

list must be sorted!
lst = [9,10,11,12,13,14,15,16]
final = True if len( [ True for x in lst[:-1] for y in lst[1:] if x + 1 == y ] ) == len(lst[1:]) else False
i don't know how efficient this is but it should do the trick.

With sorting
In Python 3, I use this simple solution:
def check(lst):
lst = sorted(lst)
if lst:
return lst == list(range(lst[0], lst[-1] + 1))
else:
return True
Note that, after sorting the list, its minimum and maximum come for free as the first (lst[0]) and the last (lst[-1]) elements.
I'm returning True in case the argument is empty, but this decision is arbitrary. Choose whatever fits best your use case.
In this solution, we first sort the argument and then compare it with another list that we know that is consecutive and has no repetitions.
Without sorting
In one of the answers, the OP commented asking if it would be possible to do the same without sorting the list. This is interesting, and this is my solution:
def check(lst):
if lst:
r = range(min(lst), max(lst) + 1) # *r* is our reference
return (
len(lst) == len(r)
and all(map(lst.__contains__, r))
# alternative: all(x in lst for x in r)
# test if every element of the reference *r* is in *lst*
)
else:
return True
In this solution, we build a reference range r that is a consecutive (and thus non-repeating) sequence of ints. With this, our test is simple: first we check that lst has the correct number of elements (not more, which would indicate repetitions, nor less, which indicates gaps) by comparing it with the reference. Then we check that every element in our reference is also in lst (this is what all(map(lst.__contains__, r)) is doing: it iterates over r and tests if all of its elements are in lts).

l = [1, 3, 5, 2, 4, 6]
from itertools import chain
def check_if_consecutive_and_no_duplicates(my_list=None):
return all(
list(
chain.from_iterable(
[
[a + 1 in sorted(my_list) for a in sorted(my_list)[:-1]],
[sorted(my_list)[-2] + 1 in my_list],
[len(my_list) == len(set(my_list))],
]
)
)
)
Add 1 to any number in the list except for the last number(6) and check if the result is in the list. For the last number (6) which is the greatest one, pick the number before it(5) and add 1 and check if the result(6) is in the list.

Here is a really short easy solution without having to use any imports:
range = range(10)
L = [1,3,5,2,4,6]
L = sorted(L, key = lambda L:L)
range[(L[0]):(len(L)+L[0])] == L
>>True
This works for numerical lists of any length and detects duplicates.
Basically, you are creating a range your list could potentially be in, editing that range to match your list's criteria (length, starting value) and making a snapshot comparison. I came up with this for a card game I am coding where I need to detect straights/runs in a hand and it seems to work pretty well.

Related

Sum of random list numbers after 1st negative number

import random
def mainlist(list, size, min, max):
for i in range(size):
list.append(random.randint(min, max))
print(list)
def counterlist(list):
for i in list:
if i<0:
x=sum(list[(list.index(i)+1):])
print('Reqemlerin cemi:', x)
break
list = []
mainlist(list, 10, -10, 30)
counterlist(list)
I need to calculate sum of numbers after 1st negative number in this random list, did it in second function but want to know is there way not using the sum() function?
Explicitly using an iterator makes it nicer and more efficient:
def counterlist(lst):
it = iter(lst)
for i in it:
if i < 0:
print('Reqemlerin cemi:', sum(it))
No idea why you wouldn't want to use the sum function, that's absolutely the right and best way to do it.
Try this:
import random
lst = [random.randint(-10, 30) for _ in range(10)]
print(sum(lst[next(i for i, n in enumerate(lst) if n < 0) + 1:]))
First you generate the list lst. Then, you iterate over your list and you find the first negative element with next(i for i, n in enumerate(lst) if n < 0). Finally, you compute the sum of the portion of the list you're interested about.
If you really don't want to use sum but keep things concise (and you're using python >= 3.8):
import random
lst = [random.randint(-10, 30) for _ in range(10)]
s = 0
print([s := s + x for x in lst[next(i for i, n in enumerate(lst) if n < 0) + 1:]][-1])
Assuming there's a negative value in the list, and with a test list "a":
a = [1,2,3,-7,2,3,4,-1,23,3]
sum(a[(a.index([i for i in a if i < 0][0]) + 1):])
Evaluates to 34 as expected. Could also add a try/except IndexError with a simple sum to catch if there's no negative value.
Edit: updated the index for the search.
Yes, you can iterate over the elements of the list and keep adding them to some var which would store your result. But what for? sum approach is much more clear and python-ish.
Also, don't use list as a list name, it's a reserved word.
# After you find a first negative number (at i position)
j = i + 1
elements_sum = 0
while j < len(list):
elements_sum += list[j]
j += 1
Not as good as the marked answer, but just to know how to make use of numpy, being sure there is a negative number in the list.
Sample list: lst = [12, 2, -3, 4, 5, 10, 100]
You can get your result using np.cumsum:
import numpy as np
np_lst = np.array(lst)
cum_sum = np.cumsum(np_lst)
res = cum_sum[-1] - cum_sum[np_lst<0][0]
res #=> 119
First of all don't use list as a variable name, it's a reserved keyword. Secondly, make your loop as follows:
for index, x in enumerate(list_):
if x < 0:
sum_ = sum(list_[(index + 1):])
print('Reqemlerin cemi:', sum_)
break
That way, you don't need to find a value.
At last if you don't want to use sum
found_negative = false
sum_ = 0
for x in list_:
if found_negative:
sum_ += x
elif x < 0:
found_negative = true
print('Reqemlerin cemi:', sum_)

How to get a symmetrical sub list and then get the sum of that sub list?

What the code does: Takes a Python list of integers as input and searches for a 'symmetrical' inner-portion of the list then it takes that inner portion and gets the sum of it.
Symmetry occurs if the value of the ith element from the start of the list is equal to the value of the ith element from the end of the list.
Examples of what i want:
symmetrical_sum([10,11,12,11,12]) == ([11, 12, 11], 34)
symmetrical_sum([9,99,88,8,77,7,77,8,88,10,100]) == ([88, 8, 77, 7, 77, 8, 88], 353)
symmetrical_sum([10,8,7,5,9,8,15]) == ([8, 7, 5, 9, 8], 37)
Is there any short-coded solution to get the outputs in the examples given above? I have a correct coded version but it is more than 30 lines of code and would like to know if there is shorter way.
def symmetrical_sum(a):
dup=[x for n, x in enumerate(a) if x in a[:n]] #to get the duplicate
to_int = int(''.join(map(str,dup))) #change duplicate into int
dup1_index=a.index(to_int) #index the first duplicate
dup2_index=a.index(to_int,dup1_index+1) #index the second duplicate
portion=a[dup1_index:dup2_index+1] #get the symetric portion
total = sum(portion) #sum the elements in portion
tuple1 = (portion,total) #create tuple
return tuple1
You can do this with a recursive function as follows:
def sym(L):
if L[0] == L[-1]:
lis, sum_list = L, sum(L)
answer = f'inner-portion: {lis}, sum: {sum_list}'
return answer
else:
return sym(L[1:-1])
Note that the above will work for a list input with odd number items (that is the length is an odd number)and a single item list but not an empty list. A more wholistic approach is the following:
def symmetrical_sum(a):
index_from_start = 0
index_from_end= len(a)-1
sym_list= []
while index_from_start<=index_from_end:
if a[index_from_start] == a[index_from_end]:
sym_list= a[index_from_start:index_from_end+1]
break
else:
index_from_start += 1
index_from_end -= 1
return sym_list, sum(sym_list)
QED :)
Try using numpy:
get a list of booleans representing the condition if ith element from beginning and end are equal
find indices where the boolean values are True
The min value represent where symmetry starts and max value is where it ends, so slice the list array to get the "symmetrical" sub-list
return the new list and its sum as a tuple
Following code should work for the input and output you posted:
import numpy as np
def sym_sum(arr):
l = len(arr)-1
bool_arr = np.array([x==arr[l-i] for i,x in enumerate(arr)])
idx_arr = np.where(bool_arr==True)[0]
if len(idx_arr):
res = arr[min(idx_arr):max(idx_arr)+1]
else:
res = []
return (res, sum(res))
If you need actual symmetrical output use:
import numpy as np
def get_sym(arr):
l = len(arr) - 1
bool_arr = np.array([x == arr[l - i] for i, x in enumerate(arr)])
idx_arr = np.where(bool_arr == False)[0]
if len(idx_arr):
return get_sym(arr[min(idx_arr)+1:max(idx_arr)])
else:
return (arr, sum(arr))
Here we recursively call the function until the unsymmetrical portions are completely striped.
In pure python this can be achieved like this:
def symmetrical_sum(a):
inner_portion = []
sum = 0;
start = 0;
for i in a:
end = len(a) - (start + 1);
if a[start] == a[end]:
inner_portion = a[start:(end+1)];
for i in inner_portion:
sum+= i
break
start+= 1
return (inner_portion, sum)
print(symmetrical_sum([10,11,12,11,12])) #([11, 12, 11], 34)
Mid = float(len(a))/2
my_list =a[int(Mid - .5): int(Mid + .5)]
my_list_total =sum(my_list)
get_total= (my_list,my_list_total)
answer return get_total ([5], 5)

Python Subset Sum Problem for Given Length of Elements

For given set, and sum, and length of elements,
I want to get the boolean value whether the set satisfy the condition
For example...
Input : set = [18,0,2,20], sum = 20, length = 2 <br>
Output : True (subset [18,2] satisfy the sum=20 for given length 2)
Input : set = [18,0,2,20], sum = 22, length = 1 <br>
Output : False
How can I solve the problem if there is a given length constraint?
(I can solve it easily if there is no length condition:
subset-sum-problem)
def isSubsetSum(set, n, sum):
if sum == 0:
return True
if (sum != 0) and (n == 0):
return False
if (set[n-1] > sum):
return isSubsetSum(set,n-1,sum)
# (a) including the last element
# (b) excluding the last element
# Not "AND", But "OR" !!!!!
return isSubsetSum(set,n-1,sum) or isSubsetSum(set,n-1,sum-set[n-1])
If you're allowed to use imported modules, itertools has a combinations function that can make this quite easy:
from itertools import combinations
set = [18,0,2,20]
total = 20
length = 2
result = [ c for c in combinations(set,length) if sum(c) == total ]
if result:
print("True, subset ",result[0],"satisfies the sum", total, "given length",length)
else:
print("False")
If you need it to be a recursive function, consider that for each element X in the set, if you can find a subset of N-1 elements in the subsequent elements that total sum-X, you have a solution for sum/length=N.
For example:
def subSum(numbers,total,length):
if len(numbers) < length or length < 1:
return []
for index,number in enumerate(numbers):
if length == 1 and number == total:
return [number]
subset = subSum(numbers[index+1:],total-number,length-1)
if subset:
return [number] + subset
return []
Use itertools.combinations:
from itertools import combinations
inp = [18,0,2,20]
length = 2
sum_ = 20
def isSubsetSum(data, length, sum_):
data = [i[0]+i[1] for i in combinations(data,length)]
if sum_ in data:
return True
return False
print(isSubsetSum(inp,length, sum_))

maximum sum of a list

I am quite new to python. Just out of curiosity is there a simpler approach to find maximum sum of a list that includes both negative and positive integers?
for ex:
IN_1
l = [1,2,3]
OUT
6
IN_2
l = [1,-2,-3]
OUT
1
IN_3
l = [-1,-2,-3]
OUT
-1
If it was the case where IN_3 would return 0, then the approach was quite simple. Just removing all the negative elements and using sum.
l = [item for item in l if item >= 0]
sum(l)
The code worked pretty well for IN_1 and IN_2.
But I am having trouble in 3rd case IN_3 where it would necessarily take a number that is least negative and return it.
Try this:
l = input('').split()
s = sum([int(i) for i in l if int(i)>0]) or int(max(l, key=int))
You already outlined the approach so the implementation is simply:
def max_sum(l):
return sum(i for i in l if i > 0) or max(l)
print(max_sum([1,2,3]))
print(max_sum([1,-2,-3]))
print(max_sum([-1,-2,-3]))
This outputs:
6
1
-1
def getsum(l):
return sum({False:[max(l)]}.get(bool([i for i in l if i >0]),[i for i in l if i >0]))
print(getsum([1,2,3]))
print(getsum([1,-2,-3]))
print(getsum([-1,-2,-3]))
Output:
6
1
-1
l = [-1,-2,-3]
s = sum([i for i in l if i > 0])
s = s if s > 0 else max(l)
print(s)
It seems that you only have two cases to worry about:
The list contains only negative integers, i.e.
if max(list) < 0:
return max(list)
Some positive integers and potentially some negative integers (or none), i.e.
if max(list) > 0:
filter out negatives and return the sum of what is left
I have done from very basic and simple coding
My Answer as Follows:
l = [1,2,3]
m = [1,-2,-3]
j = [-1,-2,-3]
i = 0
for k in m:
i+=k
print(i)
I checked for all lists.

most efficient way to find a sum of two numbers

I am looking into a problem: given an arbitrary list, in this case it is [9,15,1,4,2,3,6], find any two numbers that would sum to a given result (in this case 10). What would be the most efficient way to do this? My solution is n2 in terms of big O notation and even though I have filtered and sorted the numbers I am sure there is a way to do this more efficiently. Thanks in advance
myList = [9,15,1,4,2,3,6]
myList.sort()
result = 10
myList = filter(lambda x:x < result,myList)
total = 0
for i in myList:
total = total + 1
for j in myList[total:]:
if i + j == result:
print i,j
break
O(n log n) solution
Sort your list. For each number x, binary search for S - x in the list.
O(n) solution
For each number x, see if you have S - x in a hash table. Add x to the hash table.
Note that, if your numbers are really small, the hash table can be a simple array where h[i] = true if i exists in the hash table and false otherwise.
Use a dictionary for this and for each item in list look for total_required - item in the dictionary. I have used collections.Counter here because a set can fail if total_required - item is equal to the current item from the list. Overall complexity is O(N):
>>> from collections import Counter
>>> def find_nums(total, seq):
c = Counter(seq)
for x in seq:
rem = total - x
if rem in c:
if rem == x and c[rem] > 1:
return x, rem
elif rem != x:
return x, rem
...
>>> find_nums(2, [1, 1])
(1, 1)
>>> find_nums(2, [1])
>>> find_nums(24, [9,15,1,4,2,3,6])
(9, 15)
>>> find_nums(9, [9,15,1,4,2,3,6])
(3, 6)
I think, this solution would work....
list = [9,15,1,4,2,3,6]
result = 10
list.sort()
list = filter(lambda x:x < result,list)
myMap = {}
for i in list:
if i in myMap:
print myMap[i], i
break
myMap[result - i] = i

Categories