1

I'm working on the same assignment linked below.

(Mo' Money- Making an "algorithm" to solve two variable algebra problems)

I have tried the below solution to the linked assignment.

for fifties in range(161):
      tens = 160 - fifties
      if 50*fifties + 10*tens == 1760:
           break

I encountered the same issues I'm having with my code:

1.The below code ends with "break" and will not print the value of "fifties" and "tens"

2.When I manually print the values fifties always prints with a value of 160.

My code is below.

for tens in range(161,-1):
  fifty = (160 - 10*tens)/50 
  if 10*tens + 50*fifty == 1760:
     print(tens,fifty)

Candy
  • 21
  • 6

1 Answers1

0

First off, range(161,-1) won't iterate on any items because the first argument start is greater than the second argument end. Just do range(161).

Another thing is, you're not using your variables consistent with the units they are meant to represent. I'll explain while stepping through your script:

for tens in range(161):

Here, you're attempting different number of ten dollar bills - from 0 to 160. Looking good (now that we've stopped iterating on nothing).

    fifty = (160 - 10*tens)/50

Now, this doesn't make sense. 10*tens is the dollar value of how many tens you are trying. why are you subtracting that from 160 -the total number of bills? These are two completely unlike units and it makes no sense to subtract them. Instead, just subtract the number of tens from the total number of bills to get a number of fifties with fifty = 160 - tens

    if 10*tens + 50*fifty == 1760:
        print(tens,fifty)

Assuming tens and fifty means the number of each type of bill - which the previous point covered - this is fine.

So, altogether, your code will print the correct values of tens & fifty if it looks like this:

for tens in range(161):
    fifty = 160 - tens
    if 10*tens + 50*fifty == 1760:
        print(tens,fifty)

The solution uses break because doing that quits the loop so that the values of tens and fifty are correct and the rest of the program can use them. As the above code is, fifty and tens would continue to change even after a solution is found. Using break is a straightforward way of keeping the values after you've found a solution.

Ruzihm
  • 19,749
  • 5
  • 36
  • 48
  • 1
    Oh my goodness did I make a mess of that just trying to figure out how to make it print. thought the issue was range starting at 160, so I thought adding a -1 step **sigh, I'm a noob** Truly appreciate your help and the detailed explanation!! – Candy Oct 24 '19 at 14:49
  • @Candy You could have it count down (although it won't change the results here :] ) If you give `range` 3 arguments, the third says how much to change with each step. So you could do `for tens in range(160, -1, -1):` and it would count down from 160 (inclusive) to -1 (exclusive) going down by one each iteration. [See here for more info](https://stackoverflow.com/q/869885/1092820) – Ruzihm Oct 24 '19 at 15:47