Say you have a list of n items e.g.
seq = [1,2,3]
Find products of all items with each other
This is the simplest question.
Solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
seq = [1,2,3] | |
n=len(seq) | |
for i in range(n): | |
for j in range(n): | |
print "%s * %s = %s"%(seq[i],seq[j],seq[i]*seq[j]) |
This gives the following output:
1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
Find unique products of the items with each other
This means that you need that you can only have 1*2 or 2*1 etc
Solution: Really simple to do. Each time in the inner loop start at i rather than 0 as shown:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
seq = [1,2,3] | |
n=len(seq) | |
for i in range(n): | |
for j in range(i,n): | |
print "%s * %s = %s"%(seq[i],seq[j],seq[i]*seq[j]) |
This gives the following output:
1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 2 * 2 = 4 2 * 3 = 6 3 * 3 = 9Basically notice at each increment of i we do not allow j to go back.
Find unique products and do not multiply a list item with itself
This means that you cannot have 1*1 , 2*2 etc.
Solution: In the inner loop you need to avoid starting at i and rather start at i+1 (since this is the i*i case we need to avoid).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
seq = [1,2,3] | |
n=len(seq) | |
for i in range(n): | |
for j in range(i+1,n): | |
print "%s * %s = %s"%(seq[i],seq[j],seq[i]*seq[j]) |
Also if this is all you do at i = n the inner loop will not run so its better to stop the outer loop at n-1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
seq = [1,2,3] | |
n=len(seq) | |
for i in range(n-1): | |
for j in range(i+1,n): | |
print "%s * %s = %s"%(seq[i],seq[j],seq[i]*seq[j]) |
In both cases the output will be:
1 * 2 = 2 1 * 3 = 3 2 * 3 = 6Enjoy!
No comments:
Post a Comment