Python Modularity for a number [duplicate] - python

This question already has answers here:
How do I sort a dictionary by value?
(34 answers)
Closed 5 years ago.
How to create a itterative number 10digit long by taking a base number

A Simple approach for Solution:
a=input()
while len(a)<10:
b=int(a[len(a)-1])+int(a[len(a)-2])
a=a+str(b%10)
print (a)
May This one helpful for you.

n= 16
while(len(str(n)) < 10):
print(n)
a = n %10 + (int(n/10))%10 # sum of last two digits
n *= 10
n += a%10 #adding the last
print(n)

Based on your example, I'm assuming you want to stop once you reach a 0.
Certain numbers, like 18 wouldn't reach a 0 ever, so also want to add a meximum length that the ID can be.
The following code runs the math until you reach a 0, or until it reaches 40 digits.
def getID(number)
maxlength = 40 - len(str(number))
while maxlength:
string = str(number)
answer = (int(string[-2]) + int(string[-1])) % 10
if answer == 0:
break
number = number * 10 + answer
maxlength -= 1
return number
getID(14) == 1459437
getID(15) == 15617853819
getID(16) == 1673
getID(18) == 17853819
getID(18) == 189763921347189763921347189763921347189763
18 is a number that repeats forever, so instead the loop ends once it reaches a set length.

Related

How to split number into digits and add, then split, and add, etc [duplicate]

This question already has answers here:
How to make loop repeat until the sum is a single digit?
(10 answers)
Closed 9 months ago.
num = 15
split = ([int(single) for single in str(num)])
total = 0
iteration = 0
while iteration < len(split):
total = total + split[iteration]
iteration += 1
print(total)
I'm trying to write this program where an input is given (ex. 74837)
The number would be split into individual digits within a list [7,4,8,3,7]
It would then be added (29), then split again [2,9], and then added again until the sum is under 10, so 11, [1,1], finally turning into 2 as the final number
Any help would be awesome. :)
I think that I've figured out splitting and adding, but splitting and adding again until below 10, is confusing me.
It's a simple while loop:
n = 23452436
while n >= 10:
print(n)
n = sum(int(i) for i in str(n))
print(n)
This is a suitable place to use a recursive method.
def digit_sum(n: int):
curr_sum = sum(int(digit) for digit in str(n))
if curr_sum < 10:
return curr_sum
else:
return digit_sum(curr_sum)
Here's a fun iterative way to do it without any string conversion:
num = 15
def boilItDown(num):
while num >= 10:
total = 0
while num:
d, m = divmod(num, 10)
num, total = d, total + m
num = total
return num
Test code:
print(boilItDown(15))
print(boilItDown(155))
print(boilItDown(1555))
print(boilItDown(15555))
print(boilItDown(155555))
print(boilItDown(1555555))
print(boilItDown(15555555))
Output:
6
2
7
3
8
4
9

Don't understand why code for digit sum isn't working

I tried to do the codewars Sum of Digits/Digital Root problem, where you have to:
Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.
So passing through 52 would return 7, as 5 + 2 is 7 and passing through 942 would return 6, as 9 + 4 + 2 = 15 and then 1 + 5 = 6.
I came up with this code:
def digital_root(n):
n_str = str(n)
digit_total = 0
while len(n_str) != 1:
for digit in n_str:
digit_total += int(digit)
n_str = str(digit_total)
return(n_str)
But it only works for 2 digit numbers and it won't work for higher digit numbers, it just endlessly runs. This code is probably a bad way to do it and I've looked over other people's answers and I get their solution but I just don't get why this won't work for higher digit numbers.
You have got your program almost right. The only challenge I see is with resetting the variable digit_total = 0 after each iteration.
def digital_root(n):
n_str = str(n)
while len(n_str) != 1:
digit_total = 0 #move this inside the while loop
for digit in n_str:
digit_total += int(digit)
n_str = str(digit_total)
return(n_str)
print (digital_root(23485))
The output for print (digital_root(23485)) is 4
2 + 3 + 4 + 8 + 5 = 22
2 + 2 = 4
If the digit_total = 0 is not inside the while loop, then it keeps getting added and you get a never ending loop.
While you have a lot of code, you can do this in a single line.
def sum_digits(n):
while len(str(n)) > 1: n = sum(int(i) for i in str(n))
return n
print (sum_digits(23485))
You don't need to create too many variables and get lost in keeping track of them.
Alex,
running a recursive function would always be better than a while loop in such scenarios.
Try this :
def digital_root(n):
n=sum([int(i) for i in str(n)])
if len(str(n))==1:
print(n)
else:
digital_root(n)

How to skip a part of the code if a certain condition is met [duplicate]

This question already has answers here:
how to stop a for loop
(9 answers)
Closed 2 years ago.
As I am getting more and more comfortable with writing scripts in Python I wrote a script that finds prime numbers by trying to divide each number in a range in each number (kinda like Brute Force haha).
It works but I wanted to make the process faster and more efficient.
My code:
count = 0
for i in range(2,1000):
j = 2
while j < 1000:
if i%j==0:
count = count + 1
j = j + 1
if count == 1:
print(i)
count = 0
Explanation:
I check and store in count how many time does a number can be divided.
If by the end of the check count equals 1 that means that the number is prime (gets divided only by itself).
What I want now is to stop the process of checking how many times the number can get divided when the "count" variable exceed 1 (2 or more). How do I do that?
I wanted to do something with try and except but didn't know what...
Add an extra condition in here, and break out of the loop if the count is greater than one. Put this inside the while loop:
if i % j == 0:
count += 1
if count > 1:
break
As mentioned in the comments, it's cleaner to just use count as part of the loop condition. Here's an improved version:
for i in range(2, 1000):
j = 2
count = 0
while j <= i and count < 2:
if i % j == 0:
count += 1
j += 1
if count == 1:
print(i)
Of course, there are faster ways to find if a number is prime - in particular, in the inner loop you should not iterate until 1000, not even until i is reached, just until the sqrt(i), but I'll leave that as an improvement for you to make ;)
You can try using break. What break does is that it skips the remaining part of the loop and jumps to the statement following the loop.
count = 0
for i in range(2,1000):
j = 2
while j < 1000:
if i%j==0:
count = count + 1
break
j = j + 1 ### line 8
if count == 1:
print(i)
count = 0
In this code, when python encounters break, it skips the remaining part of the loop (that is, the remaining loop is not executed) and jumps straight to the next statement, which is line 8
Its all wrong, first you have to understand the algorithm to check for prime, basically a number is prime if it can't be fully divided by any number between 2 to (number//2)-1
Now in your question, you couldn't use break anywhere, bcz you first searching for all divisible and then checking prime, better I'm adding a sample code to your problem which is more feasible to find primes
Code
number = int(input("Enter A Number"))
for i in range(2,number//2+1): #See range arguments
if(number%i==0):
print("Not A Prime")
break #Break loop when condition reached

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

Optimized way for finding the number which satisfies specific conditions

I saw this question somewhere.
There is a 8 digit number. First digit from left to right tells how many zeroes in the number. Second digit tells you how many 1s in the number, third digit tells u how many 2 in the number and so on till 8th digit which tells u how many 7 in the number. Find the number.
So I wrote a piece of code in python to find out the digit. Apart from the conditions mentioned above, I have few additional checks like 'sum of digits should be 8' and 'no 8 or 9 should be present in the number'. I've pasted the code below. This is just brute force since I take every number and check for conditions. I was curious to know if there is any better way of solving the problem
def returnStat(number, digit, count):
number = str(number)
digit = str(digit)
print "Analysing for ",digit," to see if it appears ",count, " times in ",number,"."
actCnt = number.count(digit)
count = str(count)
actCnt = str(actCnt)
if (actCnt == count):
return 1
else:
return 0
def validateNum(number):
numList = str(number)
if '8' in numList:
print "Skipping ",number, " since it has 8 in it"
return (-1)
elif '9' in numList:
print "Skipping ",number, " since it has 9 in it"
return (-1)
elif (sum(int(digit) for digit in numList) != 8):
print "Skipping ",number, " since its sum is not equal to 8"
return (-1)
index = 0
flag = 0
for num in numList:
if (returnStat(number,index,num)) :
index = index+1
continue
else:
flag = 1
break
if (flag == 1):
return (-1)
else:
return number
for num in range(0,80000000):
number = '{number:0{width}d}'.format(width=8,number=num)
desiredNum = "-1"
desiredNum = validateNum(number)
if (desiredNum == -1):
print number," does not satisfy all "
continue
else:
print "The number that satisfies all contition is ",number
break
You can go further than to simply say that digits of 8 or 9 are impossible.
Can the last digit ever be greater than 0? The answer is no. If the last digit was 1, this means there is one 7 somewhere else. However, if there is a 7, it means that the same number has occurred 7 times. This is clearly impossible. Thus the last digit has to be 0.
So we have xxxxxxx0.
What about the second to last digit?
If xxxxxx10, then there has to be at least one 6, which means the same number occurred 6 times. We can try 60000010, but this is incorrect, because there is a 1, which should be reflected in the second digit. The second to last digit can't be higher than 1 because 2 means there are 2 sixes, which in turn means one number occurred six times while another number also occurred 6 times, which is impossible.
So we have xxxxxx00.
If xxxxx100, then there has to be at least one 5, which means the same number occurred 5 times. Let us start with 51000100. Almost, but there are now 2 1s. So it should be 52000100. But wait, there are now one 1. and one 2. So we try 52100100. But now we only have 4 0s. We can't have xxxxx200 because this means there are 2 5s, which is impossible as explained above.
So we have xxxxx000.
If xxxx1000, we can try 40001000, nope, 41001000, nope, 42101000.
Ah there it is. 42101000.
Even if you iterate over all 8 digit numbers with no 8s or 9s in them, there's not many possibilities (actually, 8^8 = 1<<24 ~= 17 million).
Here's a naive program that tries them all:
import itertools
for digs in itertools.product(range(8), repeat=8):
counts = [0] * 8
for d in digs:
counts[d] += 1
if counts == list(digs):
print digs
It completes (with exactly one solution) in 15 seconds on my machine.
To make it faster, you can only consider 8-digit numbers whose digits add up to 8. Here's the same code as before, but now it uses sum_k to produce the possibilities. (sum_k(n, k) generates all n-digit tuples where all the digits are less than 8 which sum to k).
def sum_k(n, k):
if k < 0 or n * 7 < k: return
if n == 1:
yield k,
return
for d in xrange(8):
for s in sum_k(n-1, k-d):
yield (d,) + s
for digs in sum_k(8, 8):
counts = [0] * 8
for d in digs:
counts[d] += 1
if counts == list(digs):
print digs
This code completes in 0.022 seconds on my machine.
Adapting the code to solve the general case produces these solutions:
1210
2020
21200
3211000
42101000
521001000
6210001000
72100001000
821000001000
9210000001000

Categories

Resources