Pygame object being loaded in twice [duplicate] - neural-network

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 7 years ago.
I have a list
a = ["a", "b", "c", "d", "e"]
I want to remove elements in this list in a for loop like below:
for item in a:
print(item)
a.remove(item)
But it doesn't work. What can I do?

You are not permitted to remove elements from the list while iterating over it using a for loop.
The best way to rewrite the code depends on what it is you're trying to do.
For example, your code is equivalent to:
for item in a:
print(item)
a[:] = []
Alternatively, you could use a while loop:
while a:
print(a.pop())
I'm trying to remove items if they match a condition. Then I go to next item.
You could copy every element that doesn't match the condition into a second list:
result = []
for item in a:
if condition is False:
result.append(item)
a = result
Alternatively, you could use filter or a list comprehension and assign the result back to a:
a = filter(lambda item:... , a)
or
a = [item for item in a if ...]
where ... stands for the condition that you need to check.

Iterate through a copy of the list:
>>> a = ["a", "b", "c", "d", "e"]
>>> for item in a[:]:
print(item)
if item == "b":
a.remove(item)
a
b
c
d
e
>>> print(a)
['a', 'c', 'd', 'e']

As other answers have said, the best way to do this involves making a new list - either iterate over a copy, or construct a list with only the elements you want and assign it back to the same variable. The difference between these depends on your use case, since they affect other variables for the original list differently (or, rather, the first affects them, the second doesn't).
If a copy isn't an option for some reason, you do have one other option that relies on an understanding of why modifying a list you're iterating breaks. List iteration works by keeping track of an index, incrementing it each time around the loop until it falls off the end of the list. So, if you remove at (or before) the current index, everything from that point until the end shifts one spot to the left. But the iterator doesn't know about this, and effectively skips the next element since it is now at the current index rather than the next one. However, removing things that are after the current index doesn't affect things.
This implies that if you iterate the list back to front, if you remove an item at the current index, everything to it's right shifts left - but that doesn't matter, since you've already dealt with all the elements to the right of the current position, and you're moving left - the next element to the left is unaffected by the change, and so the iterator gives you the element you expect.
TL;DR:
>>> a = list(range(5))
>>> for b in reversed(a):
if b == 3:
a.remove(b)
>>> a
[0, 1, 2, 4]
However, making a copy is usually better in terms of making your code easy to read. I only mention this possibility for sake of completeness.

import copy
a = ["a", "b", "c", "d", "e"]
b = copy.copy(a)
for item in a:
print(item)
b.remove(item)
a = copy.copy(b)
Works: to avoid changing the list you are iterating on, you make a copy of a, iterate over it and remove the items from b. Then you copy b (the altered copy) back to a.

How about creating a new list and adding elements you want to that new list. You cannot remove elements while iterating through a list

Probably a bit late to answer this but I just found this thread and I had created my own code for it previously...
list = [1,2,3,4,5]
deleteList = []
processNo = 0
for item in list:
if condition:
print(item)
deleteList.insert(0, processNo)
processNo += 1
if len(deleteList) > 0:
for item in deleteList:
del list[item]
It may be a long way of doing it but seems to work well. I create a second list that only holds numbers that relate to the list item to delete. Note the "insert" inserts the list item number at position 0 and pushes the remainder along so when deleting the items, the list is deleted from the highest number back to the lowest number so the list stays in sequence.

Related

Optimal Way to Achieve Traditional Loop Based Tasks in Scala

I am new to Scala and working on implementing an algorithm. In C#, this would have been a much easier task with necessary loops, but it is a bit confusing to implement with Scala functional programming semantics.
Assume I have to fill a spreadsheet (S) with N rows and M cols with values that I have in a one-dimensional list (L).
While filing an individual cell in the spreadsheet, there is a back and forth logic involved.
2a. The system will walk through the items in L sequentially and will fill the same in next empty cell in sheet S
2b. While filling the item value of the currently processed item from L in a cell, the system will check, can the current cell accept the item value. If yes, it will fill, and move on to the next item and follow Step 2a. If not, it will see if it could fill the next item from L. Until it finds a value that could fit in, the system will continue to evaluate till it runs out of values and will leave it blank.
2c. The system after filling the cell in Step 2b will move to the next cell. Now, it will first check whether any of the unprocessed values from the previous step (2b) could be accepted by the currently processed cell. If yes, it will fill the same and continue to do work with unprocessed values. If it cannot find an unprocessed value that could fit in, it will pull the next item from L based on the position of the pointer on Step 2b.
It would be great if I could get ideas of how-to structure this with Scala. As I mentioned earlier, in C# this would have been easy with foreach loops, but I am not sure what is the most optimal way to do this in a functional programming construct.
You can remember that imperative:
for (init; condition; afterEach) {
instructions
}
is just a syntactic sugar for:
init
while (condition) {
instructions
afterEach
}
(at least until you use break or continue). So if you are able to rewrite your for-loop code into while-loop code the translation is pretty straightforward.
If you are not interested in such solution you could do something like
val indices = for {
i <- (0 until n).toStream // or .to(LazyList) if on 2.13
j <- (0 until m).toStream // or .to(LazyList) if on 2.13
} yield i -> j
indices.foldLeft(allItemsToInsert) { case (itemsLeft, (i, j)) =>
itemsLeft.find(item => /* predicate if item can be inserted at (i, j) */) match {
case Some(item) =>
// insert item to spreadsheet
items diff List(1) // remove found element - use other data structure if you find this too costly
case None =>
items // nothing could be inserted, move on
}
}
This would go through all indices one after another, and then try to find the first element which can be inserted. If it does it would insert it and take it off the list, if it cannot be inserted move on.
You can tweak the logic to e.g. partition on items that can be inserted if there could be more than one:
indices.foldLeft(allItemsToInsert) { case (itemsLeft, (i, j)) =>
val (insertable, nonInsertable) = itemsLeft.partition(item => /* predicate if item can be inserted */)
// insert insertable
nonInsertable // pass non-insertable for the next indice
}
Alternatively you could also use tail recursion if you really need to go back and forth:
#scala.annotation.tailrec
def insertValues(items: List[Item], i: Int, j: Int): Unit = {
if (items.nonEmpty) {
// insert what you can into spreadsheet
val itemsLeft = ... // items that you haven't inserted
val newI, newJ = ...
insertValues(itemsLeft, newI, newJ)
}
}

how to get the values not repeated in the list? (Dart - Flutter)

I have two lists:
a = [1,2,3,4,5]
b = [1,4,5]
I want to get the values from list a that do not exist in list b:
result = [2,3]
There are various ways to achieve that and which one fits your situation depends on your requirements (which are not specified in the question).
Do you want to preserve duplicates in a or not:
a = [1,2,2,3,4,5]
b = [1,4,5]
Should this result in [2,3] or [2,2,3]?
If you do not want to preserve duplicates you can convert your lists to Sets and use the difference method:
result = a.toSet().difference(b.toSet())
Our if you want to preserve the duplicates just filter the list.
result = a.filter((v) => b.contains(v))

Ordering of Dictionary Swift

I'm trying to work through a problem at the moment which is currently doing the rounds on the internet. The problem is: Given an array of characters, find the first non repeating character. I had a go at it and solved it but I was curious about how other people solved it so I did some looking around and found this answer:
let characters = ["P","Q","R","S","T","P","R","A","T","B","C","P","P","P","P","P","C","P","P","J"]
var counts: [String: Int] = [:]
for character in characters {
counts[character] = (counts[character] ?? 0) + 1
}
let nonRepeatingCharacters = characters.filter({counts[$0] == 1})
let firstNonRepeatingCharacter = nonRepeatingCharacters.first!
print(firstNonRepeatingCharacter) //"Q"
Source: Finding the first non-repeating character in a String using Swift
What I don't understand about this solution, is why it always returns Q, when there are other elements "S" "A" "B" and "J" that could be put first when the filter is applied to the dictionary. My understanding of dictionaries is that they are unordered, and when you make one they change from run to run. So if I make one:
let dictionary:[String:Int] = ["P": 9, "C": 8, "E": 1]
And then print 'dictionary', the ordering will be different. Given this, can anyone explain why the solution above works and maintains the order in which the dictionary elements were added?
You are not looking correctly at the code. The filter is not applied to a dictionary. It is applied to the array (characters), which has a defined order. The dictionary is used only to store counts.

compare two lists to see what's missing

If I have two lists for example list1 and list2 how would I search list1 to see if there were any elements which were not in list2 then append it to list2. as an example here are both lists:
let list1 = ["James","John","fat","cart"]
var list2 = ["James","fat","bobby"]
therefore after the algorithm list2 would be:
["James","fat","bobby","John,"cart"]
for value in list1 {
if !list2.contains(value) {
list2.append(value)
}
}
OR
list1.forEach({ !list2.contains($0) ? list2.append($0) : nil })
OR
list2.append(contentsOf: Set(list1).subtracting(Set(list2)))
Use a foreach loop to iterate through the items in list1. If list2 does not contain an item, then append it to list2.*
You can do it one line coding
let list1 = ["James","John","fat","cart"]
var list2 = ["James","fat","bobby"]
list2.append(contentsOf: list1.filter{!list2.contains($0)})
print("\list2")
//output
["James", "fat", "bobby", "John", "cart"]
Most of the answers so far will have poor performance on large arrays.
The Array.contains(_:) method has O(n) performance, meaning that combining 2 arrays will have O(n•m) performance (where n is the number of items in one array and m is the number of items in the other array.) This the time performance will deteriorate exponentially as the arrays grow in size.
If you only need to deal with a handful of items, this doesn't matter. But with >= hundreds of items in the arrays the time performance will get bad fast.
Better to use Sets:
let list1 = ["James","John","fat","cart"]
var list2 = ["James","fat","bobby"]
list2 = Array(Set(list1).union(Set(list2)))
print(Set([list1, list2]))
print(list2)
Sets use hashes for contains/uniqueness testing, which runs in ≈ constant time.
Jorgandar's answer should have good time-performance as well, but mine is a little simpler and (I think) more straightforward to understand.
I just convert each array into a Set, combine them with Set.union(_:), and then convert the results back to a set.
If preserving the original order is important then you could build sets out of each array for uniqueness testing and then loop through one of the arrays using the sets to tell if each item needs to be added to the other array. That would be a little more complex but should give ≈O(n) performance and preserve array ordering.
You need to use Set like this way:
let list1 = ["James","John","fat","cart"]
let list2 = ["James","fat","bobby"]
let final = Array(Set([list1, list2].flatMap({$0})))
Or
let final = Array(Set(list1 + list2))

What does "rows[0]" mean?

HI! I am looking for a document that will define what the word "rows[0]" means. this is for BIRT in the Eclipse framework. Perhaps this is a Javascript word? I dunno... been searching like mad and have found nothing yet. Any ideas?
rows is a shortcut to dataSet.rows. Returns the current data rows (of type DataRow[]) for the data set associated with this report item instance. If this report element has no data set, this property is undefined.
Source: http://www.eclipse.org/birt/phoenix/ref/ROM_Scripting_SPEC.pdf
Typically code like rows[x] is accessing an element inside an array. Any intro to programming book should be able to define that for you.
rows[0] would be accessing the first element in the array.
That operation has several names depending on the language, but generally the same concept. In Java, it's an array access expression in C#, it's an indexer or array access operator. As with just about anything, C++ is more complicated, but basically the [] operator takes a collection of something or an array and pulls out (or assigns to) a specific numbered element in that collection or array (generally starting at 0). So in C# ...
// create a list of integers
List<int> lst = new List<int>() { 1, 2, 3, 4, 5 };
// access list
int x = lst[0]; // get the first element of the list, x = 1 afterwords
x = lst[2]; // get the third element of the list, x = 3 afterwords
x = lst[4]; // get the fifth element of the list, x = 5 afterwords
x = lst[5]; // IndexOutOfBounds Exception