This question already has answers here:
Why can't I iterate twice over the same iterator? How can I "reset" the iterator or reuse the data?
(5 answers)
Closed 2 months ago.
if __name__ == '__main__':
arr = map(int, input().split())
a = max([x for x in arr if x != max(arr)])
print(a)
sample input: 1 2 3 4 5
goal here is to find second greatest number
type(max(arr)) is integer,
each element type in arr when looping is integer,
so why output isnt 4? This works perfectly only when I do arr = list(arr) but I want to know why wouldnt it work without it?
map returns an iterator so it can only be consumed once. The first call to max(arr) in the first iteration already consumes it for every subsequent iteration.
If you want the second largest number, just sort the array and get the second (or second-to-last, depending on how you order). This will also give you a O(nlogn) solution instead of the (potentially) O(n^2) solution that you have attempted to write.
The problem is that arr is an iterator, and you can only go through an iterator once.
You start off with [x for x in arr...] and x gets the value 1. You then take max(arr), and that's going to see the item 2, 3, 4, 5 and then use all of them up. It will return 5, but now the iterator is empty. Your outer [...] now sees that there are no more elements to look at, and returns max(1) = 1.
Related
This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
How to remove items from a list while iterating?
(25 answers)
Closed yesterday.
Was having fun with this task on code wars where on a given list as an input my function should find all of the zeroes and put them at the end of a given list maintaining the other numbers in the same order for example:
a = [1, 2, 0, 1, 0, 1] function should return a = [1, 2, 1, 1, 0, 0]
I wrote a code which in my VS code does the job but for some reason cant pass the initial tests (4/5).
The thing is on failed test where my function should return some values, IT ACTUALLY DOES, in my compiler but cant pass test??? I'm really confused. I did not want to look for solutions online...
Here is my code:
def zerotoanend(a:list):
b = []
for i in a:
if i==0:
b.append(0)
a.remove(i)
for zero in b:
a.append(zero)
return a
It is generally not a good idea to modify a list while iterating over it, as you can skip elements. Instead, you could count the number of zeros first, use a list comprehension to get all the non-zero elements, then add the required number of zeros to the end.
zeros = a.count(0)
return [x for x in a if x != 0] + [0] * zeros
This question already has answers here:
Understanding generators in Python
(13 answers)
Closed 1 year ago.
If range(0, 3) returns the sequence 0, 1, 2
then why can't I simply print this sequence using the following code:
x = range (0, 3)
print(x)
Why do I need to use a for loop to do so?
x = range (0, 3)
for i in x:
print(i)
How do I understand how the range function generates the sequence and stores it, making a iterating function necessary to access all the numbers in the sequence.
This is precisely beacause range is a generator; it doesn't return a list, it returns an iterable object whose next() method returns another item from the list it represents.
Of course, you can always
print(list(range(0, 3))
or
print(*range(0, 3))
range is a generator function not a list. To get values from a generator you need to iterate through the generator calling for the next value. A for loop does that.
range(0, 3) is a generator so the values are not actually produced until you loop over it.
You could cast it to a list to print:
x = range(0, 3)
print(list(x))
This question already has answers here:
Understanding slicing
(38 answers)
Closed 4 years ago.
Say I have a list arr and an index i within [0:len(arr)], how do I get all the elements starting from arr[i] up to arr[-1] in a Pythonic way?
For example:
arr = 'abcdef'
i = 3
I basically want to get b = 'def'
I tried
b = a[i:-1]
but obviously that'll leave out the last element.
Also, my list sometimes has only 1 element, so i = 0. How do I safely treat that edge case?
Thank you!
You could use python list slicing like this:
b = arr[i:] # This prints 'def' when arr = 'abcdef' and i = 3
This will print everything from the ith position to the end. And if i is greater than the string length, it'll print an empty string.
This question already has answers here:
Pythonic way to find maximum value and its index in a list?
(11 answers)
How does tuple comparison work in Python?
(4 answers)
Closed 7 days ago.
I have looked thoroughly, but have not found a clear (or roundabout) answer to the following question: How can I create a for loop that will allow me to find the greatest pair where x and y in (x,y) are greater than or equal to all other x's and y's in the list?
So, suppose I have a list of 20 pseudorandom integer ordered pairs and I want to find which ordered pair is the greatest using a for loop.
The code I currently have is:
np.random.seed(1234)
a = np.random.randint(0, 11,(20,2))
alst = list(allocationsset)
print alst
Where np is the imported form of numpy and which prints,
[[1,0],[8,9],[2,1],[3,2],[10,10] etc...]
Then, I attempt to make the for loop with the following function:
def dominantx (pairs):
def maxx (pairs):
maxlist = []
for [a,b] in pairs:
if a >= b:
maxlist.append([a,b])
return maxlist
dom = maxx(pairs)
domlist = []
for [a,b] in dom:
for [c,d] in dom:
if a > c:
domlist.append([a,b])
if a == c:
if b > d:
domlist.append([a,b])
if b == d:
domlist.append([a,b])
domlist.append([c,d])
else:
domlist.append([c,d])
else:
domlist.append([c,d])
return domlist
dominantx(alst)
I believe part of the problem I am having is replacing what is in "domlist" with the new greatest ordered pair and returning that as the answer, i.e. I don't want to append "domlist" with the new greatest ordered pair until I remove the old greatest ordered pair from domlist.
My first loop works fine, it is just the second for loop in defining dominantx where I am having trouble. I am relatively new to Python, so please forgive any simply fixes or errors. I am open to any suggestions that still implement a loop and, of course, any help is greatly appreciated. Thank you!
Just use max:
arr = [[1,0],[8,9],[2,1],[3,2],[10,10]]
print(max(arr))
[10, 10]
If you want actual pairs as in [1,1],[2,2] etc..
arr = [[1,1],[8,9],[2,2],[3,2],[13,10]]
pairs = [x for x in arr if x[0] == x[1]] # get all subelements with equal elements
print(max(pairs))
[2, 2]
This question already has answers here:
repeat an iteration of for loop
(4 answers)
Closed 8 years ago.
Not sure if this is possible, mostly a curiosity question although I may have a case where this may be useful. Basically I'm wondering if it's possible to not go to the next iteration in a loop, and instead try repeating that iteration. For example:
myList = ['a','b','c']
for thing in myList:
if something:
continue
else:
try again (same iteration)
Is what I'm asking for clear? A way I've seen of doing this is to use a while loop operating only on the first element of a list and then continuously deleting the first element of the list if some condition is met.
Thanks
You can use a while loop and manually substract from the iteration variable. Demo:
import time
myList = [1,2,3,4,5,6,7,8]
i = 0
while i < len(myList):
time.sleep(1)
print(i)
if i == 3:
i -= 1
i += 1
Of course, you'll need to access your thing by indexing into myList now, i.e. do something to/with myList[i].