how do i check how what is the duplicate numbers and what their sum?
I am working on a project and I cant get it.
list = [1, 3, 5, 2, 1, 6, 5, 10, 1]
You can iterate the list and count how many times each element is met, then it's easy to check which elements are repeated (they have counter greater than 1), and the sum would be simply element_value*count
li = [1, 3, 5, 2, 1, 6, 5, 10, 1]
counters = {}
for element in li:
counters[element] = counters.get(element, 0) + 1
for element, count in counters.items():
if count >= 2:
print('Repeated element', element, 'sum=', element*count)
You can set up a separate set to check which items have already been seen, and for those where this is the case you add them to a sum:
sum = 0
li = [1, 3, 5, 2, 1, 6, 5, 10, 1]
seen_numbers = set()
for n in li:
if n not in seen_numbers:
seen_numbers.add(n)
else:
sum += n
Note that this will add a number that is already in the list each time it recurs, i.e., a number that appears three times will be added to sum twice. I don't know if that's what you want.
If you need the single results you can construct a list where each element is a tuple. Each tuple contains the number, the count and the sum.
from collections import Counter
data = [1, 3, 5, 2, 1, 6, 5, 10, 1]
result = [(value, count, value*count) for value, count in Counter(data).items() if count > 1]
print(result)
If you need to find only the full total of all values that appear more than once:
print(sum(value*count for value, count in Counter(data).items() if count > 1))
Related
I don't know how to add extra conditions to this code.
(Only using randint)
For example with list [1, 2, 3, 4, 0] I need to generate random number except the last one (covered in my code) but the next condition is, it can not choose an index number which has a value of 0. So for list [3, 3, 0, 3, 3, 7] it can only consider indexes 0,1,3,4 (not 2 and 5 because I can not include the last number and index with value 0).
My code so far:
import random
our = [2, 3, 4, 0]
random_index = random.randint(0, len(our)-2)
random_number = our[random_index]
print(random_number)
I will be very glad for any help.
You can create a second list that stores the valid index values.
import random
our = [3, 3, 0, 3, 3, 7]
index = []
for i in range(0, len(our)-1) :
if our[i] != 0 :
index.append(i)
# index: [0, 1, 3, 4]
random_index = random.choice(index)
EDIT: You can perform a sanity check for a non-zero value being present.
The any() function returns True if any element of an iterable is True. 0 is treated as False and all non-zero numbers are True.
valid_index = any(our[:-1])
if valid_index:
index = []
for i in range(0, len(our)-1) :
if our[i] != 0 :
index.append(i)
You can use a while loop to check if the number equals 0 or not.
import random
our = [3, 6, 2, 0, 3, 0, 5]
random_number = 0
while random_number == 0:
random_index = random.randint(0, len(our)-2)
random_number = our[random_index]
print(random_number)
Link to the problem: https://www.hackerrank.com/challenges/lilys-homework/forum
Summary: We have to find the minimum no. of swaps required to convert an array into sorted array. It can be sorted in ascending or descending order. So, here is the array I want to sort:
arr = [3, 4, 2, 5, 1]
We sort it in ascending order we need 4 swaps, and 2 swaps when in descending order.
For descending: -Swap 5 and 3 and then swap 3 and 2
Now, I have written a python code to solve this test case. Here is the code:
arr = [3, 4, 2, 5, 1]
arr2 = arr[:]
count = 0; count2 = 0; n = len(arr)
registry = {}
for i in range(n):
registry[arr[i]] = i
sorted_arr = sorted(arr)
#######################first for loop starts#########################
#find no. of swap required when we sort arr is in ascending order.
for i in range(n-1):
if arr[i] != sorted_arr[i]:
index = registry[sorted_arr[i]]
registry[sorted_arr[i]],registry[arr[i]]= i, index
temp = arr[i]
arr[i],arr[index]=sorted_arr[i],temp
count = count + 1
###################first for loop ends#######################
# re-initalising registry and sorted_arr for descending problem.
registry = {}
for i in range(n):
registry[arr2[i]] = i
sorted_arr = sorted(arr2)
sorted_arr.reverse()
print(arr2) #unsorted array
print(registry) #dictionary which stores the index of the array arr2
print(sorted_arr) #array in descending order.
#find no. of swap required when array is in descending order.
for i in range(n-1):
print('For iteration i = %i' %i)
if arr2[i] != sorted_arr[i]:
print('\tTrue')
index = registry[sorted_arr[i]]
registry[sorted_arr[i]],registry[arr[i]]= i, index
temp = arr2[i]
arr2[i],arr2[index]=sorted_arr[i],temp
print('\t '+ str(arr2))
count2 = count2 + 1
else:
print('\tfalse')
print('\t '+ str(arr2))
print('######Result######')
print(arr)
print(count)
print(arr2)
print(count2)
Here's the problem:
When I run the code, the second for loop i.e. the for loop for descending gives wrong value of count which is 3. But, when I comment the first for loop, i.e. the for loop for ascending it gives correct value of count which is 2.
I want to know why for loop 2 changes output when for loop 1 is present.
The output I get when loop 1 is NOT commented.
arr2: [3, 4, 2, 5, 1]
Registry: {3: 0, 4: 1, 2: 2, 5: 3, 1: 4}
sorted_arr: [5, 4, 3, 2, 1]
For iteration i = 0
True
[5, 4, 2, 3, 1]
For iteration i = 1
false
[5, 4, 2, 3, 1]
For iteration i = 2
True
[2, 4, 3, 3, 1]
For iteration i = 3
True
[2, 4, 3, 2, 1]
######Result######
[1, 2, 3, 4, 5]
4
[2, 4, 3, 2, 1]
3
The error is in your second loop, where you have:
registry[sorted_arr[i]],registry[arr[i]]= i, index
This should be:
registry[sorted_arr[i]],registry[arr2[i]]= i, index
Generally, it is a bad idea to work with such arr and arr2 variables. Instead make two functions, and pass arr as argument to the function call. The function should then make a local copy of that array ( [:]) before mutating it. All other variables should be local to the function. That way the two algorithms use their own variable scope and there is no risk of "leaking" accidently a wrong variable into the other algorithm.
I'm doing this test on testdome.com for practicing , and it's failing some test case. Can anyone help me pointing out the logic error in my code?
This is the question for my code:
"Write a function that, when passed a list and a target sum, returns, efficiently with respect to time used, two distinct zero-based indices of any two of the numbers, whose sum is equal to the target sum.
If there are no two numbers, the function should return None.
For example, find_two_sum([3, 1, 5, 7, 5, 9], 10) should return a single tuple containing any of the following pairs of indices:
0 and 3 (or 3 and 0) because addition of 3 and 7 is 10.
1 and 5 (or 5 and 1) because addition of 1 and 9 is 10.
2 and 4 (or 4 and 2) because addition of 5 and 5 is 10.
def find_two_sum(numbers, target_sum):
sss=list(dict.fromkeys(numbers))
if (sss == None or len(sss) < 2): return None
for item in sss:
tesn=target_sum-item
if tesn in sss:
if numbers.index(item)==numbers.index(tesn):
continue
else:
return numbers.index(item),numbers.index(tesn)
return None
print(find_two_sum([3, 1, 5, 7, 5, 9], 10))
They have four test cases and my code can only pass first two test cases.
Example case:Wrong answer ( to return [0,2] because 3 of index 0 + 7 of index 3 is 10)
Distinct numbers with and without solutions: Wrong answer
Duplicate numbers with and without solutions: Wrong answer
Performance test with a large list of numbers: Wrong answer
My take on the problem:
def find_two_sum(lst, n):
indices = {}
for idx, num in enumerate(lst):
indices.setdefault(num, []).append(idx)
for k, v in indices.items():
i = v.pop()
if n - k in indices and indices[n-k]:
return i, indices[n-k].pop()
print( find_two_sum([3, 1, 5, 7, 5, 9], 6) )
print( find_two_sum([3, 1, 5, 7, 5, 9], 10) )
print( find_two_sum([1, 2, 1, 8], 10) )
print( find_two_sum([5, 5], 10) )
print( find_two_sum([11], 10) )
Prints:
(1, 4)
(0, 3)
(1, 3)
(1, 0)
None
I believe you have to add a check for the two indexes to be distinct.
For example here:
print(find_two_sum([3, 1, 5, 7, 5, 9], 6))
The function will give an answer of (0, 0) which wouldn't be correct, though these are the indexes of 3, which gives a sum of 6 with itself .
Here, I've added the check for distinct indexes:
def find_two_sum(numbers, target_sum):
sss = list(dict.fromkeys(numbers))
if (sss == None or len(sss) < 2): return None
tup=()
for item in sss:
item_index = numbers.index(item)
tesn = target_sum - item
if tesn in sss:
tesn_index = numbers.index(tesn)
if item_index!=tesn_index:
return (item_index, tesn_index)
return None
One flaw in the logic is that sss does not contain duplicates that may exist in the original list - you have lost information. You are assuming there are no duplicates in the original list: list.index(n) will return the index of the first item equal to n so you can end up with a result with duplicate indices
>>> a = [3, 1, 5, 7, 5, 9]
>>> item = 5
>>> tesn = 5
>>> a.index(item),a.index(tesn)
(2, 2)
>>>
Your algorithm has a flaw e.g. find_two_sum([5, 2], 10) gives (0, 0).
This is because when you check item in sss, it's gonna evaluate to true when item is 5, there is only a single 5 in the input list.
This answer seems to be 50% correct.
def find_two_sum(numbers, target_sum):
for n in numbers:
for i in numbers[numbers.index(n)+1:]:
if n+i==target_sum:
return(numbers.index(n),numbers.index(i))
break
return None
print(find_two_sum([3, 1, 5, 7, 5, 9], 10))
If I have two numpy arrays of the same size.
ArrayOne = np.array([ 2, 5, 5, 6, 7, 10, 13])
ArrayTwo = np.array([ 8, 10, 12, 14, 16, 18, 24])
How can I count how many elements there are until the beginning of the array. Unless the condition ArrayOne >= ArrayTwo is satisfied. In which case how many elements until that condition. Then make an array out of the result.
So as an example for element [0] there are 0 elements in front. For element [1] there is 1 element in front, and ArrayOne >= ArrayTwo wasn't satisfied. At element [5] in ArrayOne is bigger than element[0] in ArrayTwo so there are four elements until element [1] in ArrayTwo Etc.
Giving the result
result = np.array([ 0, 1, 2, 3, 4, 4, 3])
Thanks in advance.
Basically, at index i you have the value
value = i -count(how often element i in array one was bigger than array two until index i)
Because I'm on mobile with damn autocorrect, I rename the two arrays to a and b.
def get_value(a, b, i):
max_value = a[i]
nb_smaller_elements = sum(1 for el in range(i) if b[el] < max_value)
return i - nb_smaller_elements
I think I got it. Using #Paul Panzer 's answer, I made a for loop that goes through the list.
def toggle(ArrayOne,ArrayTwo):
a = 0
sum = -1
linels = []
for i in range(len(ArrayOne)):
sum += 1
a = sum - np.searchsorted(ArrayTwo, ArrayOne[i])
linels.append(a)
return np.array(linels)
I get the result
linels = np.array([ 0, 1, 2, 3, 4, 4, 3])
I hope anyone can help me with the following. I have a list called: 'List'. And I have a list called X.
Now I would like to check whether the value in the third column of each row in List is smaller than (<) X or equal/bigger than X. If the value is smaller I would like to add a 0 to the 6th column and a 1 if it is equal/bigger. And for each X I would like the answers to be added to the upfollowing columns to List. So in this case there are 4 X values. So as a result 4 columns should be added to List. My code below probably shows I'm quite an amature and I hope you can help me out. Thank you in advance.
List = [(3,5,6,7,6),(3,5,3,2,6),(3,6,1,0,5)]
X= [1,4,5,6]
for item in X:
for number in row[3] for row in List:
count = 0
if number < item:
List[5+count].append(0)
count += 1
return List
else:
List[5+count].append(1)
count += 1
return List
return List
First, you should know that tuples (parenthesis enclosed lists) are immutable, so you can not change anything about them once they're defined. It's better to use a list in your case (enclosed by []).
List = [[3,5,6,7,6],[3,5,3,2,6],[3,6,1,0,5]]
X= [1,4,5,6]
for item in X: # loop on elements of X
for subList in List: # loop on 'rows' in List
if subList[2] < item: # test if 3rd element is smaller than item in X
subList.append(0); # push 0 to the end of the row
else:
subList.append(1); # push 1 to the end of the row
List = [(3,5,6,7,6),(3,5,3,2,6),(3,6,1,0,5)]
X= [1,4,5,6]
scores = []
for item in List:
scores.append(tuple(map(lambda x: 0 if item[2] < x else 1, X)))
result = []
for item, score in zip(List, scores):
result.append(item + score)
print(result)
# [(3, 5, 6, 7, 6, 1, 1, 1, 1), (3, 5, 3, 2, 6, 1, 0, 0, 0), (3, 6, 1, 0, 5, 1, 0, 0, 0)]
Your indentation is off (you should unindent everything starting with your for statement.
You can't append to tuples (your rows inside the List variable are actually tuples).
Since you are not in a function, return does not do anything.
Since indices start with 0, you should use row[2] for 3rd row.
There are more elements in your X than the number of rows in List.
That being said, you can also use list comprehensions to implement this. Here is a one-liner that does the same thing:
>>> List = [(3,5,6,7,6),(3,5,3,2,6),(3,6,1,0,5)]
>>> X = [1,4,5,6]
>>> print [tuple(list(t[0])+[0]) if t[0][2] < t[1] else tuple(list(t[0]) + [1]) for t in zip(List, X)]
will print
[(3, 5, 6, 7, 6, 1), (3, 5, 3, 2, 6, 0), (3, 6, 1, 0, 5, 0)]
List = [[3,5,6,7,6],[3,5,3,2,6],[3,6,1,0,5]]
X= [1,4,5,6]
elems = [row[3] for row in List]
for i in range(len(elems)):
for x in X:
if elems[i] < x:
List[i].append(0)
else:
List[i].append(1)
print List
And you cannot use return if you are not using functions.
return needs to be called from inside a function. It exits the function and the value specified by return is given back to the function.
So you can't use it in your program.
In the list, each row is actually known as a tuple. Tuples don't have the append function so you can't use that to add to the end of a row.
Also, you can't have two for loops in a single line. (Which is not a problem since we only need one to achieve your output)
I've modified your code so that it looks similar so it's easier for you to understand.
List = [(3,5,6,7,6),(3,5,3,2,6),(3,6,1,0,5)]
X= [1,4,5,6]
for item in X:
n = 0
for row in list:
if row[3] < item:
list[n] = list[n] + (0,)
else:
list[n] = list[n] + (1,)
n = n+1
print List
You need to add with (0,) or (1,) to show that it's a tuple addition. (Or else python will think that you're adding a tuple with an integer)
agree with Selcuk
[edited #1: Thanks #Rawing, I mistyped > as <]
Here is AlmostGr's version simplified:-
List = [[3, 5, 6, 7, 6], [3, 5, 3, 2, 6], [3, 6, 1, 0, 5]]
X = [1, 4, 5, 6]
for num in X:
for item in List:
if num > item[2]:
item.append(0)
else:
item.append(1)
it runs for all elements in X and produces the output:
[[3, 5, 6, 7, 6, 1, 1, 1, 1], [3, 5, 3, 2, 6, 1, 0, 0, 0], [3, 6, 1, 0, 5, 1, 0, 0, 0]]