I want to write a function in Python 3 that converts fractions given as numerator and denominator into their string representation as decimal number, but with repeating decimal places in brackets.
An example:
convert(1, 4) should output "0.25"
convert(1, 3) should output "0.(3)" instead of "0.3333333333"
convert(7, 11) should output "0.(63)" instead of "0.6363636364"
convert(29. 12) should output "2.41(6)" instead of "2.4166666667"
My current code is at the end of the question, but it fails if there are non-repeating and repeating decimal places. Here's an example run including the debug output (commented print calls):
----> 29 / 12
5
appended 4
2
appended 1
8
index 2 ['29', 2, 8] result ['2.', '4', '(', '1']
repeating 8
['2.', '4', '(', '1', ')']
What am I doing wrong here?
My code:
def convert(numerator, denominator):
#print("---->", numerator, "/", denominator)
result = [str(numerator//denominator) + "."]
subresults = [str(numerator)]
numerator %= denominator
while numerator != 0:
#print(numerator)
numerator *= 10
result_digit, numerator = divmod(numerator, denominator)
if numerator not in subresults:
subresults.append(numerator)
result.append(str(result_digit))
#print("appended", result_digit)
else:
result.insert(subresults.index(numerator), "(")
#print("index", subresults.index(numerator), subresults, "result", result)
result.append(")")
#print("repeating", numerator)
break
#print(result)
return "".join(result)
Your code just needed some minor changes (see the comments below):
def convert(numerator, denominator):
#print("---->", numerator, "/", denominator)
result = [str(numerator//denominator) + "."]
subresults = [numerator % denominator] ### changed ###
numerator %= denominator
while numerator != 0:
#print(numerator)
numerator *= 10
result_digit, numerator = divmod(numerator, denominator)
result.append(str(result_digit)) ### moved before if-statement
if numerator not in subresults:
subresults.append(numerator)
#print("appended", result_digit)
else:
result.insert(subresults.index(numerator) + 1, "(") ### added '+ 1'
#print("index", subresults.index(numerator), subresults, "result", result)
result.append(")")
#print("repeating", numerator)
break
#print(result)
return "".join(result)
I believe what is wrong is that you should only be checking if the number of decimal places previously seen is the number of the length of the cycle and it was seen just previous to this length.
I think the best way to do this would be to use some good ol' math.
Lets try and devise a way to find the decimal representation of fractions and how to know when there will be repeating decimals.
The best way to know if a fraction will terminate (or repeat) is to look at the factorization (hard problem) of the denominator.
There are many ways to find the factorization, but what we really want to know is, does this number have a prime factor other than 2 or 5. Why? Well a decimal expansion is just some number a / 10 * b. maybe 1/2 = .5 = 5/10. 1/20 = .05 = 5/100. etc.
So the factors of 10 are 2 and 5, so we want to find out if it has any other factors other than 2 and 5. Perfect, thats easy, just keep dividing by 2 until it is not divisible by 2 anymore, than do the same with 5. Or the other way around.
First we may want to find out if it is divisible by 2 or 5 before we start doing some serious work.
def div_by_a_or_b( a, b, number):
return not ( number % a ) or not ( number % b )
Then we divide out all the fives then all the twos and check if the number is 1
def powers_of_only_2_or_5(number):
numbers_to_check = [ 2, 5 ]
for n in numbers_to_check:
while not number % n: # while it is still divisible by n
number = number // n # divide it by n
return number == 1 # if it is 1 then it was only divisble by the numbers in numbers_to_check
I made this a bit more polymorphic so you can change this around if you want to change the base. (all you need is the factors of that base, for instance in base 14 you check 2 and 7 instead of 2 and 5)
Now all thats left to do is find out what we do in the case of non-terminating/repeating fractions.
Now this is super number theory filled, so i'll leave you with the algorithm and let you decide if you want to find out more on mathforum.org or wolfram alpha
Now that we can easily tell if a fraction will terminate and if not, what will be the length of its cycle of repeating digits. Now all thats left to do is find the cycle or how many digits it will start in.
In my search for an efficient algorithm, I found this post on https://softwareengineering.stackexchange.com/ which should be helpful.
some great insight - "When a rational number m/n with (m,n)=1 is expanded, the period begins after s terms and has length t, where s and t are the smallest numbers satisfying
10^s=10^(s+t) (mod n). "
So all we need to do is find s and t:
def length_of_cycle(denominator):
mods = {}
for i in range(denominator):
key = 10**i % denominator
if key in mods:
return [ mods[key], i ]
else:
mods[ key ] = i
Let's generate the numbers of the expansion
def expasionGenerator( numerator, denominator ):
while numerator:
yield numerator // denominator
numerator = ( numerator % denominator ) * 10
Now be careful about using this as it will create an infinite loop in a repeating expansion (as it should ).
Now I think we have all the tools in place to write our function:
def the_expansion( numerator, denominator ):
# will return a list of two elements, the first is the expansion
# the second is the repeating digits afterwards
# the first element's first
integer_part = [ numerator // denominator ]
numerator %= denominator
if div_by_a_or_b( 2, 5, denominator ) and powers_of_only_2_or_5( denominator ):
return [ integer_part, [ n for n in expasionGenerator( numerator, denominator ) ][1:], [0] ]
# if it is not, then it is repeating
from itertools import islice
length_of_cycle = cycleLength( denominator )
generator = expasionGenerator( numerator*10, denominator )
# multiply by 10 since we want to skip the parts before the decimal place
list_of_expansion = [ n for n in islice(generator, length_of_cycle[0]) ]
list_of_repeating = [ n for n in islice(generator, length_of_cycle[1]) ]
return [ integer_part, list_of_expansion, list_of_repeating ]
Now all thats left is to print it, that shouldn't be too bad. I am just going to build a function first that takes a list of numbers to a string:
def listOfNumbersToString(the_list):
string = ""
for n in the_list:
string += str(n)
return string
Then create the convert function:
def convert(numerator, denominator):
expansion = the_expansion(numerator,denominator)
expansion = [ listOfNumbersToString(ex) for ex in expansion ]
return expansion[0] + "." + expansion[1] + "(" + expansion[2] + ")"
interesting read on the topic at http://thestarman.pcministry.com/ and a similar-ish question on stackoverflow
This doesn't answer your actual question ("why isn't my code working?") but maybe it will be useful to you anyway. A few months ago I wrote some code to do the same thing you're trying to do now. Here it is.
import itertools
#finds the first number in the sequence (9, 99, 999, 9999, ...) that is divisible by x.
def first_divisible_repunit(x):
assert x%2 != 0 and x%5 != 0
for i in itertools.count(1):
repunit = int("9"*i)
if repunit % x == 0:
return repunit
#return information about the decimal representation of a rational number.
def form(numerator, denominator):
shift = 0
for x in (10,2,5):
while denominator % x == 0:
denominator //= x
numerator *= (10//x)
shift += 1
base = numerator // denominator
numerator = numerator % denominator
repunit = first_divisible_repunit(denominator)
repeat_part = numerator * (repunit // denominator)
repeat_size = len(str(repunit))
decimal_part = base % (10**shift)
integer_part = base // (10**shift)
return integer_part, decimal_part, shift, repeat_part, repeat_size
def printable_form(n,d):
integer_part, decimal_part, shift, repeat_part, repeat_size = form(n,d)
s = str(integer_part)
if not (decimal_part or repeat_part):
return s
s = s + "."
if decimal_part or shift:
s = s + "{:0{}}".format(decimal_part, shift)
if repeat_part:
s = s + "({:0{}})".format(repeat_part, repeat_size)
return s
test_cases = [
(1,4),
(1,3),
(7,11),
(29, 12),
(1, 9),
(2, 3),
(9, 11),
(7, 12),
(1, 81),
(22, 7),
(11, 23),
(1,97),
(5,6),
]
for n,d in test_cases:
print("{} / {} == {}".format(n, d, printable_form(n,d)))
Result:
1 / 4 == 0.25
1 / 3 == 0.(3)
7 / 11 == 0.(63)
29 / 12 == 2.41(6)
1 / 9 == 0.(1)
2 / 3 == 0.(6)
9 / 11 == 0.(81)
7 / 12 == 0.58(3)
1 / 81 == 0.(012345679)
22 / 7 == 3.(142857)
11 / 23 == 0.(4782608695652173913043)
1 / 97 == 0.(0103092783505154639175257
73195876288659793814432989690721649484
536082474226804123711340206185567)
5 / 6 == 0.8(3)
I forget exactly how it works... I think I was trying to reverse-engineer the process for finding the fraction form of a number, given its repeating decimal, which is much easier than the other way around. For example:
x = 3.(142857)
1000000*x = 3142857.(142857)
999999*x = 1000000*x - x
999999*x = 3142857.(142857) - 3.(142857)
999999*x = 3142854
x = 3142854 / 999999
x = 22 / 7
In theory, you can use the same approach going from fraction to decimal. The primary obstacle is that it's not completely trivial to turn an arbitrary fraction into something of the form "(some number) / (some amount of nines)". If your original denominator is divisible by 2 or 5, it can't evenly divide any 9-repunit. So a lot of form's work is about removing factors that would otherwise make it impossible to divide by 999...9.
The main idea is to find out the decimal place. In order word, where to put a decimal '.'
When a number is divided by 2 or 5, there is no recurring decimal. 1/2 = 0.5, 1/5 = 0.2. Only those are not 2 or not 5. eg. 3, 7, 11. How about 6? In fact, 6 is 2x3 where recurring decimal occurs due to the factor of 3. 1/6 = 1/2 - 1/3 = non recurring part + recurring part.
Take an other example 1/56. 56=8x7=2^3x7. Note that 1/56 = 1/7 - 1/8 = 1/7 - 1/2^3. There are 2 parts. The front part is 1/7 which is recurring 0.(142857), while the latter part 1/2^3 = 0.125 not recurring. However, 1/56 = 0.017(857142). 1/7 has recurring just after the '.' The recurring part for 1/56 is 3 decimal place later. This is because 0.125 has 3 decimal place and make it not recurring until 3 decimal place later. When we know where the recurring part starts, it is not hard to use long division to find out where the recurring's last digit.
Similar case for 5. Any fraction can have form like = a/2^m + b/5^n + recurring part. The recurring part is pushed rightward either by a/2^m or b/5^n. This is not hard to find out which ones push harder. Then we know where the recurring part starts.
For finding recurring decimal, we use long division. Since long divison will get the remainder, multiply the remainder by 10 and then use as a new nomerator and divide again. This process goes on and on. If the digit appear again. This is the end of the recurring.
Related
I'm learning to wrap my head around programming and have been given the following task:
The ISBN (International Standard Book Number) is made out of 10 digits.
z1z2z3z4z5z6z7z8z9z10
The last digit z10 is a check-digit. It's made like this: First, you create a kind of cross-sum with this formula:
s = 1 * z1 + 2 * z2 + 3 * z3 + 4 * z4 + 5 * z5 + 6 * z6 + 7 * z7 + 8 * z8 + 9 * z9
The check-digit z10 is the remainder of the integer division of s divided by 11. For the remainder 10 you write x or X. Example: For the ISBN 3826604237 you get the check-digit 7.
Calculation: 1*3+2*8+3*2+4*6+5*6+6*0+7*4+8*2+9*3 = 150
The remainder of the division of 150 and 11 is 7.
The code-solution given is as followed:
# isbn.py
number = int(input("Please enter a 9-digit number: "))
z9 = number % 10
number = number//10
z8 = number % 10
number = number//10
z7 = number % 10
number = number//10
z6 = number % 10
number = number//10
z5 = number % 10
number = number//10
z4 = number % 10
number = number//10
z3 = number % 10
number = number//10
z2 = number % 10
number = number//10
z1 = number
sum = z1+2*z2+3*z3+4*z4+5*z5+6*z6+7*z7+8*z8+9*z9
checkdigit = sum%11
print("\nCheckdigit:", checkdigit)
My question simply is: How does it work? Why do I have to calculate "number // 10" and "number % 10" and this all the time? Is there a name for this kind of algorithm, and if so, how is it called?
I'd appreciate any kind of answer for this and if it seems like the easiest thing for you and you feel like I'm wasting your time, I'm sorry. So far I understood pretty much anything I've learned thus far learning python, but this task seemed a bit hard (it was in a very early chapter of the book I'm studying on work) and I got stuck and didn't get this out of my head.
Thank you in advance and have a nice day!
The operation x % 10 is called 'modulus' and returns the remainder of the division by 10. You use it in your code to isolate the rightmost digit.
The next operation x // 10 is called 'integer division', that is, a division which returns integers only (the fractional part (if any) is cut off). Integer division by 10 on a decimal number corresponds to a rightshift by one digit so that the next digit is shifted into the rightmost place.
You repeat these 2 steps until the last digit is isolated. Then you perform the multiplications, and finally take the modulus of 11 (the remainder of the division by 11) to obtain the check digit.
This repetitive code cries for a loop. Just imagine you had to handle 100 digit numbers.
You are using % aka modulus and integer division // to get one digit a time.
It is easier to not convert the whole number into an integer and then extract the individual digits, but to process the inputted string character wise.
Throw in some input validation and you get:
while True:
# don't convert to int
# repeat until exactly 9 digits are given
number = input("Please enter a 9-digit number: ").strip()
if number.isdigit() and len(number) == 9:
break
# generator method - enumerate gives you the position and the value of each character
# i.e. for enumerate('123') you get (0,'1') then (1,'2') then (2,'3')
# the sum function adds up each given tuple but premultiplies the value with its (pos+1) as position inside strings start at 0 for the 1st character - it also
# converts each single character to its integer value
s1 = sum( (pos+1)*int(num) for pos,num in enumerate(number))
# s1 is a summed generator expression for this:
s2 = 0 # do not use sum - its a built-in functions name
for pos,num in enumerate(number):
s2 += (pos+1)*int(num)
print(s1,s2) # both are the same ;o)
checkdigit = s1%11
print("\nCheckdigit:", checkdigit)
For 382660423 you get:
150 150
Checkdigit: 7
It's began from modulo arytmetic. And module, length of ICBN and coefficients is just agreement, cause coefficients has no matter (by modulo arytmetic properties (if x mod y = 0, than k * x mod y = 0, where k is integer)).
def S(j, n):
k = 0
s = 0
left_sum = 0
while (k <= n):
denominator = 8k + j
numerator = pow(16, n-k, denominator)
left_sum = (left_sum + (numerator / denominator)) % 1.0
k += 1
right_sum = 0
k = n + 1
newt = 0
while 1:
numerator = pow(16, n-k)
denominator = 8k + j
check = numerator / denominator
right_sum = newt + check
if right_sum == check:
break
else:
newt = right_sum
k += 1
result = left_sum + (right_sum % 1.0)
return result
def pi(n):
n -= 1
x = (4*S(1, n) - 2*S(4, n) - S(5, n) - S(6, n)) % 1.0
I'm trying to find the nth digit of pi using the Bailey Borwein Plouffe algorithm. Because the algorithm uses hexadecimal, I need to convert it back into decimal. I found some code on Python fiddle that seems to do this properly:
return "%014x" % int(x * 16**14)
Could someone explain what this return statement is doing? Thank you.
This does not convert to decimal. If anything, it converts a decimal value to a hexadecimal string.
This is string formatting, usually used for output. The format specification is on the left, before the % separator; the value is on the right.
Value: x * 16**14 is x, shifted left 14 hex digits.
Format: %...x specifies unsigned hexadecimal.
014 specifies a minimum of 14 columns, zero-padded.
The resulting string is returned to the calling program.
To convert to decimal, you'll need to
Fix your posted code. This still has syntax errors.
Alter the base-specific code from hex to dec. This starts with changing the power base from 16 to 10.
If you get stuck, you can post your coding problem. In that case, please read and follow the posting guidelines in the help documentation, as suggested when you created this account. Minimal, complete, verifiable example applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem.
We should be able to paste your posted code into a text file and reproduce the problem you described.
How is it possible to extract the n-th digit of a number in Sagemath? We have to compute the 13787th digit from pi + e in Sagemath. My approach was the following:
sage: xi = e + pi
....: var1 = xi.n(digits=13786+1)
....: var2 = xi.n(digits=13787+1)
....: var3 = ((var2-var1) * 10^13787).trunc()
....: var3
0
Which gave me 0 back, however it should be 9.
The digit is indeed 9. But the subsequent digits are also 9: this part of decimal expansion goes ...9999237... Rounding rolls these 9s to 0s, carrying 1 to a higher digit.
So you need some extra digits in order to avoid the digit you are interested in from being affected by rounding. How many depends on the number; we don't know in advance if there isn't a sequence of one billion of 9s starting from that position. Here I use 10 extra digits
xi = e + pi
n = 13787
offset = 1 + floor(log(xi, 10)) # the first significant figure is not always the first digit after decimal dot, so we account for that
extra = 10
digit = int(str(xi.n(digits = n + offset + extra))[-1 - extra])
This returns 9. I think extracting with str is more reliable than subtracting two nearly-equal numbers and hoping there won't be additional loss of precition there.
Of course, including a magic number like 10 isn't reliable. Here is a better version, which starts with 10 extra digits but then increases the number until we no longer have 00000000... as a result.
xi = e + pi
n = 13787
offset = 1 + floor(log(xi, 10))
extra = 10
while True:
digits = str(xi.n(digits = n + offset + extra))[-1 - extra:]
if digits == "0" * len(digits):
extra *= 2
else:
digit = int(digits[0])
break
print(digit)
This will loop forever if the digits keep coming as 0, and rightly so: without actually knowing what the number is we can never be sure if the ...0000000... we get is not really ...999999999942... rounded up.
I have designed a code which will take a 'number' as an input from the user.
The number will be used to make a...
numerator = (3*number) - 2
and a denominator, which will be denominator = (4*n) + 1.
The code will also allow the user to choose how many times they want this sequence to go on after which the sum of all the fractions will be totaled and displayed.
Here is the Code I have:
l=int(input("How many times do you repeat this sequence?: "))
n=int(input("Enter a base number: "))
n1=n
n2=n
total=0
s = ''
def calculate(l,n,n1,n2,total,s):
for j in range(l):
s += "{}/{} + ".format(3*n1-2, 4*n2+1)
n1=n+n1
n2=n+n2
total=(((n*3)-2)/((4*n)+1))+total
print(s)
print(total)
calculate(l, n, n1, n2, total, s)
Now here are the two errors that I receive when I get the output for this code for example:
How many times do you repeat this sequence?: 2
Enter a base number: 1
1/5 + 4/9 +
0.4
The two Issues:
Since 4/9 is the last fraction, is there a way to get rid of that "+" addition sign at the end, because it just points to a blank space..
The total for the two fractions shows to be 0.4 which is incorrect, the total sum should be 1/5 + 4/9 = 0.2 + 0.44 = 0.64, I am unsure where I went astray when inputting my total sum formula above.
Any suggestions/comments would be appreciated!
A cheap way of removing the + would be to simply cut off the last character in the string: str[:-1].
As far a issue 2 goes, it looks like you want to use n1 and n2 instead of n.
As of now, you're getting 1/5(.2) + 1/5(.2) = .4
Instead of concatening a string like that, collect all the parts in a list and then join the items on the plus sign:
s = []
s.append('{}/{}'.format(1, 5))
s.append('{}/{}'.format(4, 9))
print(' + '.join(s)) # 1/5 + 4/9
I’m not really sure what you are doing but if you want to get the sum of the fractions you print, you should just make sure that you calculate those individual fractions in the same way. So instead of incrementing n1 and n2 first before calculating the sum, calculate the sum in the same way you did for the fraction output and only afterwards change those variables:
s.append("{}/{}".format(3 * n1 - 2, 4 * n2 + 1))
total += (3 * n1 - 2) / (4 * n2 + 1)
n1 += n
n2 += n
I dont know python but you could do the following to correct your logical errors.
to remove the '+' at the end, you can do something like below,
if j = l (implies last fraction)
dont include +
else
include +
While calculating total you are using 'n' value which always remains as your input value
total=(((n*3)-2)/((4*n)+1))+total
Here use n1 or n2
total=(((n1*3)-2)/((4*n2)+1))+total
An upside-down number is defined as:
An upside-down number is an integer where the i'th digit from the left plus the i'th digit from the right is
always equal to 10.
For example 13579 is an upside-down number since 1+9 = 10, 3+7 = 10 and (since
5 is both the 3rd digit from the left and from the right) 5+5 = 10.
The first few upside-down numbers, in numerical order, are 5, 19, 28, 37, … , 82, 91, 159, …
Task: Write a program to determine the nth upside-down number (in numerical order).
The input will consist of a single integer n (1 < n < 2^31). You should output a single integer giving the nth upside-down number.
My code:
def upsidecheck(tocheck):
intolist=list(map(int, str(tocheck)))
x=0
while x<(len(intolist)/2):
if (intolist[x]+intolist[len(intolist)-x-1])!= 10 :
return False
break
x+=1
return True
print("which nth upsidedownnumber do you want?")
nth=int(input())
y=0
answer=0
for x in range (1,(2**31)):
counter=upsidecheck(x)
if counter == True:y+=1
if y==nth:answer=x;break
print("the answeris",answer)
Performance issue:
This code is fine for numbers less than 100, however it needs to run within two seconds for numbers as large as '1234' which should yield an answer of '4995116'.
It does work but just takes too long (usually about 30 seconds). It needs to work within 2 seconds ;(
[Note: this is not for an exam/homework etc., it's just to help me prepare for an exam.]
First, we need a function to tell us which numbers are upside-down:
def is_ud(n):
digits = [int(ch) for ch in str(n)]
check = (len(digits) + 1) // 2
return all(digits[i] + digits[-1 - i] == 10 for i in range(check))
then let's generate some values and look for patterns:
ud = [i for i in range(10000000) if is_ud(i)]
for digits in range(1, 8):
lo, hi = 10 ** (digits - 1), (10 ** digits) - 1
answers = sum(lo <= n <= hi for n in ud)
print("{}: {}".format(digits, answers))
which gives
1: 1
2: 9
3: 9
4: 81
5: 81
6: 729
7: 729
so there are 81 4-digit solutions, and 729 6-digit solutions; this should make sense, because the 6-digit solutions look like "1" + (each 4-digit solution) + "9", "2" + (each 4-digit solution) + "8", ... "9" + (each 4-digit solution) + "1" - therefore, there are 9 6-digit solutions for every 4-digit solution (and if you generate them in this fashion you will be generating them in ascending order). Similarly, for each 4-digit solution, there is a corresponding 5-digit solution by sticking a 5 in the middle.
Looking at this table, you should now be able to see that if you want (for example) the 200th solution, it must have 6 digits; in fact, it must be the 19th 6-digit solution. More than this, because 19 < 81, it must look like "1" + the 19th 4-digit solution + "9"!
You now have everything you need to write a recursive solution to directly generate the Nth upside-down number. Good luck!
Since brute-forcing through all the numbers here is not an option, you need to first solve the mathematical problem:
Generate "upside-down" numbers in ascending order and,
If possible, determine how many "upside-down" numbers there are of a certain length since your index cap is pretty high to brute-force-generate even these.
For the 1st, "upside-down" numbers are:
of length 2n: a1...ana'n...a'1
of length 2n+1: a1...an5a'n...a'1
where ai is any digit except 0 and a'i is its 10-complement.
Since the numbers of the same length are compared digit by digit, guess which order will be the ascending one.
For the 2nd,
the number of "upside-down" numbers of length 2n or 2n+1 is both the number of all the possible combinations of a1...an.
since the previous expression is so simple, you can even work out a formula for the sum - the number of all "upside-down" numbers up to the length N.
The rest is pretty simple, i'd only add that divmod or // may come in handy for the resulting algorithm.
This is an interesting problem. The first part, as others have said, is that you want the nth number of any number of digits, so if you can find the total number of values with fewer digits you can subtract them from the value and ignore them.
Then you have a simpler problem: find the nth value with exactly k digits. If k is odd the central digit is '5', but otherwise the first half is simply the nth base 9 number but with digits expressed in the range 1..9. The tail is simply the same base 9 value with the digits reversed and using a range of 9..1 to represent values 0..8.
This function will convert a value to base 9 but with a specific character used to represent each digit:
def base9(n, size, digits):
result = []
for i in range(size):
result.append(n%9)
n //= 9
return ''.join(digits[i] for i in reversed(result))
So for example:
>>> print(base9(20, 3, "abcdefghi"))
acc
Now to print the nth upside down number with exactly k digits we convert to base 9 and insert a '5' if required.
def ud_fixed(n, k):
"""Upside down number of exactly k digits
0 => 1..159..9
1 => 1..258..9
and so on
"""
ln = k // 2
left = base9(n, ln, "123456789")
right = base9(n, ln, "987654321")[::-1]
if k%2:
return left + "5" + right
else:
return left + right
Now all we need to do is count how many shorter results there are and ignore them:
def upside_down(n):
number = [1, 9]
total = [1, 10]
if n==1: return "5"
while total[-1] < n:
number.append(9*number[-2])
total.append(total[-1]+number[-1])
length = len(total)
if length >= 2:
n -= total[length-2] # Ignore all the shorter results.
return ud_fixed(n-1, length)
Print some values to check:
if __name__=='__main__':
for i in range(1, 21):
print(i, upside_down(i))
print(1234, upside_down(1234))
Output looks like:
C:\Temp>u2d.py
1 5
2 19
3 28
4 37
5 46
6 55
7 64
8 73
9 82
10 91
11 159
12 258
13 357
14 456
15 555
16 654
17 753
18 852
19 951
20 1199
1234 4995116
Upside-down Numbers
Code is in a module, from which the OP can import the ud function.
% cat upside.py
# module variables
# a table with the values of n for which we have the greatest
# UD number of i digits
_t = [0, 1]
for i in range(1,11): last = _t[-1] ; d=9**i ; _t+=[last+d,last+d+d]
# a string with valid digits in our base 9 conversion
_d = '123456789'
def _b9(n,l):
# base 9 conversion using the numbers from 1 to 9
# note that we need a zero padding
s9 = []
while n : s9.append(_d[n%9]) ; n = n//9
while len(s9)<l: s9.append(_d[0]) # ZERO PADDING!
s9.reverse()
return ''.join(s9)
def _r9(s):
# reverse the first half of our UD number
return ''.join(str(10-int(c)) for c in s[::-1])
def ud(n):
# Error conditions
if n<1:raise ValueError, 'U-D numbers count starts from 1, current index is %d.'%(n,)
if n>_t[-1]:raise ValueError, 'n=%d is too large, current max is %d.'%(n,_t[-1])
# find length of the UD number searching in table _t
for i, j in enumerate(_t):
if n<=j: break
# the sequence number of n in all the OD numbers of length i
# note that to apply base9 conversion we have to count from 0,
# hence the final -1
dn = n-_t[i-1]-1
# now we compute the "shifted base 9" representation of the ordinal dn,
# taking into account the possible need for padding to a length of i//2
a = _b9(dn,i//2)
# we compute the string representing the OD number by using _r9 for
# the second part of the number and adding a '5' iff i is odd,
# we convert to int, done
return int(a+('5' if i%2 else '')+_r9(a))
%
Usage Example
Here it is an example of usage
% python
Python 2.7.8 (default, Oct 18 2014, 12:50:18)
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from upside import ud
>>> ud(1234)
4995116
>>> ud(7845264901)
999999999951111111111L
>>> ud(7845264902)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "upside.py", line 15, in ud
if n>_t[-1]:raise ValueError, 'n=%d is too large, current max is %d.'%(n,_t[-1])
ValueError: n=7845264902 is too large, current max is 7845264901.
>>> exit()
%
A small remark
Except for comments and error handling, ud(n) is amazingly short...
def ud(n):
for i, j in enumerate(_t):
if n<=j: break
dn = n-_t[i-1]-1
a = _b9(dn,i//2)
return int(a+('5' if i%2 else '')+_r9(a))