Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. """
  2. A Little program that prints every pair of numbers that has an even product and an odd sum.
  3.  
  4. Assumes that pairs such as (3, 7) and (7, 3) are the same thing.
  5. Also assumes that their are no re
  6.  
  7. Note this is definitely not an efficient solution to the problem. It is a
  8. simpler approach with the intentions of demonstrating fundamental programming concepts.
  9.  
  10. I recognise that not all of you may be beginners and I encourage those of you that aren't to think about how
  11. you could improve this code to make it more efficient. I would love to see how you approach this.
  12.  
  13. """
  14.  
  15. data = input("please enter the numbers (separated by ',') : ")
  16.  
  17. numbers = data.split(",") # splits the string into an array of strings. Splits the string wherever a "," occurs.
  18.  
  19. count = len(numbers) # len(list) is a function that returns the number of items in a list aka how "long" a list is.
  20.  
  21.  
  22. # A nested loop, since we need to compare every item to every other item in the list.
  23. # Complexity : O(N^2) Don't worry if you don't know what this is. You will learn about this in FIT1045 and FIT1008.
  24. # Ask me about it if you're curious.
  25. for i in range(count):
  26.  
  27. # The reason j only goes from i to count is to prevent numbers from all being compared twice.
  28. # Since (7,3) and (3,7) are the same pair.
  29. #
  30. # Try removing "i+1" and see how this changes the output : "range(0, count)" instead of "range(i+1, count)"
  31. for j in range(i + 1, count):
  32.  
  33. num1 = int(numbers[i]) # numbers need to be converted into integers since they were input as a string.
  34. num2 = int(numbers[j]) # this is an important concept, please ask for help if you are confused.
  35.  
  36. product = num1 * num2
  37. summation = num1 + num2 # sum is a reserved keyword in python so "summation" was used instead.
  38.  
  39. # if the product(mod 2) = 0 and the summation(mod 2) = 1 then the product is even and the summation is odd.
  40. # the modulo operator is simply the remainder of a division eg: 5 % 4 = 1 and 8 % 2 = 0.
  41. if product % 2 == 0 and summation % 2 == 1:
  42. print(num1, ",", num2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement