Calculate the sequence of continuous numbers - python

I'm trying to find a way to calculate the amount of continuous digits on a given number. IE Number 7 has 7 continuous digits, while number 10 has 11 continuous digits. Here's an image to depict the problem
The first row shows the sequence and the second one shows the amount of numbers this has.
This has to be on python, but any ideas will help

Here is my attempt at understanding your question.
def continuous_digits(x):
count = 0
for i in range(1,x+1):
s = str(i)
count += len(s)
return count
# Test the function
for i in range(7,12):
print(f'Number: {i}: Continuous Digit Length: {continuous_digits(i)}')
The output:
Number: 7: Continuous Digit Length: 7
Number: 8: Continuous Digit Length: 8
Number: 9: Continuous Digit Length: 9
Number: 10: Continuous Digit Length: 11
Number: 11: Continuous Digit Length: 13

You could build a string with all the digits and get its length (but that's not very efficient):
n = 103
r = len("".join(map(str,range(1,n+1)))) # 201
Alternatively what you can do it compute the number of 1-digit, 2-digit, ... x-digit values that are below n. You can figure out these numbers starting with the largest number of digit (which you can obtain using the base 10 logarithm).
from math import log
d = int(log(n,10))
r = (d+1)*(n+1-10**d) + sum((i+1)*9*10**i for i in range(d)) # 201

Related

sum of every other digit and doubling the rest

I'm working on a card number check code, for now I created a function that asks for the card number and checks if it is 8 digits or not (it has to be 8) and then calls another function that will do the math and check if the card is valid. For this function:
Starting from the rightmost digit, form the sum of every other digit. For example, if the card number is 1234 5678, then you form the sum 8 + 6 + 4 + 2 = 20
Double each of the digits that were not included in the preview step and then add all digits of the resulting numbers. For example, the digits that were not included are 7 5 3 1, we double the, 14 10 6 2, and then we sum each digit, 1 + 4 + 1 + 0 + 6 + 2 = 14
Add the sums of the two steps, 20 + 14 = 34, if the last digit is 0 then the card is valid, otherwise it is not valid (which is our case)
My problem is that I don't know how to iterate and get the sum of every other digit or double the other number which were not included in step 2. My thought was to use a while loop but then what?
EDIT: since some answers used lists... we didn't study lists yet, so I should not use it, we are only allowed to use sample stuff, loops, functions, etc.. even sum(map()) we didn't study
That is my code for now (its not much but just thought put it anyway)
def getCard():
CardInput = int(input("Enter your 8 digit credit card number: "))
if len(CardInput) == 8:
CardCheck(CardInput)
else:
print("Invalid Input: Should be exactly 8 digits!")
getCard()
def CardCheck(CardNumber):
Position = 0
Sum = 0
DoubleSum = 0
FinalSum = 0
while CardNumber >= 0:
Position += 1
So, the ugly way of doing is, you can write a for loop and use indexing for access specific elements
for i in range(len(CardInput)):
# it will iterate from 0 to 7
print(CardInput[i]) # here you get ith element
if i % 2 == 1:
print("I am other!") # you can sum your things here into another variable
Or with while:
while position < len(CardInput):
print(CardInput[position])
position += 1
It assumes CardInput is str, so I recommend to not convert it earlier.
However pythonic way would be
sum(map(int, CardInput[1::2])))
CardInput[1::2] returns list of every second element starting from second (0 is first).
map converts every element to in.
sum sums elements.
prompt = "Enter the eight-digit number: "
while True:
number = input(prompt)
if len(number) == 8 and number.isdigit():
break
prompt = "Oops, try again: "
first_digits = number[1::2] # If the user entered '12345678', this will be the substring '2468'
first_sum = sum(map(int, first_digits)) # Take each digit (character), map it to a single-digit integer, and take the sum of all single-digit integers
second_digits = number[0::2] # If the user entered '12345678', this will be the substring '1357'
doubled_ints = [int(char) * 2 for char in second_digits] # Take each digit (character), turn it into an integer, double it, and put it in a list.
second_sum = sum(map(int, "".join(map(str, doubled_ints)))) # Merge all integers in 'doubled_ints' into a single string, take each character, map it to a single digit integer, and take the sum of all integers.
total_sum = first_sum + second_sum
total_sum_last_digit = str(total_sum)[-1]
is_valid_card = (total_sum_last_digit == '0')
if is_valid_card:
print("Your card is valid (total sum: {})".format(total_sum))
else:
print("Your card is NOT valid (total sum: {})".format(total_sum))
def getCard():
CardInput = input("Enter your 8 digit credit card number: ")
if len(CardInput) == 8:
CardCheck(CardInput)
else:
print("Invalid Input: Should be exactly 8 digits!")
getCard()
def CardCheck(CardNumber):
list_CardNumber = [x for x in "25424334"]
Sum = sum(int(x) for x in list_CardNumber[1:8:-2])
DoubleSum = 2*sum(int(x) for x in list_CardNumber[0:8:-2])
FinalSum = Sum + DoubleSum
if str(FinalSum)[-1] == "0":
print("Valid Input")
else:
print("Invalid Input")
To get you started, you should check out enumerate(), it'll simplify things if you're just going to use loops by giving you easy access to both the index and value every loop.
step1 = 0
for i, x in enumerate(number):
if i % 2:
print('index: '+ str(i), 'value: '+ x)
step1 += int(x)
print('step 1: ', step1)
Output:
index: 1 value: 2
index: 3 value: 4
index: 5 value: 6
index: 7 value: 8
step 1: 20
You can use:
# lets say
CardNumber = '12345678'
# as mentioned by kosciej16
# get every other digit starting from the second one
# convert them to integers and sum
part1 = sum(map(int, CardNumber[1::2]))
# get every other digit starting from the first one
# convert them to integers and double them
# join all the digits into a string then sum all the digits
part2 = sum(map(int,''.join(list(map(lambda x: str(int(x)*2), CardNumber[0::2])))))
result = part1 + part2
print(result)
Output:
34
Edit:
Only with loops you can use:
# lets say
CardNumber = '12345678'
total_sum = 0
for idx, digit in enumerate(CardNumber):
if idx % 2 == 1:
total_sum += int(digit)
else:
number = str(int(digit)*2)
for d in number:
total_sum += int(d)
print(total_sum)
output:
34
Since you need to iterate over the digits, it's actually easier IMO if you leave it as a string, rather than converting the input to an int; that way you can just iterate over the digits and convert them to int individuall to do math on them.
Given an 8-digit long string card, it might look like this, broken into steps:
even_sum = sum(int(n) for n in card[1::2])
double_odds = (2 * int(n) for n in card[0::2])
double_odd_sum = sum(int(c) for do in double_odds for c in str(do))
All together with some logic to loop while the input is invalid:
def get_card() -> str:
"""Returns a valid card number, or raises ValueError."""
card = input("Enter your 8 digit credit card number: ")
if len(card) != 8 or not card.isdecimal():
raise ValueError("Invalid input: Should be exactly 8 digits!")
card_check(card)
return card
def card_check(card: str) -> None:
"""Raises ValueError if card checksum fails, otherwise returns None."""
even_sum = sum(int(n) for n in card[1::2])
double_odds = (2 * int(n) for n in card[::2])
double_odd_sum = sum(int(c) for do in double_odds for c in str(do))
if (even_sum + double_odd_sum) % 10:
raise ValueError("Card checksum failed!")
while True:
try:
print(f"{get_card()} is a valid card number!")
except ValueError as e:
print(e)

Solving Python Riddle

Problem I am supposed to solve:
The Riddler is planning his next caper somewhere on
Pennsylvania Avenue. The address on Pennsylvania is a four-digit number with
the following properties.
All four digits are different,
The digit in the thousands place is three times the digit in the tens place,
The number is odd, and
The sum of the digits is 27.
So I made a for loop that checks each four digit integer and puts the value in a place holder (i.e. thousands, hundreds, etc.) And conditional if statements to fit the conditions. But my problem is that the IDE gives me no error when I run the code, but it does not print my statement at the end. I'm having trouble figuring out what is wrong with my code.
address = 0
thousand = 0
hundred = 0
ten = 0
one = 0
for address in range(1000,9999+1):
thousand = (address/1000)%10
hundred = (address/100)%10
ten = (address/10)%10
one = (address%10)
if (thousand != hundred) and (thousand != ten) and (thousand != one) and (hundred != ten) and (hundred != one) and (ten !=one):
if thousand == (3*ten):
if one % 2 != 0:
if thousand+hundred+ten+one == 27:
print("The address is: ",address, "Pennsylvania Ave.")
It runs but the print statement does not show up.
All four digits are different, The digit in the thousands place is three times the digit in the tens place, The number is odd, and The sum of the digits is 27.
The digit in the thousands place is three times the digit in the tens place: valid combos are 3x1x, 6x2x, 9x3x.
The sum of the digits is 27: only 9x3x is possible since 27 - (6 + 2) > 8+7, the maximum remaining digits. In fact 27 - (9 + 3) = 15. The remaining digits can be 9,6 or 8,7
All four digits are different: 9,5 is not an option. The number is either 9837 or 9738.
The number is odd: it's 9837.
Some pencil and paper works better than a for loop here.
That being said, keep in mind that / is the true division operator in Python 3, irrespective of type. So when address = 6754, for example
thousand = (address / 1000) % 10
evaluates as
thousand = 6.754 % 10
which is just 6.754, not 6 as you were probably hoping. To get 6, use the integer division operator //:
thousand = (address // 1000) % 10
Number Theory
isop = []
for a in range(1, 10, 1):
for b in range(0, 10, 1):
for c in range(0, 10, 1):
for d in range(0, 10, 1):
if a!=b and a!=c and a!=d and b!=c and b!=d and c!=d:
sum = a+b+c+d
if a==3*c and sum == 27:
num = a*1000 + b*100 + c*10 + d
if num % 2 == 1:
isop.append(num)
for i in range(len(isop)):
print(isop[i])

Python3 check digit algorithm

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)).

Extract the n-th digit of a number in Sagemath

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.

python upside-down number puzzle. Need assistance with efficiency

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))

Categories

Resources