Hello,

I would like to stress that this is for personal practice and nothing school or assignment related.

The question:

Create a function countPages(x) that takes the number of pages of a book as an argument and counts the number of times the digit '1' appears in the page number.

(topic 5 - q 4 at pyschools.com)

My code:

def addNumbers(x):
    finalsum = list()
    theSum = 0
    i = 1
    while i <= x:
       theSum = theSum + i
       i = i + 1
       finalsum.append(theSum)
       return finalsum

I'm a beginner and I cannot seem to understand the reason of two things:

1) I'm trying to understand how to make it calculate the entire sum and produce one output. for example addnumber(10) = 55. with me it shows all the lists, and even if i do splicing (-1] it doesn't work.
2) why do I recieve a different output when i use "return" and "print" in this function?

could somebody please guide me through understanding this question? these concepts?

Thank you kindly.

Sorry, but I do not see the connection of your code and task as I understand it:

def one_count(n):
	return str(n).count('1')
def sum_of_ones(total):
	 return sum(one_count(page) for page in range(1,1+total))

print(sum_of_ones(10))
print(sum_of_ones(55))
""" Output:
2
16
"""

Hi.

It's under the while loop section of training so I reckoned I had to do this using a while loop.

I looked at your code and I am not even near that level :( lol

You can use while loop if you like, makes simpler to come down from last page then:

def one_count(n):
    return str(n).count('1')

def sum_of_ones(total):
    count = 0
    while total>0:
        count += one_count(total)
        total -= 1
    return count

print(sum_of_ones(10))
print(sum_of_ones(55))

""" Output:
2
16
"""

If you need more while, you can do away using str function and do the count by modulo arithmetic:

def one_count(n):
    count = 0
    while n>0:
        n, r = divmod(n, 10)
        count += r == 1
    return count

def sum_of_ones(total):
    count = 0
    while total>0:
        count += one_count(total)
        total -= 1
    return count

print(sum_of_ones(10))
print(sum_of_ones(55))

""" Output:
2
16
"""
Member Avatar for Enalicho

The way you should do it with a while loop and using a str method is -

def countPages(number_of_pages):
    total_number_of_ones = 0
    current_page = 1
    while current_page <= number_of_pages:
         page_number = str(current_page)
         total_number_of_ones += page_number.count('1')
         current_page  += 1
    return total_number_of_ones

I wouldn't recommend pyTony's method using -=1 as it is counter-intuitive (unless your language reads from the back of the book to the front, of course).

Of course, like many things in Python, this would be much better achieved through a for loop -

def countPages(number_of_pages):
    total_number_of_ones = 0
    for page_number in xrange(1,number_of_pages+1):
        total_number_of_ones += str(page_number).count('1')
    return total_number_of_ones

1) I'm trying to understand how to make it calculate the entire sum and produce one output. for example addnumber(10) = 55. with me it shows all the lists, and even if i do splicing (-1] it doesn't work.

Your code doesn't match your question :S I think you must mean topic 5 question 1. So my answers below are targeted for that -

That's because your code appends "theSum" to the list finalsum - not quite what you want, what you want to do is to add the current number to the integer finalsum.

2) why do I recieve a different output when i use "return" and "print" in this function?

Because your return statement is inside the while loop, it will return after running through the loop just once. print will continue to work for every time you run the while loop, running until i>x.

This question is again something that could use a for loop (and should use a for loop), but it is easy in while too. I suggest you start again, and read the question to really understand what it is asking.

def count_pages(number_of_pages):
    total_number_of_ones = 0
    current_page = 1
    while current_page <= number_of_pages:
         page_number = str(current_page)
         total_number_of_ones += page_number.count('1')
         current_page  += 1
    return total_number_of_ones

This version is probably the most intuitive for a beginner learning while loops. I'd like to walk through this with you, just to help you understand the concepts.

First off, notice how easy it is to tell what the variables in this method are doing. I did not write this method, but I can tell what each variable is used for based on its name. Try to emulate this. This will help you--in any language--as you write more complex code.

I trust the first two lines of the method (lines 2 and 3 of the code snippet) are clear enough, so I'll start with the while loop. If not, don't hesitate to ask.

while current_page <= number_of_pages:

Starting at current_page = 1, run through this loop until current_page is NOT less than or equal to number_of_page, or in other words, until we run out of pages. Notice that number_of_pages is the number we passed to the method.

page_number = str(current_page)

This line can be a bit tricky. str(current_page) converts current_page to a string. We save this string to the variable page_number. The reason we do this is seen in the next line.

total_number_of_ones += page_number.count('1')

First, let's talk about the page_number.count('1') portion of this line. count() is a method that is used for strings which counts how many times another string occurs within the original string. This is perfectly suited for our purpose! We can use this to count how many times the string '1' occurs within the current_page. Notice that this ' ' surrounds the number 1. We are passing the count() a string that contains the digit 1, not an integer 1, because that is what count() is expecting us to give it.
Also, take not of the += in the middle of the above statement. This does something very useful. += is a shorthand way of saying total_number_of_ones = total_number_of_ones + page_number.count('1'). If we used total_number_of_ones = page_number.count('1'), then total_number_of_ones would always be reset to the number of ones in the current page number. Using += is a very easy way to create a variable that keeps track of the sum of something.

current_page  += 1

This line is a "gotcha" for programming beginners. If you forget to increment this, current_page <= number_of_pages from the while loop will never stop -- your while loop will run forever!

return total_number_of_ones

This line tells Python to give, or return, the expression -- here total_number_of_ones -- to whatever called the method. For example, if you used this statement in a different method,

print count_pages(20)

the total_number_of_ones inside count_pages() is given to the print statement to print out. If you don't return total_number_of_ones, print will not be given anything to print and will simply print None.

I hope this write-up helped you understand while loops!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.