Counting Python: 1 to n

January 04, 2021

There are several ways one could go about solving this simple HackerRank problem, so I thought I'd show my solution and also include helpful resources I found.

 Print Function Read an integer N. Without using any string methods, try to print the following: 123...N  Note that "..." represents the values in between. Input Format The first line contains an integer N.  Output Format Output the answer as explained in the task. Sample Input 0 3 Sample Output 0 123

def one_to_n(n)
    n = int(n)
    values = list(range(1, n+1))
    values_to_str = ''.join(map(str, values))
    return values_to_str

There were two awesome articles I read to solve this and both were written by GeekForGeeks.com:

Python | Create list of numbers with given range

Python program to convert a list to string

How I solved this:

After reading the prompt, I knew I wanted to create a while loop or a range. I've been experiencing more range() related problems, and so I'm going with a hunch that's needed here. I looked up "Python 3 create list using range" and it lead me to the first link listed above. As the article details, there's are many different ways to go about this! I really liked list(range(1, n+1)) because it was short but very readable.

Next, I had to figure out how to take the list and turn it into a string. This proved a little tricky because I didn't anticipate the need to convert list as well as the list's values (which are integers). Using map was great because I can do these two conversions in one line. ''.join(map(str, values)) we are mapping the values from being integers to becoming strings. Next, we take those and join them together using the given string of '' (which essentially means no spaces between what we're joining).