Solve "find pairs for sum"
I have encountered this problem 3x in the wild thus far: 1. www.InterviewCake.com 2. Cracking the Coding Interview 3. www.Pramp.com
This commit is contained in:
		
							parent
							
								
									92ab94943e
								
							
						
					
					
						commit
						ff08b723db
					
				
					 1 changed files with 19 additions and 0 deletions
				
			
		
							
								
								
									
										19
									
								
								scratch/facebook/moderate/find-pairs-for-sum.py
									
										
									
									
									
										Normal file
									
								
							
							
						
						
									
										19
									
								
								scratch/facebook/moderate/find-pairs-for-sum.py
									
										
									
									
									
										Normal file
									
								
							|  | @ -0,0 +1,19 @@ | ||||||
|  | import random | ||||||
|  | 
 | ||||||
|  | def find_pairs(xs, n): | ||||||
|  |     """ | ||||||
|  |     Return all pairs of integers in `xs` that sum to `n`. | ||||||
|  |     """ | ||||||
|  |     seeking = set() | ||||||
|  |     result = set() | ||||||
|  |     for x in xs: | ||||||
|  |         if x in seeking: | ||||||
|  |             result.add((n - x, x)) | ||||||
|  |         else: | ||||||
|  |             seeking.add(n - x) | ||||||
|  |     return result | ||||||
|  | 
 | ||||||
|  | xs = [random.randint(1, 10) for _ in range(10)] | ||||||
|  | n = random.randint(1, 10) + random.randint(1, 10) | ||||||
|  | print("Seeking all pairs in {} for {}...".format(xs, n)) | ||||||
|  | print(find_pairs(xs, n)) | ||||||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue