Python for loop to iterate two times - python

Below is example code:
List1 = [['a'], ['b'], ['c']]
range_value = len(List1) * 2
for x in range(0, range_value):
if x == 0 or x == 1:
for y in List1[1]:
print y
if x == 2 or x == 3:
for y in List1[2]
if x == 4 or x == 5:
for y in List1[2]
This is manual steps defineing if statement in case I have big values like 100 or 1000. Its difficult, Please help me with any logic for this. first two values should use List[1] and next two values List[2] and so on.

Use a third loop:
for x in List1:
for _ in [0,1]:
for y in x:
...
This iterates over each element of List1 twice, as in the original code, without explicit index wrangling.

I think you're looking for:
for y in List1[x//2]
It's a bit hard to tell, since you started at index 1 instead of index 0, but apparently want to use every element of the list. You may need [x//2 + 1].
Another possible enhancement is to double-step your outer loop:
for x in range(0, range_value, 2):

Related

How to find back to back same items in Python?

I basically want to count how many times "H" printed back to back 3 times in this random sequence. How can i add a code which detects its occurence, is it possible with index method?
import random
prob= ["H","T"]
streakcount=0
x =[]
for excount in range(1000):
y = random.choice(prob)
x.append(y)
print(x)
Yeah, you can index the previous element in the 'x' array and check if it is also an 'H'.
So, first add an IF statement after y is assigned a random value and check if that value is 'H'. If it is, then you want to index the previous element in the array 'x' to see if it is also an 'H'. Finally, we need an accumulator to store the number of times this happens.
That's the gist of it. The only potential hiccup we want to avoid occurs at the very beginning of the 'for' loop when excount is 0 or 1. At this time, if an 'H' is randomly chosen and we try to index the 'x' array at the index, excount-2, we'll end up indexing the list from the end (with a negative number) or indexing a list at an index that does not yet exist.
This could occur because we're subtracting 1 and 2 from excount and then indexing the 'x' array, so we just want to double-check that excount is >= 2 before we start checking to see if we've seen three H's in a row.
import random
prob= ["H","T"]
streakcount=0
x =[]
for excount in range(1000):
y = random.choice(prob)
if y == 'H' and excount >= 2:
# check to see if previous element was also an 'H'
if x[excount-1] == 'H' and x[excount-2] == 'H':
streakcount += 1 # 3 H's in a row! increment counter
x.append(y)
print(x)
I think you can just convert a list to string and then use count to get count.
import random
prob= ["H","T"]
streakcount=0
x =[]
for _ in range(1000):
y = random.choice(prob)
x.append(y)
strlist = ' '.join(map(str, x))
print(strlist.count("H H H"))
The deque class from the collections module is useful for this use-case. The deque is constructed so as to support a list with a maximum size of 3. As new values are appended to the deque the oldest value is lost. Therefore we can use the deque's count() function to get the number of values matching the criterion of interest
from random import choice
from collections import deque
ht = ['H', 'T']
streakcount = 0
d = deque([], 3)
for _ in range(1_000):
d.append(choice(ht))
if d.count('H') == 3:
streakcount += 1
print(f'{streakcount=}')
import random
prob = ["H", "T"]
streakcount = 0
x = []
for excount in range(1000):
y = random.choice(prob)
x.append(y)
for i in range(len(x)):
if i > 0 and i + 1 <= len(x):
if x[i - 1] == 'H' and x[i] == 'H' and x[i + 1] == 'H':
streakcount += 1
print(streakcount)

Python: Comparing values in two lists

I've really tried looking all over for solutions to my problem but haven't been successful in finding anything. If someone else has already asked this question, I apologize. Onto the problem.
I have two lists in with values to be compared to each other. I have tried the following option.
list1 = [1,3,5,7,9]
list2 = [200,2]
x = 0
n = 0
y = 0
while x <= 9:
if list1[y] >= list2[n]:
print('TRUE')
x = x + 1
y = y + 1
if y > 4:
y = 0
n = n + 1
else:
print('FALSE')
x = x + 1
y = y + 1
if y > 4:
y = 0
n = n + 1
The only problem is, instead of the variables in place, I need to iterate through a list of values.
So instead, I would like the code to look something like this:
x = 0
n = [0,1]
y = [0,3]
z = len(n) + len(y) - 1
while x <= z:
if list1[y] >= list2[n]:
print('TRUE')
x = x + 1
else:
print('FALSE')
x = x + 1
Where n and y are index values of the numbers that I want to compare.
This does not work for me and I'm really not sure how else to do this.
Edit: I didn't think I had to explain everything by text since I included two sets of code. The first set of code works and it shows exactly what I am trying to do. The second is what I want it to do.
Broken down further I want to know if list1[0]>=list2[0], followed by list1[3]>=list2[0], followed by list1[0]>=list2[1], followed by list1[3]>=list2[1]. The outputs that I expect are in the code I provided.
Apologies if I wasn't clear before. I need to call specific index positions that I will have in a separate list. This is the problem that I tried to outline in the second code.
I think now get what you are trying to do.
First, there are two lists of "raw" data:
list1 = [1,3,5,7,9]
list2 = [200,2]
Then, there are two sets of "indices of interest":
y = [0, 3] # indices of interest for list1
n = [0, 1] # indices of interest for list2
I think the following can achieve what you want:
product = [(index1, index2) for index2 in n for index1 in y] #cartesian product
for index1, index2 in product:
if list1[index1] >= list2[index2]:
print("True")
else:
print("False")
Or if the cartesian product is not wanted, simply do it within nested loops:
for index2 in n:
for index1 in y:
if list1[index1] >= list2[index2]:
print("True")
else:
print("False")

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_)

Find first non zero numbers in an array (zeroes can be anywhere)

Suppose we have an array: x = [10,0,30,40]. I would like to extract the first non zero element and store it in a different variable, say y. In this example, y = 10. We can also have many zeros, x = [0,0,30,40], which should give y = 30 as the extracted value.
I tried a Python snippet like this:
i = 0
while x[i] != 0:
y = arr[i]
if x[i] == 0:
break
This only works if the array is [10,0,30,40]. It does not work if I have 0,20,30,40. The loop would stop before that. What is an efficient way to implement this? I try not to use any special Numpy functions, just generic common loops because I might need to port it to other languages.
You can do this
x = [10,0,30,40]
for var in x:
if var != 0:
y = var
break
You could use list comprehension to get all the non-zero values, then provided there are some non-zero values extract the first one.
x = [10,0,30,40]
lst = [v for v in x if v != 0]
if lst:
y = lst[0]
print(y)
The problem with your code is that you don't increment i so it's stuck on the first element. So what you could do to keep the code portable is:
while x[i] != 0:
y = x[i]
if x[i] == 0:
break
i+=1
This code is still not clean, because if there is no 0 in your array then you will get an IndexError as soon as you reach the end.
I'm kind of new to this but i think this should work:
x = [0, 12, 24, 32, 0, 11]
y = []
for num in x:
if num != 0:
y.append(num)
break
print(y)
You can use the next function:
x = [10,0,30,40]
next(n for n in x if n) # 10
x = [0,0,30,40]
next(n for n in x if n) # 30
if you need to support the absence of zero in the list, you can use the second parameter of the next() function:
x = [0,0,0,0]
next((n for n in x if n),0) # 0

How to write a function that copies all of the elements of a list except the largest value into another list? Python 3.2

I'm trying to answer this question on a practice test:
Write a function, def eliminate(x, y), that copies all the elements of the list x except the largest value into the list y.
The best thing I could come up with is:
def eliminate(x, y):
print(x)
y = x
big = max(y)
y.remove(big)
print(y)
def main():
x = [1, 3, 5, 6, 7, 9]
y = [0]
eliminate(x, y)
main()
I don't think that'll cut it if a question like that comes up on my final, and I'm pretty sure I shouldn't be writing a main function with it, just the eliminate one. So how would I answer this? (keep in mind this is an introductory course, I shouldn't be using more advanced coding)
I'd probably do this:
def eliminate(x, y):
largest = max(x)
y[:] = [elem for elem in x if elem != largest]
This fills y with all the elements in x except whichever is largest. For example:
>>> x = [1,2,3]
>>> y = []
>>> eliminate(x, y)
>>> y
[1, 2]
>>> x = [7,10,10,3,4]
>>> eliminate(x, y)
>>> y
[7, 3, 4]
This assumes that by "copies" the question is asking for the contents of y to be replaced. If the non-maximal elements of x are to be appended to y, you could use y.extend instead.
Note that your version doesn't handle the case where there are multiple elements with the maximum value (e.g. [1,2,2]) -- .remove() only removes one of the arguments, not all of them.
In order to find the largest number in a list you will need to iterate over that list and keep trace of the largest element along the way. There are several ways to achieve this.
So this code answers the question:
y.extend([n for n in x if n != max(x)])
but i'm worried it might not solve your problem, which is learning how and why this works. Here is that code expanded into a very straight forward way that just uses for loops and if statments.
def trasfer_all_but_largest(transfer_from_list, transfer_to_list):
current_index = 0
index_of_current_largest_element = 0
largest_element_so_far = None
for element in transfer_from_list:
if current_index == 0:
largest_element_so_far = element
else:
if element > largest_element_so_far:
largest_element_so_far = element
index_of_current_largest_element = current_index
current_index = current_index + 1
index_of_largest_element = index_of_current_largest_element
current_index = 0 # reset our index counter
for element in transfer_from_list:
if current_index == index_of_largest_element:
continue # continue means keep going through the list
else:
transfer_to_list = transfer_to_list + [element]
current_index = current_index + 1
return transfer_to_list
list_with_large_number = [1, 2, 100000]
list_were_transfering_to = [40, 50]
answer_list = trasfer_all_but_largest(list_with_large_number, list_were_transfering_to)
print(answer_list)

Categories