n = int(input("Input n: "))
c = int(input("Input c: "))
def it_show(n, c):
counter= 0
for i in range(1, n 1):
if i < 10:
if i == c:
counter = 1
if i > 9:
digit = i % 10
if digit == c:
counter = 1
i //= 10
return counter
print(it_show(n, c))
From the start sory my English is not so good.
In the task it is emphasizes to work with numbers, no strings.
I need to input n and c.Program need to return in how many numbers from 1 to n(including n), c show up.Etc. n=20 and c=5 return is 2.Because from 1 to 20, 5 show up in numbers 5 and 15, that is 2 numbers.In this code for this case it works.But if I input n=14 and c=1 return is 2, but it needs to bee 6 because from 1 to 14(including 14) there are 6 numbers that have c(1) in them (1, 10, 11, 12, 13, 14).
CodePudding user response:
You can use a while
to cycle through the digits.
def it_show(n, c):
counter = 0
for i in range(1, n 1):
while i > 0:
if i % 10 == c: # if the right digit is equal to c
counter = 1
break # counter increased, and no need to check the other digits
i //= 10 # integer division to eliminate the right digit, which was already checked
return counter
print(it_show(20,5))
print(it_show(14,1))
CodePudding user response:
n = int(input("Input n: "))
c = int(input("Input c: "))
def it_show(n, c):
sc = str(c)
counter= 0
for i in range(1, n 1):
if str(i).count(sc):
counter = 1
return counter
print(it_show(n, c))
compare strings like this will make it simpler to understand and (likely) faster.
CodePudding user response:
You can check if a number is a substring of another number as a string.
n = 14
c = 1
def it_show(n, c):
counter=0
for i in range(1,n 1):
if str(c) in str(i):
counter = 1
return counter
print(it_show(n, c))
[Output]
6
CodePudding user response:
It would be easier if you convert numbers to string and then count the number of numbers
from digits:
n = int(input("Input n: "))
c = int(input("Input c: "))
def it_show(n, c):
counter= 0
c_str = str(c)
for i in range(1, n 1):
num_str = str(i)
if c_str in num_str: # if number c exists in number i
counter = 1
return counter
print(it_show(n, c))
Output
Input n: 14
Input c: 1
6
CodePudding user response:
def it_show(n,c):
counter = 0
for i in range(1,n 1):
if str(c) in str(i):
counter =1
return counter