How to edit integers of a list? - python

So I’m trying to take a list like this:
[1, 2, 3, 8, 15, 4, 12, 8]
And whenever a number is larger than 9 or has two digits, that number has 10 subtracted from it, and 1 is added to the previous number in the list.
So the list would result into this:
[1, 2, 3, 9, 5, 5, 2, 8]
For now, i have something like:
for i in list:
If i in list>= 10
list[i] = list[i] - 10
list[i-1] = list[i-1] + 1
But I’m getting an error from this
Does anyone know how to do this?

We are enumerating the list and as your logic says, if we encounter a number that is bigger than 9, we substract it from 10 and we add 1 to the previous element.
my_list = [1, 2, 3, 8, 15, 4, 12, 8]
for index,item in enumerate(my_list):
if item > 9:
my_list[index] -= 10
if index > 0:
my_list[index-1] += 1
print(my_list) # [1, 2, 3, 9, 5, 5, 2, 8]

data = [1, 2, 3, 8, 15, 4, 12, 8]
count = 0
for item in data:
if item >= 10 :
data[count-1] += 1
data[count] -= 10
count += 1
Output:
[1, 2, 3, 9, 5, 5, 2, 8]

Here it is man, but this only handles if the first item is less than 10 because I did not make the logic for it to check if its the first item, it will crash if the first item in the list is greater than or equal to 10.
x = [1,2,3,8,15,4,12,8]
for i in range(0, len(x)):
if x[i] >= 10:
x[i] = x[i]-10
x[i-1] = x[i-1]+1
print(x)
the output will be
[1, 2, 3, 9, 5, 5, 2, 8]

Related

'List index out of range' while reversing list

The problem is regarding reversing a list A of size N in groups of K. For example if A = [1,2,3,4,5], k = 3
Output = [3,2,1,5,4]
The error I get, when I run this is List Index out of range on line 4.
def reverseInGroups(A,N,K):
arr1 = []
for i in range(K):
arr1.append(A[(N-i)%K]) #line 4
for j in range(N-K):
arr1.append(A[N-j-1])
return arr1
This will implement what you are trying to achieve:
def reverseInGroups(A,K):
N = len(A)
arr1 = []
for i in range(0, N, K):
arr1.extend(A[i : i+K][::-1])
return arr1
print(reverseInGroups([1,2,3,4,5], 3))
Interestingly, the code in the question actually works in the example case, but it is not general. The case where it works is where N = 2*K - 1 (although where it does not work, the elements are in the wrong order rather than an IndexError).
Cant seem to reproduce your 'List index out of range' error, but your logic is faulty:
reverseInGroups(A,N,K):
arr1 = []
for i in range(K):
arr1.append(A[(N-i)%K]) #line 4
for j in range(N-K):
arr1.append(A[N-j-1])
return arr1
print(reverseInGroups([1,2,3,4,5],5, 3)) # works, others get wrong result
print(reverseInGroups([1,2,3,4,5,6],6, 3)) # wrong result: [1, 3, 2, 6, 5, 4]
prints:
[3, 2, 1, 5, 4] # correct
[1, 3, 2, 6, 5, 4] # wrong
You fix this and make this smaller by packing it into a list comprehension:
def revv(L,k):
return [w for i in (L[s:s+k][::-1] for s in range(0,len(L),k)) for w in i]
for gr in range(2,8):
print(gr, revv([1,2,3,4,5,6,7,8,9,10,11],gr))
to get:
2 [2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 11]
3 [3, 2, 1, 6, 5, 4, 9, 8, 7, 11, 10]
4 [4, 3, 2, 1, 8, 7, 6, 5, 11, 10, 9]
5 [5, 4, 3, 2, 1, 10, 9, 8, 7, 6, 11]
6 [6, 5, 4, 3, 2, 1, 11, 10, 9, 8, 7]
7 [7, 6, 5, 4, 3, 2, 1, 11, 10, 9, 8]
You can also try with this:
def reverse(l, n):
result = []
for i in range(0, len(l)-1, n):
for item in reversed(l[i:i+n]):
result.append(item)
for item in reversed(l[i+n:]):
result.append(item)
return result
You can reverse the array upto index K and reverse the remaining part and add these both arrays.
def reverseInGroups(A,N,K):
return A[:K][::-1]+A[K:][::-1]
A = [1,2,3,4,5]
N = 5
K = 3
res = reverseInGroups(A,N,K)
print(res)

How to make ascending sublists in a list of integers go in descending order?

Working on some example questions, the particular one asks to make a function which would take a list and return a new one which would make every ascending sublist in the list go in descending order and leave the descending sublists as they are. For example, given the list [1,2,3,4,5], I need the list [5,4,3,2,1] or given a list like [1,2,3,5,4,6,7,9,8] would return [5,3,2,1,9,7,6,4,8]
Here's what I have so far, but it does not do anything close to what I'd like it to do:
def example3(items):
sublst = list()
for i in items:
current_element = [i]
next_element = [i+1]
if next_element > current_element:
sublst = items.reverse()
else:
return items
return sublst
print (example3([1,2,3,2])) #[[1, 2, 3, 2], [1, 2, 3, 2], [1, 2, 3, 2], [1, 2, 3, 2]]
EDIT:
I feel like people are a little confused as to what I want to do in this case, heres a better example of what I'd like my function to do. Given a list like: [5, 7, 10, 4, 2, 7, 8, 1, 3] I would like it to return [10, 7, 5, 4, 8, 7, 2, 3, 1]. As you can see all the sublists that are in descending order such as ([5,7,10]) gets reversed to [10, 7, 5].
It was a bit challenging to figure out what you need.
I think you want something like as follows:
import random
l = [5, 7, 10, 4, 2, 7, 8, 1, 3]
bl =[]
while True:
if len(l) == 0:
break
r = random.randint(0, len(l))
bl.extend(l[r:None:-1])
l = l[r+1:]
print(bl)
Out1:
[10, 7, 5, 4, 8, 7, 2, 3, 1]
Out2:
[10, 7, 5, 2, 4, 1, 8, 7, 3]
Out3:
[3, 1, 8, 7, 2, 4, 10, 7, 5]
Out4:
[2, 4, 10, 7, 5, 3, 1, 8, 7]
etc.
If you want a specific reverse random list:
import random
loop_number = 0
while True:
l = [5, 7, 10, 4, 2, 7, 8, 1, 3]
bl =[]
while True:
if len(l) == 0:
break
r = random.randint(0, len(l))
bl.extend(l[r:None:-1])
l = l[r+1:]
loop_number += 1
if bl == [10, 7, 5, 4, 8, 7, 2, 3, 1]:
print(bl)
print("I tried {} times".format(loop_number))
break
Out:
[10, 7, 5, 4, 8, 7, 2, 3, 1]
I tried 336 times
The general algorithm is to keep track of the current ascending sublist you are processing using 2 pointers, perhaps a "start" and "curr" pointer. curr iterates over each element of the list. As long as the current element is greater than the previous element, you have an ascending sublist, and you move curr to the next number. If the curr number is less than the previous number, you know your ascending sublist has ended, so you collect all numbers from start to curr - 1 (because array[curr] is less than array[curr - 1] so it can't be part of the ascending sublist) and reverse them. You then set start = curr before incrementing curr.
You will have to deal with the details of the most efficient way of reversing them, as well as the edge cases with the pointers like what should the initial value of start be, as well as how to deal with the case that the current ascending sublist extends past the end of the array. But the above paragraph should be sufficient in getting you to think in the right direction.

Modifying list with numbers in python

I am trying modify a list. Currently, there is a list with random number and I would like to change the list which creates maximum number of increase between numbers. Maybe I worded badly. For example, if list is [2,3,1,2,1], I would modify into [1,2,3,1,2] since 1->2, 2->3 and 1->2 in an increase which gives total of 3 increasing sequence. Any suggestions?
I would approach your problem with this recursive algorithm. What I am doing is sorting my list, putting all duplicates at the end, and repeating the same excluding the sorted, duplicate-free list.
def sortAndAppendDuplicates(l):
l.sort()
ll = list(dict.fromkeys(l)) # this is 'l' without duplicates
i = 0
while i < (len(ll)-1):
if list[i] == list[i+1]:
a = list.pop(i)
list.append(a)
i = i - 1
i = i + 1
if hasNoDuplicates(l):
return l
return ll + sortAndAppendDuplicates(l[len(ll):])
def hasNoDuplicates(l):
return( len(l) == len( list(dict.fromkeys(l)) ) )
print(sortAndAppendDuplicates([2,3,6,3,4,5,5,8,7,3,2,1,3,4,5,6,7,7,0,1,2,3,4,4,5,5,6,5,4,3,3,5,1,2,1]))
# this would print [0, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 3, 4, 5, 3, 5, 3, 5]

How to print out certain elements of a list in python?

So I have a list li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and I only want to print out elements that are a part of an arithmetic sequence 6n - 5 (1st, 7th and 13th).
How can I do that if I have a list with n elements?
You could simply say
print([x for x in li if x % 6 == 1])
or, alternatively, if you just want the sequence and don't want to bother about creating li in the first place,
print([6*n-5 for n in range(1, (13+5)//6+1)])
Use the code:
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
new=[]
for i in li:
if int((i+5)/6)==((i+5)/6):
#You can also use
#if ((i+5)/6).is_integer():
new.append(i)
I tried to make it as easy as possible.
Hope it helps :)
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
for n in range(1,len(li)+1): #choose n such that it is length of the list since it cant have more values than the number of values in the list.
for i in li:
if (6*n - 5) == i:
print(i)
Hope this helps
Thanks
Michael
From what I understand, you want the elements whose positions are generated by the sequence. Hence, you want elements from an array of length n whose index is from the sequence function 6x-5.
NOTE: I am assuming you are using 1-based indexing, which means, when you say 1st element in your list, you intend to get 1 and not 2.
n = 13
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# generate the sequence till n
seq = []
x = 1
while 6*x-5 <= n:
seq.append(6*x-5)
x += 1
# Print the elements from the sequence:
for idx in seq:
print(li[idx-1])
# If you want to store it in another list:
li2 = [li[idx-1] for idx in seq]
Below is a more generic and efficient way for above code:
n = 13
li = list(range(1, n+1)) # More easy to write
# More efficient way is to create a generator function
def get_seq(n):
x = 1
while 6*x-5 <= n:
yield 6*x-5
x += 1
# Get the generator object
seq = get_seq(n)
# Print the elements from the sequence:
for idx in seq:
print(li[idx-1])
# Want to store it in another list:
seq = get_seq(n) # Don't forget to get a new generator object.
li2 = [li[idx-1] for idx in seq]
Output for both snippets:
1
7
13
Hope the answer helps, and remove confusion for others as well ;)
You can simply generate the sequence for any n.
for example:
n = 10
print([ 6*x - 5 for x in range(1,n)])
output:
[1, 7, 13, 19, 25, 31, 37, 43, 49]
>>> [Finished in 0.2s]
But if you just want to filter your existing list li:
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print([ x for x in li if x % 6 == 1 ])
output:
[1, 7, 13]
>>>
[Finished in 0.3s]
li[1] is 2, li[7] is 8 and the element with the index 13 is out of range.
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
for num, i in enumerate(li):
if ((num + 5)/6).is_integer():
print(i)
# 2
# 8
If you want to start with the index 1 add start=1 to the enumerate() function.
for num, i in enumerate(li, start=1):
if ((num + 5)/6).is_integer():
print(i)
# 1
# 7
# 13

How can I compare a value in a list with the others but not itself?

I want to take the value of an integer in a list, and compare it to all the other integers in the list, except for itself. If they match, I want to subtract 1 from the other integer. This is the code I have:
for count6 in range(num_players):
if player_pos[count6] == player_pos[count5]:
if not player_pos[count5] is player_pos[count5]:
player_pos[count6] -= 1
I've tried a few other things, but I can't seem to make it work. I was able to get it to subtract 1 from every value, but it included the original value. How can I make this work?
Here's a simple way, just loop through each index and decrement if the value is the same, but the index is not the one you're checking against:
#!/usr/bin/env python3
nums = [3, 4, 5, 5, 6, 5, 7, 8, 9, 5]
pos = 3
print("List before: ", nums)
for idx in range(len(nums)):
if nums[idx] == nums[pos] and idx != pos:
nums[idx] -= 1
print("List after : ", nums)
which outputs:
paul#local:~/Documents/src/sandbox$ ./list_chg.py
List before: [3, 4, 5, 5, 6, 5, 7, 8, 9, 5]
List after : [3, 4, 4, 5, 6, 4, 7, 8, 9, 4]
paul#local:~/Documents/src/sandbox$
All the 5s have been decremented by one, except for the one at nums[3] which is the one we wanted to leave intact.
I think you're looking for something like this:
>>> values = [1, 3, 2, 5, 3, 8, 1, 5]
>>> for index, value in enumerate(values):
... for later_value in values[index + 1:]:
... if value == later_value:
... values[index] = values[index] - 1
...
>>> values
[0, 2, 2, 4, 3, 8, 1, 5]
This decrements each value by the number of times it occurs later in the list. If you want to decrement each value by the number of times it appears EARLIER in the list, you could reverse the list first and then re-reverse it after.
I'm not sure about "but included the original value" means, i'm trying to use the following code, hope this is what you want :
>>> num_players = 4
>>> player_pos = [3, 4, 5, 6]
>>> count5 = 2
>>> for count6 in range(num_players):
if player_pos[count6] <> player_pos[count5]:
player_pos[count6] -= 1
>>> player_pos
[2, 3, 5, 5]

Categories

Resources