Sum of digits in recursion - python-3.x

Super-sum S of an integer x is defined as x if x is single digit number otherwise Super-sum of x is defined as Super-sum of digit-sum of x. Given two numbers n,k find the Super-sum of the number formed when n is concatenated k times.Note that k is only multiplied with the number when it is at least a 2 digit number
Input:
1987 4
Output:
1
Is there a faster method than this?
s,k=input().split()
summ=0
for ele in s:
summ+=int(ele)
s=summ*int(k)
while s>=10:
s=str(s)
summ=0
for ele in s:
summ+=int(ele)
s=summ
print(s)

n,k=map(int,input().split())
if n<10:
print(n)
else:
if ((n*k)%9==0):
print(9)
else:
res=(n*k)%9
Any number greater than 9 will have digits repeated that's why you need to take mod of 9 for example 13 will have sum of 1+3 =4 and 13 %9=4 .There will be a special case when mod of 9 will be zero and this will be at number 9,18,27,36 etc which are divisible by 9 and their sum will always be 9 hence return 9 .

The formula used in the accepted answer should actually be proved. So, let's do this.
First, let's prove that for any positive integer number N, N modulo 9 is the same sum of its digits modulo 9.
Having proved the statement above, we easily conclude that N % 9 provides the needed digit as per challenge description. The only exception is if N % 9 == 0, then a digit is 9.

Related

Hacker rank problem - code optimisation and debugging logical errors required to pass all the test cases for the below python program

This problem is regarding sets, here is an array arr of integers. There are also disjoint sets, A and B, each containing integers. You like all the integers in the set A and dislike all the integers in set B. Your initial happiness is 0. For each integer in the array, if i belongs to A, you add 1 to your happiness. If i belongs to B, you add -1 to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end.
Note: A and B are set, they have no repeated elements. However, the array might contain duplicate elements.
In the below code, I have tried to take input n,m
k = list(map(str,input().split(' ')))
n,m =k
arr=[]
arr = [int(i) for i in input().split()]
arr1 = list( dict.fromkeys(arr) )
A=set(int(i) for i in input().split())
B=set(int(i) for i in input().split())
a=len(set(arr1).intersection(A))
b=len(set(arr1).intersection(B))
print(a-b)
Input Format
The first line contains integers n and m and separated by a space.
The second line contains n integers, the elements of the array.
The third and fourth lines contain m integers, A, and B, respectively.
Input
**1** **2**
3 2 13 4
1 5 3 1 7 8 5 3 7 9 4 9 8 2 1 4
3 1 1 5 3 9
5 7 7 4 2 8
Output
1 0
The above piece of code works for small input test cases but it results as the Wrong answer for the rest.
Follow the link for the actual problem statement
This is the code I used but it was unable to clear most test cases. Need help.

I want to improve speed of my algorithm with multiple rows input. Python. Find average of consequitive elements in list

I need to find average of consecutive elements from list.
At first I am given lenght of list,
then list with numbers,
then am given how many test i need to perform(several rows with inputs),
then I am given several inputs to perform tests(and need to print as many rows with results)
every row for test consist of start and end element in list.
My algorithm:
nu = int(input()) # At first I am given lenght of list
numbers = input().split() # then list with numbers
num = input() # number of rows with inputs
k =[float(i) for i in numbers] # given that numbers in list are of float type
i= 0
while i < int(num):
a,b = input().split() # start and end element in list
i += 1
print(round(sum(k[int(a):(int(b)+1)])/(-int(a)+int(b)+1),6)) # round up to 6 decimals
But it's not fast enough.I was told it;s better to get rid of "while" but I don't know how. Appreciate any help.
Example:
Input:
8 - len(list)
79.02 36.68 79.83 76.00 95.48 48.84 49.95 91.91 - list
10 - number of test
0 0 - a1,b1
0 1
0 2
0 3
0 4
0 5
0 6
0 7
1 7
2 7
Output:
79.020000
57.850000
65.176667
67.882500
73.402000
69.308333
66.542857
69.713750
68.384286
73.668333
i= 0
while i < int(num):
a,b = input().split() # start and end element in list
i += 1
Replace your while-loop with a for loop. Also you could get rid of multiple int calls in the print statement:
for _ in range(int(num)):
a, b = [int(j) for j in input().split()]
You didn't spell out the constraints, but I am guessing that the ranges to be averaged could be quite large. Computing sum(k[int(a):(int(b)+1)]) may take a while.
However, if you precompute partial sums of the input list, each query can be answered in a constant time (sum of numbers in the range is a difference of corresponding partial sums).

Alternate between printing two series of numbers

Input format: The first line of input consists of the number of test cases, T
Next T lines consist of the value of N.
Constraints: 1<= T <=100, 1<= N <= 250
Output format: For each test case, print the space-separated N terms of the series in a separate line.
Sample test case 1
Input:
1
7
Output:
1 1 2 2 4 2 6
The series is a combination of 2 series, the 1st series: 1,2,4,6,... and the 2nd series: 1,2,2,.... I have made the code for the first series but cannot find how to code the 2nd one.
Code for the first series appended into list depending on the no of elements
def firstS:
l=[1]
i=1
x=math.ceil(7/2)
while(x!=0):
l.append(i+i)
i+=1
x-=1
return l
The problem is the no of elements, for 7 elements the 1st series has 4 and 2nd series has 3 elements, for 8 elements 1st has 4 and 2nd has 4 elements and for 9 elements 1st has 5 and 2nd has 4 elements so the no of elements will be for series 1 math.ceil(n/2) and for series 2 math.floor(n/2) where n is total elements of the combined series.
For iteration, one way do something every N iterations is to use the modulus operator (%). Modulus is basically a remainder operator, so the result periodically repeats as numbers are iterated one-by-one.
Also, in Python, the standard method for doing a for-loop (iterating a certain number of times) is using range.
Here's an example demonstrating both, where every third number has the same number of exclamation marks:
# List the numbers 0-9 (repeat ten times)
for i in range(0, 10):
if i % 3 == 0:
print(i, "!")
elif i % 3 == 1:
print(i, "!!")
else:
print(i, "!!!")
Result:
0 !
1 !!
2 !!!
3 !
4 !!
5 !!!
6 !
7 !!
8 !!!
9 !
I'll leave it as an exercise for the asker to determine how to apply this to their use-case of switching between printing two different sequences.

How can I solve this classical dynamic programming problem?

There are N jewellery shop(s). Each jewellery shop has three kinds of coins - Gold, Platinum, and Diamond having worth value A, B, and C respectively. You decided to go to each of N jewellery shop and take coins from each of the shop. But to do so following conditions must satisfy -
You can take at most 1 coin from an individual shop.
You can take at most X coins of Gold type.
You can take at most Y coins of Platinum type.
You can take at most Z coins of Diamond type.
You want to collect coins from shops in such a way that worth value of coins collected is maximised.
Input Format :
The first line contains an integer N. Where N is the number of jewellery shops.
The second line contains three integers X, Y, Z. Where X, Y, Z denotes the maximum number of coins you can collect of type Gold, Platinum, and diamond respectively.
Then N lines contain three space-separated integers A, B, C. Where A, B, C is the worth value of the Gold, Platinum, and diamond coin respectively.
Output Format :
Print a single integer representing the maximum worth value you can get.
Constraints :
1
<=
N
<=
200
1
<=
X
,
Y
,
Z
<=
N
1
<=
A
,
B
,
C
<
10
9
Example : -
4
2 1 1
5 4 5
4 3 2
10 9 7
8 2 9
Answer:-
27(9+9+5+4)
I tried the obvious greedy approach but it failed :-)

how many numbers of n digits in a mobile number pad

if we are given a mobile phone with number pad as
9 8 7
6 5 4
3 2 1
* 0 #
and a number n , then how many numbers of n digit we can make my typing in keypad , we can not move diagonally from a previously chosen number i.e from if we have typed 9 the next no i can choose is 8 or 6 . Also number like 082 will be count as 2 digit number not 3.
sample test case
input n = 1 output = 9
input n = 2 output = 25
I am unable to formulate a dynamic programming/backtracking solution for it .
Let f(n) be the list of all sequences composed of n digits.:
The base case is simple: f(1) = [ 1, 2, ..., 9 ].
In the general case, how can you compute f(n) from f(n-1)? Simply loop over the elements of f(n-1) and check the last digit. Say f(2) contains 85, then f(3) should contain 852, 854 856, and 858. Add all these new elements in a new list and return it.

Resources