How to create list of 15-digit numbers with condition? - python

I want to create list of random 20 15-digit numbers and each of this 15-digit numbers must follow 1 rule.
The rule is that I want this 15-digit number to be made out of 5 3-digit numbers in which first digit + second digit = third digit or if sum of first two digits is greater than 10 then third digit must be, equal to second digit of sum of first two digits. for example if first digit is 5 and second is 8, third digit must be 3 since 5 + 8 = 13.
I've written code that fills list with 15-digit numbers with the same rule, but it only works for first three digits.
import random as rd
def numchoose(start, end):
arr=[]
num=0
while num<20:
a=(rd.randint(start, end))
if int(str(a)[0]) + int(str(a)[1]) == int(str(a)[2]):
arr.append(a)
num+=1
elif int(str(a)[0]) + int(str(a)[1]) > 10 and int(str(a)[2]) == int(str(int(str(a)[0]) +
int(str(a)[1]))[1]) :
arr.append(a)
num+=1
else: continue
print(numchoose(100000000000000, 999999999999999))
How do I write this code so that entire 15-digit number is made out of 3-digit numbers that follow the stated rule and first three digits are not the only ones that follow rule?

This seems to work, but i replaced the big number with how long you want the number to be.
import random as rd
def numchoose(len):
number = ""
for i in range(int(len/3)):
a = rd.randint(0, 9)
while i == 0 and a == 0:
a = rd.randint(0, 9)
b = rd.randint(0, 9)
c = a + b
if c >= 10:
c -= 10
number += str(a) + str(b) + str(c)
return int(number)
print(numchoose(15))

Bit more compact then #eav28 but credit goes to them for answering first:
import random
def NumberGen(Length):
Number = ""
for X in range(int(Length // 3)):
A = random.randint(0, 9)
## To drop leading zero's:
## if X == 0 and A == 0:
## A = random.randint(1, 9)
B = random.randint(0, 9)
C = A + B
if C > 9:
C -= 10
Number += str(A) + str(B) + str(C)
return Number
print(NumberGen(15))
I hope this answers your question

Related

Reading in a positive int and transform every digit of that number in an even-odd way

So what I need to do is read in a number and transform every digit.
add 2 to an odd digit
subtract 3 from an even digit (watch out for negative numbers!)
zero stays 0
input
14502
wanted output
31701
Current output
14504
Below is what I have for now, I can read every digit in a for loop but I don't know how to transorm them one by one.
num = int(input("Enter a number:"))
for digit in str(num):
print(digit)
if (num % 2)==0:
print(num + 2)
else:
print(num - 3)
ALSO NO IMPORTS
num = input("Enter a number:")
new_num = []
single_number = ''
for digit in num:
digit = int(digit)
if digit == 0:
new_num.append(digit)
elif (digit % 2)!=0:
digit = digit+2
new_num.append(digit)
elif (digit % 2)==0:
digit = digit-3
if digit>=0:
new_num.append(digit)
else:
digit = digit*(-1)
new_num.append(digit)
print(new_num)
# for single int instead of array
for digit in new_num:
digit = str(digit)
single_number = single_number+digit
print(single_number)
new_number is array of digits single_number is the final number you want.
is your code missing the indent after the for loop? I know that may not solve the question but is that another issue with your code or just a formatting issue here on stack?
num = int(input("Enter a number:"))
for digit in str(num):
print(digit)
if (num % 2)==0:
print(num + 2)
else:
print(num - 3)
num = int(input("Enter a number:"))
print(len(str(num)))
finaloutput = []
for i in range(len(str(num))):
digit = num%10
if digit%2==0:
if digit - 3 < 0:
digit = 0
else:
digit = digit - 3
else:
digit = digit + 2
finaloutput.append(digit)
num = num //10
print(finaloutput)
string=""
for i in range(len(finaloutput)):
string = string + str(finaloutput[i])
print(string[::-1])
Might be a big scuffed but gets the job done. Substract 3 from even, add 2 to odds, and watch for zeros.
output:
Enter a number:14502
5
[0, 0, 7, 1, 3]
31700
I put it so if an even number sub 3 is less than zero it jus stays zero, bc thats how I understood it. You can easily modify the code to suit your need and in accordance with your task or whatever
Try:
num = 9876543210
l = [int(c) for c in str(s)]
l = [min(c, 7) + 2 if c % 2 else max(c, 4) - 3 if c != 0 else c for c in l]
out = int(''.join(str(c) for c in l))
Output:
>>> out
9593715130
Details:
9 -> 9 (else 12)
8 -> 5 (-3)
7 -> 9 (else 10)
6 -> 3 (-3)
5 -> 7 (+2)
4 -> 1 (-3)
3 -> 5 (+2)
2 -> 1 (else -1)
1 -> 3 (+2)
0 -> 0 (do nothing)
A simple implementation based on your solution. It can only handle integers though. And there is one case which you have not specified which is
what to do when the digit is 9? As 9 + 2 = 11 and 11 is not a digit but could well be what you want in your algorithm?
In this implementation 9 is turned to 1.
def calc_on_digits(num: str):
result: str = ""
for digit in num:
digit = int(digit)
if digit == 0:
result += "0"
continue
if digit % 2 == 0:
# in case it get negative take the absolute value
digit = abs(digit - 3)
else:
digit += 2
# in case its 9 the result would be 11 -> make it one
digit = digit % 10
result += str(digit)
return result
# string in this implementation can only contain valid integer values
print(calc_on_digits("14502"))
You cannot calculate modulo from string. Also you have to perform the comparison per digit, not for the whole number.
num = input("Enter a number:") # no need to cast to int just to transform back to str below
new_number = ""
for digit in num:
digit = int(digit)
print(digit)
if (digit % 2) = 0:
tmp = digit + 2
if tmp >= 10:
tmp = 0
else:
tmp = digit - 3
if tmp < 0:
tmp = 0
new_number += str(tmp)

Sum of digits untill reach single digit

I set an algorithm which sum a number's digits but I couldn't make it till single digit. It only work for one step.
For example:
a=2, b=8
a^b=256 = 6+5+2 = 13
But I want to reach single digit, like:
a^b=256 = 6+5+2 = 13 = 3+1 = 4
Below you can see my codes.
a = int(input("Enter a value"))
b = int("Enter second value")
number = pow(a, b)
sum= 0
while float(number) / 10 >= .1:
m = number % 10
sum += m
number = number // 10
if float(number) / 10 > .1:
print(m, end=" + ")
else:
print(m, "=", sum)
Here you go:
n = 256
while n > 9:
n = sum(int(i) for i in str(n))
print(n)
So whats going on? str(n) converts n to a string, strings in python can be iterated over so we can access digit by digit. We do this in a generator, converting each digit back to a integer, int(i) for i in str(n), we use sum to sum the elements in the generator. We repeat this process until n is a single digit.
Added a solution that gives the calculation explicitly:
def sum_dig(n):
_sum = sum(int(i) for i in str(n))
explained = "+".join(list(str(n)))
return _sum, explained
n = 256
s = ""
while n > 10:
n, e = sum_dig(n)
s+= f'{e}='
s += str(n)
print(s)
yields:
2+5+6=1+3=4
you can try this.
a = int(input("Enter a value"))
b = int(input("Enter second value"))
number = pow(a, b)
result = str(a)+'^'+str(b) + ' = ' + str(number)
while number > 9:
digit_sum = sum(map(int, str(number)))
result += ' = ' + '+'.join(str(number)) + ' = ' + str(digit_sum)
number = digit_sum
print ( result )
for a=2, b=8 result:
2^8 = 256 = 2+5+6 = 13 = 1+3 = 4
This produces the output in the format OP asked for:
a = int(input("Enter a value: "))
b = int(input("Enter second value: "))
n = pow(a, b)
while n >= 10:
nums = [i for i in str(n)]
op = "+".join(nums)
n = eval(op)
print("{}={}".format(op, n))
Logic:
Store the input in an array of individual numbers as strings.
Create the summation string using "+".join(nums) - for the output print.
Calculate the sum using eval(op) which works on strings (a built-in function) - store in n.
Print the summation string and what it equals.
Output:
Enter a value: 2
Enter second value: 8
2+5+6=13
1+3=4
Enter a value: 2
Enter second value: 6
6+4=10
1+0=1
Enter a value: 2
Enter second value: 50
1+1+2+5+8+9+9+9+0+6+8+4+2+6+2+4=76
7+6=13
1+3=4
sol = 0
if (a^b)%9==0:
sol = 9
else:
sol = (a^b)%9

Project Euler problem #111. Generate 10 digit primes with most repeated individual digits

I am working on project Euler problem #111. I have created this program which works fantastic for the given example but apparently is not producing the desired answer to the problem. Here's my source code in python:-
#This function generates all the primes of 4 digits with the highest repeated digits 1 to 9 and returns their sum for eg. 3313, 4441, 4111 etc.
Note that any digit from 1 to 9 can come at most of 3 times in a 4 digit prime number. I have highlighted the same in the code.`
from more_itertools import distinct_permutations
from sympy.ntheory.primetest import isprime
def fn1to9():
s = 0
for digit in range(1, 10):
for j in range(0, 10):
permutations = list(distinct_permutations(str(digit) * 3 + str(j)))
for perm in permutations:
num = int("".join(perm))
if (num > 1000000000):
if (isprime(num)):
print(num)
s = s + num
return s
This function is for the special case of 0. Note that 0 can come atmost 2 times in a 4 digit prime no. I have bolded the number 2 in the code.
def fnFor0():
s = 0
for firstDigit in range(1, 10):
permutations = list(distinct_permutations(str(0) *2+ str(firstDigit)))
for perm in permutations:
for msd in range(1, 10):
temp = list(perm)
temp.insert(0, str(msd))
num = int("".join(temp))
if (num > 1000000000):
if (isprime(num)):
print(num)
s = s + num
return s
Now, this program works well and produces the desired sum of 273700 as has been stated in the question. So, I made the required changes and ran it for 10 digits. The required changes were changing the str(digit)*3 to str(digit)*9 in fn1to9 and str(digit)*2 to str(digit)*8 in fnFor0 in the distinct_permutations() function (Hoping that 9 digits will be repeated for every digit from 1 to 9 in the prime number and 8 0s for the prime number containing 0s). But it did not give the desired answer. Then I inspected and found out that for repeated digits of 2 and 8, the maximum repetition can be of 8 digits, so I wrote another function specifically for these 2 digits which is as follows:
def fnFor2and8():
s = 0
for digit in [2,8]:
for firstDigit in range(0, 10):
for secondDigit in range(0, 10):
permutations = list(distinct_permutations(str(digit) * 8 + str(firstDigit) + str(secondDigit)))
for perm in permutations:
num = int("".join(perm))
if (num > 1000000000):
if (isprime(num)):
print(num)
s = s + num
return s
This function as expected produces the desired 10 digits numbers with 2 and 8 repeated exactly 8 times. I had hoped it summing up the results from all of these 3 functions will give me the answer but seems like I am missing some numbers. Can someone please help me point out the flaw in my reasoning or in my program. Thanks a lot in advance.
Here was the solution I came by wehn I was working on this problem:
import eulerlib
def compute():
DIGITS = 10
primes = eulerlib.list_primes(eulerlib.sqrt(10**DIGITS))
# Only valid if 1 < n <= 10^DIGITS.
def is_prime(n):
end = eulerlib.sqrt(n)
for p in primes:
if p > end:
break
if n % p == 0:
return False
return True
ans = 0
# For each repeating digit
for digit in range(10):
# Search by the number of repetitions in decreasing order
for rep in range(DIGITS, -1, -1):
sum = 0
digits = [0] * DIGITS
# Try all possibilities for filling the non-repeating digits
for i in range(9**(DIGITS - rep)):
# Build initial array. For example, if DIGITS=7, digit=5, rep=4, i=123, then the array will be filled with 5,5,5,5,1,4,7.
for j in range(rep):
digits[j] = digit
temp = i
for j in range(DIGITS - rep):
d = temp % 9
if d >= digit: # Skip the repeating digit
d += 1
if j > 0 and d > digits[DIGITS - j]: # If this is true, then after sorting, the array will be in an already-tried configuration
break
digits[-1 - j] = d
temp //= 9
else:
digits.sort() # Start at lowest permutation
while True: # Go through all permutations
if digits[0] > 0: # Skip if the number has a leading zero, which means it has less than DIGIT digits
num = int("".join(map(str, digits)))
if is_prime(num):
sum += num
if not eulerlib.next_permutation(digits):
break
if sum > 0: # Primes found; skip all lesser repetitions
ans += sum
break
return str(ans)
if __name__ == "__main__":
print(compute())

Taking away from nearest 10

Okay, i have made my code so that a user can input 7 numbers and times them by 1 for the odd index numbers and 3 for the even:
num = str(input("Please enter 7 numbers")
length = len(num)
while length < 7 or length ? 7:
num = input("Only enter 7 numbers")
string = ''
for t in range(1,8):
if t % 2 == 0:
string += str(t * 3)
else:
string += str(t) + ' '
print(string)
This works fine, but now i need to add all the numbers up and take it away from the highest 10 so for example, all the numbers add up to 53 i need to take that away from 60 which leaves me 7, that will be my eight number, then after i have got that number i print it out, how do i get it to add the numbers up and the take it away from the highest 10 and output the difference of the two into the numbers i already have?
Thanks
Brad
If you have a number, x, which is equal to 53, then going up should be math.ceil(x) except that math.ceil() rounds for 1. To account for that, we divide by 10, use math.ceil(), and then multiply by 10 again:
import math
rounded_up = math.ceil(x / 10) * 10
result = rounded_up - x
Brad could you clarify your question? Also your above code does not work.
Missing a bracket on the first line and this isn't valid while length < 7 or length ? 7:
I believe this is what you're looking for:
def take_away_from_nearest(number, nearest):
return nearest - (number % nearest)
Usage:
>>> take_away_from_nearest(53, 10)
7
edit:
If I understand you correctly, this would be the entire code:
while True:
# this is just an easy way to keep asking until the input is correct
num = input("Please enter 7 numbers: ")
if len(num) == 7:
break
weird_sum = 0 #here's where we're gonna sum up the numbers; the "eighth number"
for index, character in enumerate(num):
if index % 2 == 0: # index is odd, so count the character thrice
print(3 * int(character))
weird_sum += 3 * int(character)
else: # index is even
print(int(character))
weird_sum += int(character)
print(10 - (weird_sum % 10)) # 10 minus (weird_sum modulo 10)
# and finally, adding them all up and checking whether it ends with 0:
print((10-(weird_sum % 10) + weird_sum) % 10 == 0) # prints True

Python3.4 - math with index numbers

My objective was to use the index of a list to do addition/subtraction with. Where by I turned the even index positive, and the odd index negative.
EX1: 1234508 Should be answered by a 0: 1-2+3-4+5-0+8 = 11, then the while loops it again and I get 1-2+1 = 0
Ex2: 12345 Should be answered by a 3: 1-2+3-5 = 3, so it shouldn't go through the loop again.
Ex3: 121 Should be answered by a 0: 1-2+1 = 0, so it shouldn't go throught he loop again.
def main():
print()
print("Program to determine if a number is evenly\ndivisible by 11")
print()
indexed = input("Enter a number: ",)
total = 0
num = 0
while num >= 10:
for item in indexed:
if num %2 == 0:
total = total + int(item)
else:
total = total - int(item)
num = num + 1
print(total)
main()
Note that this print statement above is a place holder for a if statement which is inactive on my code, but was printing as large bold print here.
Let's say you have a string st whose characters are all digits, and that you want to have the sum of these digits. You then define the following function
def sd(st):
return sum(int(d) for d in st)
that we can test in the interpreter
In [30]: sd('10101010101010101010')
Out[30]: 10
In [31]: sd('101010101010101010101')
Out[31]: 11
What you really want is to sum the odd digits and subtract the even ones, but this is equivalent to sum the odds, sum separately the evens and then take the difference, isn't it? so what you want is
step_1 = sd(odds(st)) - sd(evens(st))
How can you separate the odd digits from the even ones? Ah! no need for a function, we can use slices
step_2 = sd(st[::2]) - sd(st[1::2])
Now we want to test the slices in the interpreter
In [32]: '101010101010101010101'[::2]
Out[32]: '11111111111'
In [33]: '101010101010101010101'[1::2]
Out[33]: '0000000000'
But step_2 could be a negative number, that I don't want to manage... I'd rather use the abs builtin
step_3 = abs(sd(st[::2]) - sd(st[1::2]))
and this is exactly what you were looking for.
Eventually we can put all the above together, but we may need to iterate until the difference is less than 11 --- we'll use an infinite loop and a break statement to exit the loop when we'll have found the answer
def sd(st):
return sum(int(d) for d in st)
number = input('Give me a number: ')
trial = number
while True:
n = abs(sd(trial[::2]) - sd(trial[1::2]))
if n < 11: break
trial = str(n)
if n > 0:
...
else:
...
what exactly do you want to do with this?
evenindex = evenindex int(item)
"list" is a type, means the list type in python, so it cannot be the name of a variable. Furthermore, you have not defined this variable in your code.
I have figured out the answer to the question I asked above. As such, my answer here is in the event anyone stumbles upon my above question.
def main():
indexed = input("Enter a number: ",)
total = 0
num = 0
while num <= 10:
for item in indexed:
if num %2 == 0:
total = abs(total + int(item))
else:
total = abs(total - int(item))
num = num + 1
if total == 0:
print(indexed, "is evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
else:
print(indexed, "is not evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
input()
main()

Categories

Resources