Reversing array without reverse function but loop isn't working - python
So I am trying to reverse an array from a .txt file without using the reverse function. here is what I have.
numbers = read() #creates numbers array out of the txt file
numbersrev = numbers #blank array for reverse
numLength = len(numbers) #measures the length of the array
print(numbers)
print("Array length of numbers: ", numLength)
i = numLength
i = i-1 #since the array starts at 0 instead of 1
k = 0
for k in range(8):
numbersrev[k] = numbers[i]
print ("The ", i," element of numbers is the ", k," element of numbersrev")
i -= 1
k += 1
print(numbersrev)
This is what I get after debugging on vscode:
[2, 4, 9, 11, 8, 3, 2, 5, 10]
Array length of numbers: 9
The 8 element of numbers is the 0 element of numbersrev
The 7 element of numbers is the 1 element of numbersrev
The 6 element of numbers is the 2 element of numbersrev
The 5 element of numbers is the 3 element of numbersrev
The 4 element of numbers is the 4 element of numbersrev
The 3 element of numbers is the 5 element of numbersrev
The 2 element of numbers is the 6 element of numbersrev
The 1 element of numbers is the 7 element of numbersrev
[10, 5, 2, 3, 8, 3, 2, 5, 10]
The top array is the original and the bottom array is the supposed reversal array
I cannot for the life of me find out why it stops changing the numbersrev array halfway through. Anybody know what the cause could be?
Okay, a few things...
First for loops increment their variables automatically in python.
so:
for k in range(8):
...
i -= 1
k += 1
should be:
for k in range(8):
...
i -= 1
No need to manually increment k.
Next lists are NOT arrays.
Lists in python are very different from arrays in a language like C.
Lists are mutable, and are passed by reference by default.
so when you try to make an empty array:
numbersrev = numbers #blank array for reverse
you are actually referencing the same 'list' from both numbers AND numbersrev
What you should have done is numbersrev = []
Then in your for loop, simply append to numbersrev rather than assign.
for k in range(numLength):
numbersrev.append(numbers[i])
print ("The ", i," element of numbers is the ", k," element of numbersrev")
i -= 1
Lastly
you could/should reference the length of numbers rather than a hardcoded value in your for loop, but how you have it will still work (assuming you ONLY ever get 8 numbers)
for k in range(numLength):
...
All together
numbers = read() #creates numbers array out of the txt file
numbersrev = [] #blank array for reverse
numLength = len(numbers) #measures the length of the array
print(numbers)
print("Array length of numbers: ", numLength)
i = numLength
i = i-1 #since the array starts at 0 instead of 1
for k in range(numLength):
numbersrev.append(numbers[i])
print ("The ", i," element of numbers is the ", k," element of numbersrev")
i -= 1
print(numbersrev)
numbersrev = numbers sets numbersrev to point to the same list as numbers, meaning when you modify numbers or numbersrev you're modifying the other at the same time. To make an actual copy of the object, you instead need to call numbersrev = numbers.copy(). Also, #sahasrara62's comment is correct, you need to call for k in range(numLength) instead of for k in range(8)
What you've done here is assign the reversed array as the normal array with this line:
numbersrev = numbers #blank array for reverse
What you're actually doing with that loop is this:
numbers[0] = numbers[9] # [10, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers[1] = numbers[8] # [10, 9, 3, 4, 5, 6, 7, 8, 9, 10]
numbers[2] = numbers[7] # [10, 9, 8, 4, 5, 6, 7, 8, 9, 10]
numbers[3] = numbers[6] # [10, 9, 8, 7, 5, 6, 7, 8, 9, 10]
numbers[4] = numbers[5] # [10, 9, 8, 7, 6, 6, 7, 8, 9, 10]
numbers[5] = numbers[4] # [10, 9, 8, 7, 6, 6, 7, 8, 9, 10]
numbers[6] = numbers[3] # [10, 9, 8, 7, 6, 6, 7, 8, 9, 10]
numbers[7] = numbers[2] # [10, 9, 8, 7, 6, 6, 7, 8, 9, 10]
numbers[8] = numbers[1] # [10, 9, 8, 7, 6, 6, 7, 8, 9, 10]
numbers[9] = numbers[0] # [10, 9, 8, 7, 6, 6, 7, 8, 9, 10]
...
If you assign the variable like this:
numLength = len(numbers) #measures the length of the array
numbersrev = [0]*numLength #blank array for reverse
You'll get the correct answer since the reverse list is no longer pointing to the normal list.
the problem you are facing is because of this line
numbersrev = numbers #blank array for reverse
In this line you are not creating an empty array, you are saving the reference of numbers array in a new variable named numbersrev. This means that when you make an operation in array numbersrev you are changing also the values of numbers. To avoid this kind of problems you have two options:
Make a copy of the array with slices
In this way you copy the values of the array, not the reference of the array. This means the changes you make to the new array will not change the original array.
numbersrev = numbers[:]
Create an empty array and use append instead of assignation
This change is a little different from what you did, but basically instead of creating a copy of the array, you create a new array which will be filled in the for loop, something like:
numbers.rev = []
...
for k in range(8):
numbersrev.append(numbers[i])
So with the first option and also changing some things in the k index we have a code like this:
numbers = [2, 4, 9, 11, 8, 3, 2, 5, 10] # you can change for read
numbersrev = numbers[:] #copy array elements
numLength = len(numbers) #array length
print(numbers)
print("Array length of numbers: ", numLength)
i = numLength - 1
# you don't need to initialize k because it's initialized and incremented with range in the loop
for k in range(numLength):
numbersrev[k] = numbers[i]
print ("The ", i," element of numbers is the ", k," element of numbersrev")
i -= 1
print(numbersrev)
Hope this would help you solve the problem, just like a note you could solve this problem in many ways: slicing (numbers[::-1]), list comprehension and some others. All the ways are valid so just in case you want to explore more.
Related
Swapping opposite elements of a List of Integers if either is Odd
Write a program with the definition of a function named Array_Swap() that will accept an integer list & its size as arguments and the function will swap elements in such a way that the first element is swapped with the last element, the second element is swapped with the second last element and so on, only if anyone or both the elements are odd and display the result. If initially, a list of seven elements is: [5, 16, 4, 7, 19, 8, 2], the contents of the list after the execution should be: [2, 16, 19, 7, 4, 8, 5]. def Array_Swap(List,Size): for i in range (Size//2): List[i]=List[Size//2-i] print(List) L=[] n=int(input("Enter number of elements")) for i in range(n): x=int(input("Enter element")) L.append(x) Array_Swap(L,len(L))
The size/length of the list is not relevant because it can be obtained by len(list). And even then it's not required to conditionally swap items in the list. I suggest that the Size parameter be removed, but considering it's an assignment, it can be given a default of None so that it can be ignored by the caller if desired. The following algorithm zips the input list with its reverse to form pairs relative to their index from the front and end of the list respectively, i.e. the first and last items are paired, the second and second last are paired, etc. Once the items are paired it is simply a matter of iterating over the list and emitting the second number of the pair if either number is odd, or the first number if neither is odd - effectively swapping the pairs as required. This is done in-place (that's what the List[:] does) with a list comprehension. def ArraySwap(List, Size=None): List[:] = [b if (a % 2 or b % 2) else a for a, b in zip(List, reversed(List))] print(List) >>> l = [5, 16, 4, 7, 19, 8, 2] >>> ArraySwap(l) [2, 16, 19, 7, 4, 8, 5] >>> l [2, 16, 19, 7, 4, 8, 5] >>> l = list(range(1,30)) >>> ArraySwap(l) [29, 2, 27, 4, 25, 6, 23, 8, 21, 10, 19, 12, 17, 14, 15, 16, 13, 18, 11, 20, 9, 22, 7, 24, 5, 26, 3, 28, 1] >>> ArraySwap([1]) [1] >>> ArraySwap([]) []
To swap two elements in the list, use the pattern a, b = b, a. If i is the index of a list item, it's opposite/mirror element is -(i+1), or - i - 1. so for the 0th element (first one), the mirror is -(0+1), = -1 using that as the indexer for the element, swap the two list elements IF check that at least one of them is odd before swapping: def Array_Swap(List,Size): for i in range (Size // 2): if List[i] % 2 == 1 or List[-(i+1)] % 2 == 1: List[i], List[-(i+1)] = List[-(i+1)], List[i] print(List) L = [5, 16, 4, 7, 19, 8, 2] # use your input blocks as before, this is an example Array_Swap(L,len(L)) Output: [2, 16, 19, 7, 4, 8, 5] (And if L = [5, 16, 4, 7, 19, 8, 1, 2], output is [2, 1, 4, 19, 7, 8, 16, 5].) Btw, you don't need to pass in the size of the list as a parameter. You could do just: for i in range(len(List) // 2)
Another solution: def Array_Swap(List, Size=None): if Size is None: Size = len(List) for (i, j) in zip(range(Size // 2), range(Size - 1, Size // 2, -1)): if List[i] % 2 or List[j] % 2: List[i], List[j] = List[j], List[i] print(List) Alternatively: Size parameter is redundant since python's list instance knows its own size Use bitwise operatos & | >>... possibly cheaper than modulus % and divide / operations. def Array_Swap(List): for i in range(len(List) >> 1): if (List[i] | List[-i-1]) & 1: List[i], List[-i-1] = List[-i-1], List[i] print(List)
The standard way to swap two variables in Python is: a, b = b, a In this case, you would do: lst[i], lst[size - i - 1] = lst[size - i - 1], lst[i] which swaps the ith element with the element that is at index size - i - 1 (i.e. the ith index from the end). The other issue with your code is that it doesn't check whether either of the elements being swapped are odd, which you can resolve by adding the condition: if lst[i] % 2 or lst[size - i - 1] % 2: before doing the swap. This uses the modulo operator (%) to check the parity of the elements. Taking a number modulo 2 will return 1 if the number is odd. If either are odd (1 has a truth value of True), the condition would succeed and the swap will be performed. Finally, your function was printing the list, rather than returning it. Its usually best to return a result and print the returned result. The full working version, with the above three changes is as follows: def list_swap(lst, size): for i in range(size // 2): if lst[i] % 2 or lst[size - i - 1] % 2: lst[i], lst[size - i - 1] = lst[size - i - 1], lst[i] return lst l = [] n = int(input("Enter number of elements: ")) for _ in range(n): x = int(input("Enter element: ")) l.append(x) result = list_swap(l, len(l)) print(result) Also note, I've changed all the variables to be lowercase, which is standard in Python. With your shown example: Enter number of elements: 7 Enter element: 5 Enter element: 16 Enter element: 4 Enter element: 7 Enter element: 19 Enter element: 8 Enter element: 2 [2, 16, 19, 7, 4, 8, 5]
Watching a counter, tally total and counting missed counts
I am attempting to create a piece of code that will watch a counter with an output something like: a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30] I want the code to be able to tally the total and tell me how many counts are missed for example if this happened: a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24, 25, 26, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,1,2] I would get a total of 92 still, but get feedback that 8 are missing. I have gotten very close with the following code: Blk_Tot = 0 CBN = 0 LBN = 0 x = 0 y = 0 z = 0 MissedBlocks = 0 for i in range(len(a1)): CBN = a1[i] if CBN - LBN <= 0: if LBN == 30: y = 30 - abs(CBN - LBN) elif LBN < 30: z = 30 - LBN y = 30 - abs(CBN - LBN) + z print(z) Blk_Tot = Blk_Tot + y else: x = CBN - LBN Blk_Tot = Blk_Tot + x if x > 1: MissedBlocks = MissedBlocks - 1 + x LBN = CBN print(Blk_Tot) print(MissedBlocks) If I delete anywhere between 1 and 30 it works perfectly, however if I delete across 30, say 29,30,1,2 it breaks.I don't expect it to be able to miss 30 in a row and still be able to come up with a proper total however. Anyone have any ideas on how this might be achieved? I feel like I am missing an obvious answer :D Sorry I think I was unclear, a1 is a counter coming from an external device that counts from 1 to 30 and then wraps around to 1 again. Each count is actually part of a message to show that the message was received; so say 1 2 4, I know that the 3rd message is missing. What I am trying to do is found out the total that should have been recieved and how many are missing from the count. Update after an idea from the posts below, another method of doing this maybe: Input: 123456 List[1,2,3,4,5,6] 1.Check first input to see which part of the list it is in and start from there (in case we don't start from zero) 2.every time an input is received check if that matches the next value in the array 3.if not then how many steps does it take to find that value
You don't need to keep track if you past the 30 line. Just compare with the ideal sequence and count the missing numbers. No knowledge if parts missing at the end. No knowledge if more than 30 parts are missing in a block. from itertools import cycle def idealSeqGen(): for i in cycle(range(1,31)): yield(i) def receivedSeqGen(): a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30, 1,2] for i in a1: yield(i) receivedSeq = receivedSeqGen() idealSeq = idealSeqGen() missing = 0 ideal = next(idealSeq) try: while True: received = next(receivedSeq) while received != ideal: missing += 1 ideal = next(idealSeq) ideal = next(idealSeq) except StopIteration: pass print (f'There are {missing} items missing') Edit The loop part can be a little bit simpler missing = 0 try: while True: ideal = next(idealSeq) received = next(receivedSeq) while received != ideal: missing += 1 ideal = next(idealSeq) except StopIteration: pass print (f'There are {missing} items missing')
In general, if you want to count the number of differences between two lists, you can easily use a dictionary. The other answer would also work, but it is highly inefficient for even slightly larger lists. def counter(lst): # create a dictionary with count of each element d = {} for i in lst: if d.get(i, None): d[i] += 1 else: d[i] = 1 return d def compare(d1, d2): # d1 and d2 are dictionaries ans = 0 for i in d1.values(): if d2.get(i, None): # comapares the common values in both lists ans += abs(d1[i]-d2[i]) d2[i] = 0 else: #for elements only in the first list ans += d1[i] for i in d2.values(): # for elements only in the second list if d2[i]>0: ans += d2[i] return ans l1 = [...] l2 = [...] print(compare(counter(l1), counter(l2)))
New code to check for missing elements from a repeating sequence pattern Now that I have understood your question more clearly, here's the code. The assumption in this code is the list will always be in ascending order from 1 thru 30 and then repeats again from 1. There can be missing elements between 1 and 30 but the order will always be in ascending order between 1 and 30. If the source data is as shown in list a1, then the code will result in 8 missing elements. a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30, 1,2] a2 = a1.copy() c = 1 missing = 0 while a2: if a2[0] == c: c+=1 a2.pop(0) elif a2[0] > c: missing +=1 c+=1 elif a2[0] < c: missing += 31-c c = 1 if c == 31: c=1 print (f'There are {missing} items missing in the list') The output of this will be: There are 8 items missing in the list Let me know if this addresses your question earlier code to compare two lists You cannot use set as the items are repeated. So you need to sort them and find out how many times each element is in both lists. The difference will give you the missing counts. You may have an element in a1 but not in a2 or vice versa. So finding out the absolute count of missing items will give you the results. I will update the response with better variables in my next update. Here's how I did it: code with comments: a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30] a2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,1,2] #step 1: Find out which list is longer. We will use that as the master list if len(a1) > len(a2): master_list = a1.copy() second_list = a2.copy() else: master_list = a2.copy() second_list = a1.copy() #step 2: We must sort both master and second list # so we can compare against each other master_list.sort() second_list.sort() #set the counter to zero missing = 0 #iterate through the master list and find all values in master against second list #for each iteration, remove the value in master[0] from both master and second list #when you have iterated through the full list, you will get an empty master_list #this will help you to use while statement to iterate until master_list is empty while master_list: #pick the first element of master list to search for x = master_list[0] #count the number of times master_list[0] is found in both master and second list a_count = master_list.count(x) b_count = second_list.count(x) #absolute difference of both gives you how many are missing from each other #master may have 4 occurrences and second may have 2 occurrences. abs diff is 2 #master may have 2 occurrences and second may have 5 occurrences. abs diff is 3 missing += abs(a_count - b_count) #now remove all occurrences of master_list[0] from both master and second list master_list = [i for i in master_list if i != x] second_list = [i for i in second_list if i != x] #iterate until master_list is empty #you may end up with a few items in second_list that are not found in master list #add them to the missing items list #thats your absolute total of all missing items between lists a1 and a2 #if you want to know the difference between the bigger list and shorter one, #then don't add the missing items from second list missing += len(second_list) #now print the count of missig elements between the two lists print ('Total number of missing elements are:', missing) The output from this is: Total number of missing elements are: 7 If you want to find out which elements are missing, then you need to add a few more lines of code. In the above example, elements 27,28,29,30, 4, 5 are missing from a2 and 31 from a1. So total number of missing elements is 7. code without comments: a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30] a2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,1,2] if len(a1) > len(a2): master_list = a1.copy() second_list = a2.copy() else: master_list = a2.copy() second_list = a1.copy() master_list.sort() second_list.sort() missing = 0 while master_list: x = master_list[0] a_count = master_list.count(x) b_count = second_list.count(x) missing += abs(a_count - b_count) master_list = [i for i in master_list if i != x] second_list = [i for i in second_list if i != x] missing += len(second_list) print ('Total number of missing elements are:', missing)
Add 1 for odd numbers on list Python
So this is my code: numbers = []#1 for i in range(10): i += 1 numbers.append(i) print (numbers) numbers2 = [n + 2 for n in numbers]#2 print (numbers2) numbers3 = []#3 for x in numbers2: if (x % 2 == 1) : x += 1 numbers3 = x print (numbers3) I'm using Google Colab and run those codes on 3 separate code cells(hashtag numbers comment). The #1 program output is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. And the #2 output is [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]. So at #3 cell I want program to add 1 on each odd numbers in numbers2 list. The output I want is [4, 4, 6, 6, 8, 8, 10, 10, 12, 12]. But what I get is : 4 6 8 10 12 Also I'm trying to not use function(just for these codes). And for loop on #1 code I intend to do that. Additional question : Is it possible to modify elements on list without append the result to another list(like #2 code)? Like just add 2 on each numbers on list
Try the following: second_list = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12] third_list = second_list for i in range(len(second_list)): if (second_list[i] % 2 == 1): make_even = second_list[i] + 1 third_list[i] = make_even else: third_list[i] = second_list[i] print (third_list) You'll have to tweak it for the Google Colab project you're doing, but the logic here should be right. Right now this answer works in regular Python 3.
your third cell should look like this, you were close to the solution all you need to do is to add x values in numbers3 list numbers3 = []#3 for x in numbers2: if (x % 2 == 1) : x += 1 numbers3.append(x) print(numbers3)
In order to fill the list instead of just printing the value you must use the append function instead of = numbers3 = x #becomes numbers3.append(x) To get the list in the format you want, you also have to drop the append out of the if statement, and drop the print out of the for loop, like so: numbers3 = []#3 for x in numbers2: if (x % 2 == 1) : x += 1 numbers3.append(x) # Here print (numbers3) # and here
Generating a list of N pseudo-random integers, drawn from a specific range, with the list summing to a specific value
In Python: How can I generate a list of N (e.g. 10) pseudo-random integers, each drawn from a specific range (e.g. between 3 and 9), with the list summing up to a specific value (e.g. 58)? For this example the solution would look like this: solution = [3, 7, 7, 9, 3, 6, 4, 8, 8, 3] sum(solution) 58 That is, 10 numbers, each between 3 and 9, summing up to 58. I've tried a solution approaches with np.random.dirichlet or np.random.multinomial as suggested in related questions here, but these do not allow for choosing the integers from a specific range.
import random N = 10 s = 58 i, j = 3, 9 out = [i] * N while sum(out) != s: idx = random.randint(0, N-1) if out[idx] < j: out[idx] += 1 print(out) Prints (for example): [9, 7, 6, 4, 5, 8, 3, 5, 5, 6]
One idea I've just had is to initialise a list with n values that are the average value (so, as close to being all the same value as possible) and then randomly select a pair of values and increase one while decreasing the other while ensuring values are kept with the required range, so don't increase/decrease if the value will go out of bounds.
Repeat until success? a = [] while sum(a) != 58: a = random.choices(range(3, 10), k=10) Takes about 17 attempts on average.
how to identify duplicate integers within a list, than minus each integer following the duplicate by one?
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]