My program has the purpose of determining the greatest product of a certain amount of consecutive digits. For example the program prompts the user for a string of numbers (ex 255969406) and for the size of consecutive digits (3), thus my program will determine what the greatest product of 3 consecutive digits in the number provided is, my program compiles and runs but the product returned is incorrect.
def Pro(dig,snum):
number = 1
pr = 0
for x in xrange(0,dig-1):
pr = int(snum[x])
number = pr*number
return number
def Product(dig,indx,snum):
number = 1
pr = 0
for x in xrange(1,dig):
pr = int(snum[indx+x])
number = pr*number
return number
def Main():
num = raw_input("Enter a string of digits")
dig = input("Input number of digits in group")
x = 1
val = Pro(dig,num)
grps = int(len(num)/ dig)
while x<grps:
val2= Product(dig,x,num)
if val2>val:
val = val2
x +=1
print("The max product of " + str(dig) +" consecutive digits in " + num + " is " + str(val))
if __name__ == "__main__":
Main()
You can try this out:
x = '134214257248'
m = 0
for i in range(len(x) - 2):
m = max(m, int(x[i])*int(x[i+1])*int(x[i+2]))
print m
# 2*5*7 = 70
70
EDIT: Accept any amount (n) of consecutive digits
import numpy as np
x = '134214257248'
m = 0
n = 3
for i in range(len(x) - n + 1):
m = max(m, np.prod(list(int(l) for l in x[i:i + n])))
print m
70
Related
Working on an example but it does not work. There must be a function which counts trailing zero in n! the factorial formula. where, n is the number for whose factorial we want to find the number of trailing zeros. Used some imports but it did not work.
My code:
def is_positive_integer(x):
try:
x = float(x)
except ValueError:
return False
else:
if x.is_integer() and x > 0:
return True
else:
return False
def trailing_zeros(num):
if is_positive_integer(num):
# The above function call has done all the sanity checks for us
# so we can just convert this into an integer here
num = int(num)
k = math.floor(math.log(num, 5))
zeros = 0
for i in range(1, k + 1):
zeros = zeros + math.floor(num/math.pow(5, i))
return zeros
else:
print("Factorial of a non-positive non-integer is undefined")
Ex:
Input: n = 5
Output: 1
Factorial of 5 is 120 which has one trailing 0.
Input: n = 20
Output: 4
Factorial of 20 is 2432902008176640000 which has
4 trailing zeroes.
Input: n = 100
Output: 24
Output must be:
Trailing 0s in n! = Count of 5s in prime factors of n!
= floor(n/5) + floor(n/25) + floor(n/125) + ....
This code can do the job, your code is very complex.
def Zeros(n):
count = 0
i = 5
while n / i >= 1:
count += int(n / i)
i *= 5
return int(count)
n = 100
print("Trailing zeros " +
"in 100! is", Zeros(n))
Output:
Trailing zeros in 100! is 24
#Function factorial
def fact(d):
f=1
for i in range(d,0,-1):
f=f*i
print(f"factorial {f}")
return f
#Function for summation of factorial of digits
def f(n):
s=0
d=n%10
s=fact(d)+s
n=int(n/10)
print(f"summing {s}")
return s
l=[]
q=int(input("enter number of queries"))
print(q)
n=int(input("enter the number to which you want to calculate"))
m=int(input("enter range"))
for i in range(1,n+1):
l.append(i) #adding elements from 1 to n in list
print(l[i-1])
for j in range(1,m+1):
p=f(j)
if(l[i-1]==p):#element in list is equal to function (i.e sum of factorial of digits)
l[i-1]=p #then assign p to list
print(f"list {l[i-1]}")
break #then break the second loop
Like for eg:
For query 1
n= 3 and m=100
Till 1 to n
look in m for numbers whose sum of factorial of digits is equal to number in n
For eg :
5=25 ( as 2! + 5! = 2+ 120 = 122
1+2+2=5)
Then break for the next i iteration but I don't know where I'm making the mistake.
Goal: Find the smallest x such that the sum of digits of the factorials of the digits of x is n.
Sample behavior:
Find the smallest x such that:
the sum of digits of the factorials of the digits of x is n
Please provide n: 12
Please provide the maximal x to check: 10000
Trying 1:
Sum of the digits of factorials of the digits of 1 is:
digit_sum(1!)
= digit_sum(1)
= 1
...
Trying 4:
Sum of the digits of factorials of the digits of 4 is:
digit_sum(4!)
= digit_sum(24)
= 6
...
Trying 16:
Sum of the digits of factorials of the digits of 16 is:
digit_sum(1!) + digit_sum(6!)
= digit_sum(1) + digit_sum(720)
= 10
...
Trying 33:
Sum of the digits of factorials of the digits of 33 is:
digit_sum(3!) + digit_sum(3!)
= digit_sum(6) + digit_sum(6)
= 12
x is 33.
Source code:
import math
def print_sum_eq(x):
print(f" Sum of digits of the factorials of the digits of {x} is:")
msg1 = [f"digit_sum({d}!)" for d in str(x)]
print(" " + " + ".join(msg1))
msg2 = [f"digit_sum({math.factorial(int(d))})" for d in str(x)]
fact_values_str = " + ".join(msg2)
print(f" = {fact_values_str}")
def digit_sum(x):
return sum(int(d) for d in str(x))
def sum_fact_digit(x):
"""Calculate sum of factorials of the digits of x
For example, when x = 25, the digits are 2 and 5. The sum of the
factorials of the digits is 2! + 5! = 2 + 120 = 122.
Parameters
----------
x : int
Returns
-------
digit_sum : int
Sum of the factorials of the digits of x
"""
s = 0
print_sum_eq(x)
# Loop over the digits of x
for d in str(x):
digit = int(d)
digit_fact = math.factorial(digit)
s += digit_sum(digit_fact)
print(f" = {s}")
return s
def search(n, max_x=None):
"""Try to find x such that sum of factorials of the digits of x is n
Parameters
----------
n : int
max_x : int, optional
The function will search over x = 1, 2, ..., max_x
Returns
-------
result : int or None
If we find x, the result is x.
If we can't find x, the result is None.
"""
if max_x is None:
max_x = int(10 ** n)
for x in range(1, max_x + 1):
print(f"Trying {x}:")
sum = sum_fact_digit(x)
if sum == n:
return x
return None
def main():
print("Find the smallest x such that:")
print(" the sum of digits of the factorials of the digits of x is n")
n = int(input("Please provide n: "))
max_x = int(input("Please provide the maximal x to check: "))
x = search(n, max_x=max_x)
if x is None:
print("Cannot find such a x.")
else:
print(f"x is {x}.")
main()
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
This is my implementation, but it not efficient when given 6 digit number.
Input : n = 2
Output : 9009
9009 is the largest number which is product of two
2-digit numbers. 9009 = 91*99.
def isPali(x):
n = str(x)
for i in range(len(n)):
if not n[i] == n[-i-1]:
return False
return True
def isProduct(x,A):
counter = A
while counter > 1:
if x // counter <= A and x % counter == 0:
return True
else:
counter-=1
return False
def largestProduct(A):
for i in range(A*A,1,-1):
if isPali(i) and isProduct(i,A):
return i
return False
largestProduct(999999)
Let x and y be the two n-digit factors of the palindrome number.
You can iterate over them in a descending number.
Key is to stop as soon as possible, which mean, once a first solution has been found, you don't check any product below that solution.
def get_max_palindrome(n):
res = 0
for x in range(10 ** n - 1, 1, -1):
for y in range(10 ** n - 1, 1, -1):
p = x * y
if res > p:
break
if str(p) == str(p)[::-1]:
res = p
break
if (x - 1) ** 2 < res:
break
return res
print(get_max_palindrome(6))
Exec in 0.378s on my laptop.
Codewise, this is not too difficult:
n = 999999
max_pali =0
t = ()
for i in range(1,n+1):
for j in range(i,n+1):
m = i*j
s = str(m)
if s == s[::-1] and m > max_pali:
max_pali = m
t = (i,j)
print(max_pali,t)
However, this is a brute force approach. For numbers with 6 digits, this will not terminate in a reasonable amount of time. Even if it will, I could ask you the same question for 7 or 42 digits. I suggest you look for some structure, or property, of those numbers whose multiple is a palindrome. Could such a pair be any pair of numbers? Is the case 91*99 = 9009 a mere coincidence, or is there a pattern?
I'm trying to write a python function number_pairs which consumes a natural positive number n, and reads in n pairs of natural positive numbers from the user. Each pair represents a value and its frequency. For each pair, the function must prompt the user to input two positive integers the value and its frequency, while indicating the index of the expected pair. The process repeats until all n pairs have been entered. At the end, the function should print the average (of Float type, with the exact string message as in the example) of the n pairs of numbers, and returns the average as well. You may assume that the user only inputs valid data.
I was thinking that maybe writing a helper function that does accumulative recursion but I missed a lot of lectures and I have no idea how to do it. This is what I have so far:
def averge_h(counter):
...
def number_pairs(n):
prompt1 = "Enter value for pair number "
prompt2 = "Enter its frequency:\n"
pn = "{0}: ".format(n)
res="Their average is: "
v = int(input(prompt1+pn))
f = int(input("Enter its frequency: "))
if n = 1:
average = (v*f)/f
else:
v = v+1
print res + str(average)
return average
You can try something like this :
def read_and_avg(sum_,n,left,i): ## left is the number of times the input is to be taken
if left == 0:
print (sum_/float(n))
return (sum_/float(n))
else:
i = i + 1
print "Enter the values for pair number "+str(i)
a = int(input())
b = int(input())
sum_ = sum_ + (a*b) ## Increment the sum
n = n + b ## Increment the total count
print sum_,n,left
return read_and_avg(sum_,n,left-1,i) ## Decrease left by 1,
def func(n):
read_and_avg(0,0,n,0)
Since you said it can only have one argument "n" take a look at this:
def number_pairs(n):
if n == 0:
return 0
else:
average = number_pairs(n-1)
print str(n) + ("st" if n == 1 else ("nd" if n == 2 else ("d" if n == 3 else "th"))) + " pair"
val = input("value: ")
frq = input("frequency: ")
print "" # added for new line
return average + (val * frq)
n = input("Enter the number of pairs: ")
print "" # added for new line
print "The average is: " + str(number_pairs(n) / n)
Output:
Enter the number of pairs: 5
1st pair
value: 1
frequency: 2
2nd pair
value: 2
frequency: 2
3d pair
value: 3
frequency: 2
4th pair
value: 4
frequency: 2
5th pair
value: 5
frequency: 2
The average is: 6