python addition 2 digit number - python

I'm studying algorithms. The exercise consist in put a number of 2 digits (between 10 and 99) and then do the addition of the two digits. I made it in python and it works, but my teacher said that there's another way to do it without the conversions that i'm using. Can you help me? Is there a better way? Thanks.
for i in range(5):
add = 0
num = input("Number: ")
num = int(num)
if num > 9 and num < 100:
num = str(num)
add = int(num[0]) + int(num[1])
print("The addition of the two digits is: " + str(add))
else:
print("It is not a two digit number.")

I think he meant:
(num // 10) + (num % 10)
With num // 10 you perform an integer division with 10. But this is the first digit. With num % 10 you get the remainder of the division, which is the second digit. For example:
>>> 67 // 10
6
>>> 67 % 10
7
The most succinct way must be:
sum(divmod(num, 10))
because divmod performs the integer division with 10 and finding the remainder at the same time. So with sum we get the sum of those two numbers. For example:
>>> divmod(67, 10)
(6, 7)
>>> sum(divmod(67, 10))
13

rem = num%10
quotient = int(num/10)
sum = rem+quotient
print sum
I guess this should suffice.

Related

Finding the last digits sum with recursion

I'm attempting to create a function that will sum all the digits
and will return the sum of the summarized number.
Example:
For Input getNumValue(1589)
The Output will be: 5
Becuase: 1 + 5 + 8 + 9 = 23
And 2 + 3 = 5
So the output will be 5
Because we can't split it into more digits.
I did managed to create a recursion function that summarize the digits:
def getNumValue(number: int):
if number == 0:
return 0
return (number % 10 + getNumValue(int(number / 10)))
But I can't seem to utilize it to my cause.
Btw
I don't want to use any strings
And I'm trying to use recursion so far no luck.
I bet this is a known mathematic problem I'm just unfamiliar with.
Any advice?
Even shorter:
def getNumValue(number: int): return ((number-1) % 9) + 1
The digit sum is always in the same remainder class mod 9 as the original decimal number, this applies recursively, and thus reducing it to one digit just is the remainder under division by 9.
The shift by 1 just serves the purpose that the remainder class 0 is represented by 9.
you can make a final check before returning the answer.
def getNumValue(number: int):
if number == 0:
return 0
answer = (number % 10 + getNumValue(int(number // 10)))
if answer < 10:
return answer
return getNumValue(answer)
print(getNumValue(15899999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999))
OUTPUT :
9
You can check if number is greater than 9. If yes, then call the function again:
def getNumValue(number: int):
if number == 0:
return 0
j=(number % 10 + getNumValue(int(number // 10)))
if j>9:
return getNumValue(j)
return j
print(getNumValue(getNumValue(1589)))
Without recursion:
def getNumValue(number: int) -> int:
while True:
total = 0
while number:
total += number % 10
number //= 10
number = total
if total <= 9:
return total
>>> getNumValue(number)
5
pythonic recursion :)
def getNumValue(number=1589):
ans = number % 10 + getNumValue(int(number / 10)) if number else 0
return getNumValue(ans) if ans > 10 else ans
output
5

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

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

Finding the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? [duplicate]

This question already has answers here:
Least common multiple for 3 or more numbers
(32 answers)
Closed 5 years ago.
This is a Project Euler challenge where I'm trying to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
The logic while I came up with seems to run really slowly. It's been running for the last 4 mins and still hasn't found the number. I'm trying to figure out a) Is this logic correct? b) Why does this take so long? and c) Could someone give me a hint on an alternate logic that is more efficient.
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
smallest_num = 2520
while smallest_num >= 2520:
divisor = 2
while smallest_num % divisor == 0 and divisor < 21:
print("Smalles num = {} and Divisor = {}").format(smallest_num, divisor)
divisor += 1
smallest_num += 1
print("Smallest number is: {}").format(smallest_num)
This is still processing and so far my terminal looks like this
Here's your method run "properly" (using the term liberally), but as #James mentioned it will take an egregious amount of time as a loop.
divisors = np.arange(1, 21)
num = 2520
while True:
if np.all(num % divisors == 0):
print(num)
break
num += 1
A much better method (for Python 3.x). Directly from a similar question:
import functools
import math
functools.reduce(lambda x,y: x*y//math.gcd(x, y), range(1, 21))
Out[27]: 232792560
The following code works fine.
#!/usr/bin/env python
import math
#Generating primes
divisorMax = 20;
top = divisorMax + 1 #divisor max is the upper limit
p = [x for x in range(2,top)]
for num in p:
for idx in range(2,(top//num)+1):
if num*idx in p:
p.remove(num*idx)
#Solving the problem
result = 1;
for i in range(0, len(p)):
a = math.floor(math.log(divisorMax) / math.log(p[i]));
result = result * (p[i]**a);
print(result)
You are using brute force technique to calculate the number, which is easy to understand and write, but takes very much time.
I am using the Prime Factorisation technique explained here.
i am not 100% sure, if my solution is really correct, but i guess it is and it is pretty fast.
First of all, we don't need to care for all divisors, as most are multiples of each other. So best way is to count the divisors backwards, for example starting with 20 down to 1.
I had a look at the prime numbers, the solution needs to be a multiple of all primes above 10, furthermore we need to check the 20 divisor, the rest can be ignored, as when testing divisor 18, the 9 will work as well, and so on.
So i mulitplied 11 * 13 * 17 * 19 * 20. The resulting is 923780 and is divisible by at least the primes + 20.
So i would start at 923780 and test only every 923780th number.
smallest_num = 923780
steps = 923780
while True:
divisor = 19
while smallest_num % divisor == 0 and divisor > 10:
print("Smalles num = {} and Divisor = {}").format(smallest_num, divisor)
divisor -= 1
if divisor == 10:
print("Smallest number is: {}").format(smallest_num)
break
smallest_num += steps
Maybe i have logical error?!

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

Reversing a number's digits using modular division

My homework is to find the "emirp numbers" (pairs of primes like 13 &lrarr; 31) up to 10,000. I can reverse the digits using [::-1], but I must do it with % instead.
Here's my code. It works, but how can I reverse the digits using % instead of [::-1]?
counter=0;
prime_counter=0;
emirp_counter=0;
for N in range(13,9968):
i=2;
controlq=1;
while i < N/2+1 and controlq==1:
counter+=1;
if N % i == 0:
controlq=0;
i+=1;
if controlq==1:
x=int(str(N)[::-1]); # Here's the problem.
a=2;
controlw=1
while a < x/2+1 and controlw==1:
emirp_counter+=1
if x % a == 0:
controlw=0;
a+=1
if controlw==1 and (N!=x):
prime_counter+=1;
print(N,'<-- is an emirp number -->',x,);
print('TOTAL PRIME NUMBERS', prime_counter);
print('TOTAL PROCESS', emirp_counter+counter);
I just started learning Python (and programming) 1 month ago.
reverse a number using mod? from the top of my head I get this
def reverse_number(n):
digit=[]
while n!=0:
n,d = divmod(n,10) # n//10 , n%10
digit.insert(0,d)
result=0
for i,d in enumerate(digit):
result += d*10**i
return result
because n mod 10 give my the last digit of the number, then I just have to save it and then do a interger division of the number by 10, and repeat until my number is zero, Python let my do both at the same time with divmod, finally a make the new reversed number adding power of 10 as needed.
>>> reverse_number(45682)
28654
Short answer:
def reverse(x):
def reverse_int_(n, r):
return reverse_int_(n / 10, n % 10 + r * 10) if n else r
return reverse_int_(x, 0)
There you have your % operator.

Categories

Resources