-2
\$\begingroup\$

I’m a complete beginner. I was practicing from coding bat and the question was to create a function that will round 3 integers to the nearest 10 and then find their summation. I thought of a way to do it and it’s given in the picture below. Please help.

def round10(num):
       return           # This will return the rounded number 
def sum(a,b,c) 
     return round10(a) + round10(b) + round10(c)

enter image description here

\$\endgroup\$
4
  • 3
    \$\begingroup\$ Welcome to Code Review. Code Review is a place to help improve your code after you have successfully implemented and tested it. Questions asking for advice on code yet to be written or implemented are off-topic for this site and will be closed. See What topics can I ask about? for reference. \$\endgroup\$
    – L. F.
    Commented Apr 11, 2020 at 7:31
  • 1
    \$\begingroup\$ Please include the code as actual code, not as a picture. Does or doesn't it work as intended? \$\endgroup\$
    – Mast
    Commented Apr 11, 2020 at 13:26
  • \$\begingroup\$ Sorry about the picture. The code I wrote in the picture doesn’t work. I didn’t know that integers themselves were immutable. The answer given by Jono 2906 works perfectly. \$\endgroup\$
    – Bum Bum
    Commented Apr 11, 2020 at 16:20
  • 1
    \$\begingroup\$ To note, the first close reason has a bad name in this case - Authorship of code. We know you're the author, however you haven't embedded the code into the question in a format all users can digest. For instance the bright background is causing my eyes to hurt when trying to read your image. This is only worse for our blind users that can't see. \$\endgroup\$
    – Peilonrayz
    Commented Apr 12, 2020 at 0:28

1 Answer 1

1
\$\begingroup\$

There is a potential here to mangle type conversions

I noticed that you are trying to manipulate integers in ways only strings and other iterables can: both len(num) and num[0]/num[-1] will give you a TypeError. In order to prevent that from happening, you would need to first convert the number to a string and then to a list:

def round10(num):
    number = list(str(num))

Try it online!

However, a further problem arises from the fact that integers cannot be subtracted from strings (once again, TypeError), so each list item needs to be converted to an integer:

def round10(num):
    number = list(str(number))
    for i in range(len(number)): # Doable because num is a list
        number[i] = int(number[i])

Try it online!

Then, once all the logic has been applied, it needs to be converted back to an integer. This means that you would have to convert the list to a single string and call int() on that string:

def round10(num):
    number = list(str(num))
    for i in range(len(number)): # Doable because num is a list
        number[i] = int(number[i])

    if len(number) < 2 and num >= 5:
        number = [1, 0]

    elif len(number) > 2 and number[-1] >= 5:
        number[0] += 1
        number[-1] = 0

    else:
        number[0] -= 1
        number[-1] = 0

    final = ""
    for n in number:
        final += str(n)

    # Here, I'd use final = "".join([str(n) for n in number])

    return int(final)

Try it online!

As you can see, there is quite a potential to confuse all the types in use.

There are logic errors within your if-statements

If you go to the Try It Online! link from the above function, you'll see that there are issues with your logic:

  1. Numbers with more than one digit round incorrectly.
  2. The number 10 gets rounded to 0.
  3. If the last digit is less than five, then the number gets rounded down too far.
  4. Very important: If a number happens to round up to the next hundred (e.g. 599 -> 600), then there is no incrementation of the rest of the number.

Below is a fixed version of your proposed method that works for numbers up to 194:

def round10(num):
    number = list(str(num))
    for i in range(len(number)): # Doable because num is a list
        number[i] = int(number[i])

    if len(number) < 2 and num >= 5:
        number = [1, 0]

    elif len(number) >= 2 and number[-1] >= 5:
        number[-2] += 1
        number[-1] = 0

    else:
        number[-1] = 0

    final = ""
    for n in number:
        final += str(n)

    # Here, I'd use final = "".join([str(n) for n in number])

    return int(final)

Try it online!

Changes:

  • elif len(number) > 2 and number[-1] >= 5: has been changed to elif len(number) >= 2 and number[-1] >= 5:. This fixes the issue where numbers with two or more digits do not round correctly.
  • I have removed number[0] -= 1 from the else block in order to address points 2 and 3

Notice how I haven't addressed issue 4. That's because I feel like implementing such a system would be beyond the scope of the CodingBat challenge.

That's because there is a simpler way to do this

Indeed, I suggest that instead of relying on string manipulation, you utilise mathematics to do the rounding for you.

Use the modulus (%) operator

The % operator returns the remainder of the first number divided by the second. This can be used to see how far the number is from the nearest 10:

def round10(num):
    distance = num % 10

Try it online!

Then, if the distance from the nearest 10 is greater than or equal to 5, simply add 10 minus that distance onto the original number. Otherwise, subtract 10 minus that distance from the original number:

def round10(num):
    if num % 10 >= 5: 
        return num + (10 - (num % 10))
    else:
        return num - (10 - (num % 10))

Try it online!

A Minor Point

I assume that CodingBat wants the function that performs the summing to be called sum. In that case, you can't really change it. But if this were in a proper program, I would strongly recommend you change the function name. Why? To avoid "masking" (that is, overwriting) the built-in function called sum.

\$\endgroup\$
5
  • 1
    \$\begingroup\$ Thank you soo much man. I’m really grateful. I’m only 15 and I started learning from freecodecamp 4 days ago. Again, thank you . \$\endgroup\$
    – Bum Bum
    Commented Apr 11, 2020 at 10:43
  • \$\begingroup\$ Glad I could help! \$\endgroup\$
    – lyxal
    Commented Apr 11, 2020 at 11:51
  • \$\begingroup\$ I was wondering whether you could give me some advice on programming. I started off with python and I’ve learnt some of the basics. What do you think is the best way to learn python and what strategies should I use while solving problems? And what language should I learn next if I (somehow) finish learning python? Any tips will help . I really appreciate your help, stay safe m8. \$\endgroup\$
    – Bum Bum
    Commented Apr 11, 2020 at 16:36
  • \$\begingroup\$ @BumBum I believe the best way to learn python (and any language for that matter) is through practice. Online tutorials are a great way to learn the basics, but I suggest that you also "experiment" with what is being taught - once you feel you have a basic understanding of a concept, open a program like IDLE and play around with what you've learnt. In regards to the best way to approach problems, I suggest that before you write any code, you take a moment to plan your approach. Doing so will help you think critically about what needs to be written. \$\endgroup\$
    – lyxal
    Commented Apr 12, 2020 at 0:10
  • \$\begingroup\$ @BumBum in regards to what to do after Python, I suggest that you move onto a language which has explicit data typing (such as C++). Doing so will help you fully understand the interactions between objects such as integers and strings. It will also give you exposure to other concepts that Python doesn't necessarily teach (such as memory manipulation, or advanced OOP). Hopefully that helps! \$\endgroup\$
    – lyxal
    Commented Apr 12, 2020 at 0:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.