Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
August 13th, 2013, 04:24 AM
 umarus
Registered User

Join Date: Jul 2013
Posts: 3
Time spent in forums: 22 m 3 sec
Reputation Power: 0
Int to Str

Hi,
I have an input less than 99
I need a result that will show two digit output
eg 05 if input 5, 13 if input 13.
Because it is only starting course I cannot use if, only use arithmetic operations and greatest integer (//) and remainder (%).
I am very confused

#2
August 13th, 2013, 08:38 AM
 b49P23TIvg
Contributing User

Join Date: Aug 2011
Posts: 4,147
Time spent in forums: 1 Month 3 Weeks 2 Days 7 h 44 m 41 sec
Reputation Power: 455
Omitting the theory lesson about representation of numbers and that Intel processors are designed to be really good at finding remainders leaves us with only the solution. After viewing these answers I'm sure you'll agree that the program would be worse with an "if" statement. "if" could work though.
Code:
# 3 solutions

for i in (5,27,):
print('\n'*2)

print('%d%d'%divmod(i,10), 'divmod')

ones = i % 10   # remainder after dividing by 10
tens = int(i/10) # works with both modern versions of python.  If you're feeling advanced look up the // operator.
print('{}{}'.format(tens,ones), 'explicit divmod')

print('{:0>2d}'.format(i), 'string formatting')
__________________
[code]Code tags[/code] are essential for python code!

#3
August 13th, 2013, 10:06 AM
 umarus
Registered User

Join Date: Jul 2013
Posts: 3
Time spent in forums: 22 m 3 sec
Reputation Power: 0
Thanks, but found this
Code:
print( str(n//10)+str(n%10))
b49P23TIvg agrees: yup, that works too. I'll bet divmod is faster.

#4
August 14th, 2013, 10:55 PM
 b49P23TIvg
Contributing User

Join Date: Aug 2011
Posts: 4,147
Time spent in forums: 1 Month 3 Weeks 2 Days 7 h 44 m 41 sec
Reputation Power: 455
know the builtin methods!

Another solution:

'{}'.format(n).zfill(2)

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > Int to Str