ProfRose - 27 days ago 5x

Python Question

I'm taking a Python course at Udacity, and I'm trying to work this out for myself without looking at the answer. Perhaps you can give me a hint for my logic?

Below are the instructions and what I have so far. We haven't learned conditional statements yet, so I can't use those. We've only learned how to assign/print a variable, strings, indexing strings, sub-sequences, and .find. They just introduced the str command in this final exercise.

`# Given a variable, x, that stores the`

# value of any decimal number, write Python

# code that prints out the nearest whole

# number to x.

# If x is exactly half way between two

# whole numbers, round up, so

# 3.5 rounds to 4 and 2.5 rounds to 3.

# You may assume x is not negative.

# Hint: The str function can convert any number into a string.

# eg str(89) converts the number 89 to the string '89'

# Along with the str function, this problem can be solved

# using just the information introduced in unit 1.

# x = 3.14159

# >>> 3 (not 3.0)

# x = 27.63

# >>> 28 (not 28.0)

# x = 3.5

# >>> 4 (not 4.0)

x = 3.54159

#ENTER CODE BELOW HERE

x = str(x)

dec = x.find('.')

tenth = dec + 1

print x[0:dec]

////

So this gets me to print the characters up to the decimal point, but I can't figure out how to have the computer check whether "tenth" is > 4 or < 5

I figured I could probably get far enough for it to return a -1 if "tenth" wasn't > 4, but I don't know how I can get it to print x[0:dec]

:/

Could someone please give me a nudge in the right direction?

Answer

This is a weird restriction, but you could do this:

```
x = str(x)
dec_index = x.find('.')
tenth_index = dec_index + 1
tenth_place = x[tenth_index] # will be a string of length 1
should_round_up = 5 + tenth_place.find('5') + tenth_place.find('6') + tenth_place.find('7') + tenth_place.find('8') + tenth_place.find('9')
print int(x[0:dec_index]) + should_round_up
```

What we do is look at the tenths place. Since `.find()`

returns -1 if the argument isn't found, the sum of the `.find()`

calls will be -4 if if the tenths place is 5, 6, 7, 8, or 9 (since one of the `.find()`

calls will succeed and return `0`

), but will be -5 if the tenths place is 0, 1, 2, 3, or 4. We add 5 to that, so that `should_round_up`

equals 1 if we should round up, and 0 otherwise. Add that to the whole number part, and we're done.

That said, if you weren't subject to this artificial restriction, you would do:

```
print round(x)
```

And move on with your life.

Source (Stackoverflow)

Comments