Python | addition of pattern 1 22 333 4444 55555​ ....? - python

How do i do addition of 1 22 333 4444 55555​ ....?
i) case 1: n = 1, v = 1
ii) case 2: n= 2, v = 23 (Note: 23 is derived as 1 + 22)
def create_sequence():
n = int(input('Enter the number till which you want the sequence:'))
for i in range(1,n+1):
print(str(i) * i)
create_sequence()

You generate a sequence of elements of the form str(i)*i, which you cast into an integer, then sum that sequence.
def create_sequence(n):
return sum(int(str(i)*i) for i in range(1, n+1))
create_sequence(int(input('Enter the number till which you want the sequence: ')))

Take advantage of loops, they are your friend
def create_sequence():
n = int(input('Enter the number till which you want the sequence:'))
sum = 0
for x in range(1, n+1):
string = ""
for i in range(1, x+1):
string += str(x)
sum += int(string)
return sum
print(create_sequence())

Related

Explain the logic of 'Count of N-digit numbers with absolute difference of adjacent digits not exceeding K' in Detail

Can someone please help me understand the logic of following Dynamic Programmming question Found this one at geeksforgeeks.com. I am unable to understand even after going through the answer provided.
Question:
Count of N-digit numbers with absolute difference of adjacent digits
not exceeding K | Set 2
Given two integers N and K, the task is to
find the count of N-digit numbers such that the absolute difference of
adjacent digits in the number is not greater than K.
Examples:
Input: N = 2, K = 1
Output: 26
Explanation: The numbers are 10, 11,
12, 21, 22, 23, 32, 33, 34, 43, 44, 45, 54, 55, 56, 65, 66, 67, 76,
77, 78, 87, 88, 89, 98, 99
Input: N = 3, K = 2
Output: 188
Python3 solution:
# Function to return the count of such numbers
def getCount(n, K):
# For 1-digit numbers, the count is 10 irrespective of K
if(n == 1):
return 10
# dp[j] stores the number of such i-digit numbers ending with j
dp = [0] * 11
# Stores the results of length i
next = [0] * 11
# Initialize count for 1-digit numbers
for i in range(1, 9 + 1):
dp[i] = 1
# Compute values for count of digits greater than 1
for i in range(2, n + 1):
for j in range(9 + 1):
# Find the range of allowed numbers if last digit is j
l = max(0, j - k)
r = min(9, j + k)
# Perform Range update
next[l] += dp[j]
next[r + 1] -= dp[j]
# Prefix sum to find actual count of i-digit numbers ending with j
for j in range(1, 9 + 1):
next[j] += next[j - 1]
# Update dp[]
for j in range(10):
dp[j] = next[j]
next[j] = 0
# Stores the final answer
count = 0
for i in range(9 + 1):
count += dp[i]
return count
if __name__ == '__main__':
n = 2
k = 1
print(getCount(n, k))
This code is contributed by Shivam Singh
Link: https://www.google.com/amp/s/www.geeksforgeeks.org/count-of-n-digit-numbers-with-absolute-difference-of-adjacent-digits-not-exceeding-k-set-2/amp/
I am unable to understand the logic in following lines
# Compute values for count of
# digits greater than 1
for i in range(2, n + 1):
for j in range(9 + 1):
# Find the range of allowed
# numbers if last digit is j
l = max(0, j - k)
r = min(9, j + k)
# Perform Range update
next[l] += dp[j]
next[r + 1] -= dp[j]
# Prefix sum to find actual count
# of i-digit numbers ending with j
for j in range(1, 9 + 1):
next[j] += next[j - 1]
# Update dp[]
for j in range(10):
dp[j] = next[j]
next[j] = 0
N=2 so we are dealing with strictly 2 digit numbers
K=1 so each digit in the current number shall be no more than 1 digit greater or less than its neighbors
While the answer is 26 (the count of such numbers), lets take a look at why the answer includes 10, 11, and 12 but not 13
10 is good as the absolute value of 1 - 0 (the digits of 10) is less than or equal to 1 (the value of K)
13 is bad as the absolute value of 1 - 3 is 2 and 2 is greater than K
Note that as N increases, the number of pairwise digit comparisons required will also increase.
I'll skip parsing someone else's code with meaningless variable names. Here is how I might attempt to solve this:
def is_valid_number(number_to_test, allowed_digit_spread):
if number_to_test < 10:
# apparently all 1 digit numbers pass
return True
# get the individual digits as a list
digits = [int(digit) for digit in str(number_to_test)]
for i in range(1, len(digits)):
current_digit = digits[i]
prior_digit = digits[i-1]
if abs(current_digit - prior_digit) > allowed_digit_spread:
# bad pairwise compare so reject
return False
return True
def get_numbers_to_test(allowed_digits):
start = pow(10, allowed_digits -1)
end = pow(10, allowed_digits)
return range(start, end)
def getCount(allowed_digits, allowed_digit_spread):
count = 0
for n in get_numbers_to_test(allowed_digits):
if is_valid_number(n, allowed_digit_spread):
count += 1
return count
if __name__ == '__main__':
n = 2
k = 1
print(getCount(n, k))

Find the Number which does not contain the digit d

I need the numbers from 1-100 which does not having the digit 1 and 7, eg 0,2,3,4,5,6,8,9,22,23,24,25 so on. Below is the sample code to find the Number which contain the digit d. I need to modify according to my requirement.
def isDigitPresent(x, d):
# Breal loop if d is present as digit
while (x > 0):
if (x % 10 == d):
break
x = x / 10
# If loop broke
return (x > 0)
# function to display the values
def printNumbers(n, d):
# Check all numbers one by one
for i in range(0, n+1):
# checking for digit
if (i = d or isDigitPresent(i, d)):
print(i,end=" ")
# Driver code
n = 500
d = 0
print("The number of values are")
printNumbers(n, d)
It's a lot easier if you convert the integer into a string and check just check if '7' or '1' are in the string. If not, print it.
def printNumbers(n):
for i in range(0, n + 1):
str_int = str(i)
if not '7' in str_int and not '1' in str_int:
print(i, end=" ")
# Driver code
n = 500
print("The number of values are")
printNumbers(n)
returns
The number of values are
0 2 3 4 5 6 8 9 20 22 23 24 25 26 28 29 30 32 33 ...
You can create a function that checks a digit individually.
def not_contain(num):
nums = list(str(num))
res = [i for i in nums if i not in ['1', '7']]
return True if len(res) == len(nums) else False
Then use filter() to get the results you want.
mylist = [i for i in range(101)]
res = list(filter(not_contain, mylist))
# [0, 2, 3, 4, 5, 6, 8, 9 ------, 99]
Here's modifying your way to work:
def isDigitPresent(x, d):
# Breal loop if d is present as digit
while x > 0:
if int(x % 10) in set(d):
return True
x //= 10
return False
def printNumbers(n, d):
# Check all numbers one by one
for i in range(0, n + 1):
# checking for digit
if not isDigitPresent(i, d):
print(i, end=" ")
# Driver code
n = 500
d = [1, 7]
print("The number of values are")
printNumbers(n, d)

How to create a function to find numbers divisible by 7 but not by 5

Im trying to write a function named find_numbers that will find all numbers divisible by 7 and not by 5.
My issue is the actual function
this is what I have so far:
def find_numbers(lower_bound, upper_bound):
for i in range(lower_bound,upper_bound):
if (i % 7 == 0 and i % 5 !=0):
print(i)
return ()
do i have the correct parameters? what exactly am i returning? I feel that i'm close to the correct solution, but I really am stuck :( It's printing out what I want, sort of, but not correctly. Any help is really appreciated!! Thank you all.
lower_bound = int( input("Lower bound to search for numbers: ") )
upper_bound = int( input("Upper bound to search for numbers: ") )
found_numbers = find_numbers(lower_bound, upper_bound)
print("The numbers that are divisible by 7 but not by 5
are:\n{}".format(found_numbers))
def find_numbers(lower_bound, upper_bound):
results=[]
for i in range(lower_bound,upper_bound):
if (i % 7 == 0 and i % 5 !=0):
results.append(i)
return results
lower_bound = int( input("Lower bound to search for numbers: ") )
upper_bound = int( input("Upper bound to search for numbers: ") )
found_numbers = find_numbers(lower_bound, upper_bound)
print("The numbers that are divisible by 7 but not by 5
are:\n{}".format(found_numbers))
You can use a simple list comprehension for this purpose.
result = [x for x in range(lower_bound, upper_bound) if x % 7 == 0 and x % 5 != 0]
You can wrap it in a function if you want to make more elegant and re-usable like this.
def find_numbers(lower_bound, upper_bound):
return [x for x in range(lower_bound, upper_bound) if x % 7 == 0 and x % 5 != 0]
lower_bound = int( input("Lower bound to search for numbers: ") )
upper_bound = int( input("Upper bound to search for numbers: ") )
found_numbers = find_numbers(lower_bound, upper_bound)
print("The numbers that are divisible by 7 but not by 5 are:\n{}".format(found_numbers))
It can be seen that this method of list comprehension will run a little faster than conventional looping solution.
There are several things wrong in the logic:
It will only print the last value found
the return statement is not right
What if there is not number in that range
I'd modify it like this:
In [1]: def find_numbers(L, U):
...: r = []
...: for i in range(L, U):
...: if i % 7 == 0 and i % 5 != 0:
...: r.append(i)
...: if not r:
...: return None
...: else:
...: return r
...:
You can think of it like pattern, offset, instead of lower and upper bounds.
7 * 5 = 35 => you’ll have a harmonic pattern of length 35, where 7, 14, 21, 28 are your numbers of interest, 35 is the one you skip. Add n * 35 as offset and you have the infinity at the reach of your hands 😏
Sorry to use java. On the go with my cell it’s what I have on the top of my mind easier.
List<Integer> pattern = Arrays.asList(7, 14, 21, 28);
Stream.iterate(0, offset -> offset + 1)
.forEach(offset -> pattern.stream()
.forEach(p -> print(35 * offset + p))
);

Three digit size N odometer

I want to generate all possible outputs of a list of size N that acts as a 3 digit odometer. For example, if N = 4, I want the following output:
0000
1000
2000
3000
0100
1100
...
3332
3333.
Here is my code, any help is much appreciated!
odom = [0]*N ## initialize odometer
print odom
while odom[N-1] <= 3:
idx = 1
odom[0] += 1
if odom[0] > 3:
while odom[idx] > 3:
idx += 1
for i in range(idx):
odom[i] = 0
print odom
def foo(n, digits = 4):
if digits == 0:
return ''
msb, lsb = divmod(n, 4)
return str(lsb) + foo(msb, digits - 1)
result = []
number_of_digits = 4
maxn = sum(3 * pow(number_of_digits,n) for n in range(number_of_digits))
for n in range(maxn + 1):
result.append(foo(n, number_of_digits))
result = [foo(n, number_of_digits) for n in range(maxn + 1)]
foo_4 = functools.partial(foo, digits=4)
result = list(map(foo_4, range(maxn + 1)))
The easy way is to just use itertools.product:
import itertools
for odom in itertools.product('0123', repeat=4):
print ''.join(odom)
If you need to increment the first digit first, you can use ''.join(odom)[::-1] instead.
The order of your example doesn't seem to be correct given that it starts by incrementing the first digit by one but it ends by incrementing the last digit by one. Assuming you just want to increase the first digit by 1 in base 4 with 4 digits (change the print if you're using python 2)
import numpy as np
def odo(numdigits, maxdigit):
x = 1
while len(np.base_repr(x, base=maxdigit)) <= numdigits:
padding = numdigits - len(np.base_repr(x, base=maxdigit))
yield np.base_repr(x, base=maxdigit, padding=padding)[::-1]
x += 1
for x in odo(4, 4):
print(x)

codeabbey : list index out of range

Here is the question:
Let us calculate sum of digits, as earlier, but multiplying each digit by its position (counting from the left, starting from 1). For example, given the value 1776 we calculate such weighted sum of digits (let us call it "wsd") as:
wsd(1776) = 1 * 1 + 7 * 2 + 7 * 3 + 6 * 4 = 60
Here is my code:
digitlist = []
numlist = []
def splitdigit(number):
numlist = []
digitlist = []
numlist.append(number)
while number >= 1:
number = number/10
numlist.append(number)
del numlist[-1]
for ele in numlist:
digitlist.append(ele%10)
return digitlist
# digit part
# test if the split digit work here:
# print (splitdigit(1234)) it works
times = int(input())
raw = raw_input()
string = raw.split()
nlist = []
outbox = []
rout = 0
res = 0
n = 0
for item in string:
nlist.append(int(item))
# print (nlist) [it worked]
for element in nlist:
# check for split method : checked
# formula to make the digit work: n = len(out) | while(n>1): n=n-1
# rout=out[-n]*n res=res+rout(res=0)
n = len(splitdigit(element))
print (n)
res = 0
while n >= 1:
rout = (splitdigit(element)[(n*(-1))]) * n # I HAVEN"T CHECK THIS FORMULA OUT !!!
res = res + rout
n = n + 1
outbox.append(res)
print (outbox)
print(" ".join(str(x) for x in outbox))
And here is my running error:
> 3
9 15 1776
1
Traceback (most recent call last):
File "13.py", line 39, in <module>
rout = splitdigit(element)[(n*(-1))] * n # I HAVEN"T CHECK THIS FORMULA OUT !!!
IndexError: list index out of range
and I checked it in interactive python. I think I am not asking for a item out of range but it gives me this error. I hope someone can help me out. Thank you, love you all.
You are thinking way too complicated.
def wsd(number):
digits = [int(i) for i in str(number)]
result = 0
for index, value in enumerate(digits):
result += (index + 1) * value
return result
print(wsd(1776))
Output:
60

Categories