Add 1 for odd numbers on list Python - 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
Related
Trying to understand how my python code works
i = [1, 2, 3, 5, 5, 7, 9, 12, 14, 14,] list_length = len(i) def numbers_found(x): y = i.count(x) return y latest_num = i[list_length - 1] for z in range(latest_num + 1): print("Found", numbers_found(z), "of number", "\"" + str(z) + "\".") I am trying to find how many of a certain number is available in the list, if I somehow minus by 1 to the maximum number in the list (assuming it is in ascending order) and add 1 again it works. Please help explain this to me.
Lets break it down, step by step. # a list. indexes shown below # 0 1 2 3 4 5 6 7 8 9 i = [1, 2, 3, 5, 5, 7, 9, 12, 14, 14] # getting the length of the list (10) # or the number of elements list_length = len(i) # a function returning the amounts of # times a passed value is found in the list i def numbers_found(x): y = i.count(x) return y # see above that list_length is 10 # but we need one less that to retrieve the last element # which will be 14 latest_num = i[list_length - 1] # range given 1 argument iterates from 0 # to the number you pass it but not including it # since latest_num is 14, it won't include it # So range(15) would iterate like # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 for z in range(latest_num + 1): print("Found", numbers_found(z), "of number", "\"" + str(z) + "\".") The reason range works like this, is it's common to see range(length_of_my_list) and expect it to return indexes for the full list. In order for that to happen you need to only iterate to and not include the length. In your case (10). What you are using it for is something else. You are trying to find the occurrences of all the numbers in the list. Since you are not using it for indexes, adding + 1 works since you WANT it to include 14.
Use for z in range(len(i)): print("Found", numbers_found(z), "of number", "\"" + str(z) + "\".") Here len(i) is the size of i i.e. the number of elements in i, and range(n) = [0, 1, ..., n - 1] i.e all numbers from 0 to n-1, sorted asc.
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)
Single line chunk re-assignment
As shown in the following code, I have a chunk list x and the full list h. I want to reassign back the values stored in x in the correct positions of h. index = 0 for t1 in range(lbp, ubp): h[4 + t1] = x[index] index = index + 1 Does anyone know how to write it in a single line/expression? Disclaimer: This is part of a bigger project and I simplified the questions as much as possible. You can expect the matrix sizes to be correct but if you think I am missing something please ask for it. For testing you can use the following variable values: h = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] x = [20, 21] lbp = 2 ubp = 4
You can use slice assignment to expand on the left-hand side and assign your x list directly to the indices of h, e.g.: h = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] x = [20, 21] lbp = 2 ubp = 4 h[4 + lbp:4 + ubp] = x # or better yet h[4 + lbp:4 + lbp + len(x)] = x print(h) # [1, 2, 3, 4, 5, 6, 20, 21, 9, 10] I'm not really sure why are you adding 4 to the indexes in your loop nor what lbp and ubp are supposed to mean, tho. Keep in mind that when you select a range like this, the list you're assigning to the range has to be of the same length as the range.
I need to know why this is the output for these python condition
numbers=[i**3 for i in range (10) if i**3%3==1] print(numbers) #gets 1,64,343 Why is 1, 64, 343 the answer?
This is equivalent to the code: for i in range(10): if (i*i*i) % 3 == 1: numbers.append(i*i*i) print (numbers) You are checking if the remainder obtained when the cube of a number from 1 to 10 is divided by 3 is equal to 1. If it is, you are adding it to a list and printing it.
The meaning of ** ex: 2**3= 2*2*2 #this means 2 to the power 3 = 8 The meaning of % ex: 5%2= 1 #the sign means module, that means the remaining value after divide 5 by 2, it is one. in your way, the correct path to write the for each is for i in range(0,10): value = i**3 if(value%3 == 1): print("the value is {0}".format(value)) so the result is : the value is 1 the value is 64 the value is 343 bit explanation inside the for loop first get the i = 0, at this point value = 0*0*0 = 0, then value%3=0 then get the i=1, at this point value = 1*1*1 = 1 ,the 'value%3' means 1%3 = 1, so the answer i 1 .... like this see about other conditions also. hope this will help to you.
first i is in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] then if (i*i*i) rem 3 is equal to 1 it selects (i*i*i) and for [1,4,7]: (1*1*1)%3==1, (4*4*4)%3==1 and (7*7*7)%3==1: 1*1*1=1 and 1/3=0 :remainder=1 4*4*4=64 and 64/3=21 :remainder=1 7*7*7=343 and 343/3=114 :remainder=1 so the output is: [1*1*1, 4*4*4, 7*7*7] which is [1, 64, 343] your code: numbers=[i**3 for i in range (10) if i**3%3==1] print(numbers) and this code: numbers=[] for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: if (i*i*i) % 3 == 1: numbers.append(i*i*i) print(numbers) output this: [1, 64, 343]
Iterate through each value of list in order, starting at random value
Given the following code: length = 10 numbers = [x for x in range(length)] start_index = randint(0,length-1) # now output each value in order from start to start-1 (or end) # ex. if start = 3 --> output = 3,4,5,6,7,8,9,0,1,2 # ex if start = 9 ---> output = 9,0,1,2,3,4,5,6,7,8 What is the best / simplest / most pythonic / coolest way to iterate over the list and print each value sequentially, beginning at start and wrapping to start-1 or the end if the random value were 0. Ex. start = 3 then output = 3,4,5,6,7,8,9,1,2 I can think of some ugly ways (try, except IndexError for example) but looking for something better. Thanks! EDIT: made it clearer that start is the index value to start at
You should use the % (modulo) operator. length = 10 numbers = [x for x in range(length)] start = randint(0, length) for i in range(length): n = numbers[(i + start) % length] print(n)
>>> start = randint(0, len(numbers)) >>> start 1 You can use list slicing then iterate over that >>> numbers[start:] + numbers[:start] [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] You can also use the modulus % operator in a list comprehension >>> [numbers[i%len(numbers)] for i in range(start, start + len(numbers))] [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
What is the best / simplest / most pythonic / coolest way ... You can use collections.deque and its rotate function, like this >>> from collections import deque >>> d = deque(numbers) >>> d.rotate(-9) >>> d deque([9, 0, 1, 2, 3, 4, 5, 6, 7, 8]) >>> >>> d = deque(numbers) >>> d.rotate(-2) >>> d deque([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
You can try to iterate over the list with simple conditional loops i = start while(True): print i, if i==numbers[-1]: # If it's the last number i=numbers[0] else: i += 1 if i==start: # One iteration is over break This will print 3 4 5 6 7 8 9 0 1 2