# For loops 5 - set iteration¶

Browse file online

Given a set, we can examinate the element sequence with a for cycle.

WARNING: sets iteration order is not predictable !

To better understand why, you can see again the tutorial on sets

[2]:

for word in {'this', 'is', 'a', 'set'}:
print(word)

set
a
this
is

[3]:

s = set()
print(s)

{'nium', 'de', 'pan', 'mo'}


### Questions - sets¶

Look at the following code fragments, and for each try guessing the result it produces (or if it gives an error):

1. s = set()
print(s)

2. for x in {'a',12,'34',56,34}[2:4]:
print(x)

3. for x in set(['a']) | set(['b']):
print(x)

4. for x in set(['a']) & set(['b']):
print(x)


## Exercise - Screwed¶

The multinational ToxiCorp produces electrical appliances which are designed on purpose to break after a couple of years usage. When that happens, their components require very special tools only the corporation possess. Customers are then forced to go to repair workshops affiliated with ToxiCorp, and pay extra money. Over time the corporation has developed so many special shapes for screws that now its workshops have trouble managing all needed screwdrivers, so they ask you to devise a software to tell workshops which crewdrivers they are missing. You find it questionable, but they pay well, so you accept.

Each screw is star shaped, and is defined by a radius and a certain number of tips. We can represent it as a two elements list like [3,7] where 3 is the radius and 7 the number of tips. Each screwdrivers is also defined as a two elements list with the values of the radius and tips it can screw.

A workshop has in store a list of screws and a list of screwdrivers: write some code that prints a sorted list of the screwdrivers which are missing in order to be able to handle all the screw types.

Example - given:

screws = [[5,8], [7,4], [2,9], [8,2], [7,4],[2,6], [8,3], [2,6], [8,3], [8,3], [5,8]]
screwdrivers = [[8,2], [1,3], [5,8], [2,5], [1,3]]


Required screwdrivers: [(2, 6), (2, 9), (7, 4), (8, 3)]

• Notice input lists may have duplicates

• DO NOT use list methods or operators which search stuff

• so no .index, .find, in … they’re slow!

• DO NOT use nested loops… they would probably be slow !

Show solution
[4]:


screws = [[5,8], [7,4], [2,9],[8,2], [7,4],[2,6], [8,3],
[2,6], [8,3], [8,3], [5,8]]

screwdrivers = [[8,2], [1,3], [5,8], [2,5], [1,3]]

# write here



## Continue¶

Go on with for and dictionaries

[ ]: