No response in python - python

I wrote a simple code for:
enter any number and a digit and count how many times the digit is in the number.
the code i wrote is:
num= int(input("enter a number"))
n=num
digit = int(input("enter the digit"))
times=0
while n > 0 :
d = n%10
if d==digit :
times += 1
continue
else:
continue
n=n//10
print ("no. of times digit gets repeated is ", times)
When I tried this code, somehow it gave me nothing

Remove the else and continue statements because the loop always hits the continue and never goes to n=n//10
num= int(input("enter a number"))
n=num
digit = int(input("enter the digit"))
times=0
while n > 0 :
d = n%10
if d==digit :
times += 1
n=n//10
print ("no. of times digit gets repeated is ", times)
Output:
enter a number1111222233344567433232222222
enter the digit2
no. of times digit gets repeated is 12

if d==digit :
times += 1
continue
else:
continue
n=n//10
There is no way to reach the code line above that divides n by ten because both the true and false branches restart the loop with continue, hence n will never change value and you'll loop forever (for non-zero number input).
You should remove continue from both branches and, in fact, you don't need the else part since it doesn't do anything:
if d == digit:
times += 1
n = n // 10

The line n=n//10 never gets executed because of the continues before it. You don't need continue if you don't intend to skip the remaining of this loop iteration.

The other answers point out your continue misuse, but there're a couple Pythonic ways to do this.
divmod() neatly does division and modulus in one operation:
num = int(input("enter a number"))
digit = int(input("enter the digit"))
times = 0
while num > 0:
num, d = divmod(num, 10)
if d == digit:
times += 1
print("no. of times digit gets repeated is ", times)
You can also more simply not do anything with numbers, but with strings, and use str.count:
num = input("enter a number")
digit = input("enter the digit")
print("no. of times digit gets repeated is ", num.count(digit))

Related

Count number of digits using for loop in Python

I want to count number of digits of any digits number without converting the number to string and also using for loop. Can someone suggest how to do this.
num = int(input("Enter any number : "))
temp = num
count = 0
for i in str(temp):
temp = temp // 10
count += 1
print(count)
If you stick to using input, you can't get away the fact that this function prompts a String. As for the for loop, simply count the number of characters in the input string:
num = input("Enter any number : ")
print(len(num))
You don't have to create a temp variable as num already contains the input.
If there should only digits being entered, you can first check that with a pattern, then get the length of the string without using any loop.
import re
inp = input("Enter any number : ")
m = re.match(r"\d+$", inp)
if m:
print(len(m.group()))
else:
print("There we not only digits in the input.")
i = int(input('num : '))
j=0
while i:
j+=1
i//=10
print(j)
Repeats dividing the entered number stored in i by 10 and adds 1 to j (result) Checks From i if it finds it equal to 0 it exits the iteration and prints the result j
i = 103
j = 0
#inside repetition :
i//=10 #i=10
j+=1 #j=1
i!=0 #completion
i//=10 #i=1
j+=1 #j=2
i!=0 #completion
i//=10 #i=0
j+=1 #j=3
i==0 #break
print j #result

Finding unique 9 digit numbers

I'm writing a program that accepts as input a 9 digit number with each number from 1-9 (i.e 459876231) The program takes that number and then finds the next highest number with the same digits. The code I have works, but only when I put the print statement within the for loop.
n = int(input("Please input a 9 digit number"))
n_str = str(n)
n_str1 = str(n+1)
while n < 1000000000:
for char in n_str:
if not char in n_str1:
n += 1
n_str1 = str(n)
print(n)
If I put don't indent the print statement to where it is now, the program will not work. Putting the print statement here also displays every number that the program tries on the way to the correct number, and I only want to display the final answer. Why is this happening? I've tried storing n in a completely new variable and then trying to print outside the loop but get the same thing.
It's because if you do n += 1, n will be 1, then 2, 3.., so you need to print n every time. If you print n outside of the for, it will only print its last value.
Your code is fixed like:
n = int(input("Please input a 9 digit number: "))
n_str = str(n)
n_str1 = str(n+1)
while n < 1000000000:
found = True
for char in n_str:
if not char in n_str1:
n += 1
n_str1 = str(n)
found = False
break
if found:
print(n)
break
There is a bug in your condition
for char in n_str:
if not char in n_str1:
If input number is 333222323, n_str1 is 333222324, digit check char in n_str1 would be all true and 333222323 would be the result.
I find the LeetCode problem 31. Next Permutation is quite similar to your question, and there are already many recommended solutions, most are more efficient than yours.
This example code is based on my LeetCode answer:
nstr = input("Please input a 9 digit number: ")
nums = [int(c) for c in nstr]
l = len(nums) # length should be 9
for i in range(l-2, -1, -1):
swap_idx, swap_n = None, None
for j in range(i+1, l):
if (nums[i] < nums[j]) and (not swap_n or (nums[j] < swap_n)):
swap_idx, swap_n = j, nums[j]
if swap_idx:
tmp = nums[i]
nums[i] = nums[swap_idx]
nums[swap_idx] = tmp
break
nums = nums[:i+1] + sorted(nums[i+1:])
print(''.join([str(i) for i in nums]))
With a test:
Please input a 9 digit number: 459876231
459876312
Please input a 9 digit number: 333222323
333222332

using the calculation number for the next calculation

experts.
I'm trying to define a function (collatz) that:
Asks for a number. If it is even it prints number // 2, if it odd it prints 3 * number + 1. (OK)
The result, whatever it is, must enter a loop until the result is 1. (NOK)
So, i´m not figure out because the result is not used and is in an infinite loop. Any suggestion?
def collatz():
number = int(input('Enter the number: '))
x = number % 2
while number != 1:
if x == 0:
print(f'{number // 2}')
else:
print(f'{3 * number + 1}')
number = number
print(f'{collatz()}')
You need to actually assign the result back to number.
As well:
The divisibility check needs to be in the loop.
The outer print() is not needed.
The f-strings are redundant. print() converts its arguments to string automatically.
def collatz():
number = int(input('Enter the number: '))
while number != 1:
if number % 2 == 0:
number //= 2 # Short for "number = number // 2"
else:
number = 3*number + 1
print(number)
collatz()
Example run:
Enter the number: 3
10
5
16
8
4
2
1

Cycling the digits of a 5 digit number in a function

I'm trying to solve this problem but I'm just stuck at the very end.
I need to make a function that cycles the 5 digit number around. So for example, the input is 12345 and then it should be 51234, 45123 etc. Then when it cycles it out, until it's at the beginning again which is 12345, it should print out the biggest number of all of the cycled ones.
def number_cycle(number):
if number >= 99999 or number < 9999:#this is for limiting the number to 5 digits
print('Error,number isnt in 5 digit format')
else:
e = number%10 #5th digit
d = int(((number-e)/10)%10)#4th digit
c = int(((((number - e)/10)-d)/10)%10)#3rd digit
b = int(((((((number - e)/10)-d)/10)-c)/10)%10)#2nd digit
a = int(((((((((number - e)/10)-d)/10)-c)/10)-b)/10)%10)#1st digit
print(e,a,b,c,d)
print(d,e,a,b,c)
print(c,d,e,a,b)
print(b,c,d,e,a)
print(a,b,c,d,e)
number = eval(input('Input number:'))
I can't figure out how to get the biggest number out of all these.
Can you help?
You can try this solution:
def get_largest(number):
num_str = str(number)
num_len = len(num_str)
if num_len != 5:
print(f"Error: {number} is not a 5 digit number")
return
largest = 0
for i in range(num_len):
cycled_number = int(num_str[i:] + num_str[:i])
print(cycled_number)
if cycled_number > largest:
largest = cycled_number
print("Largest: ", largest)
number = int(input("Input number: "))
get_largest(number)
It will basically convert your 5 digit number to a string using a for loop, and then rotate the string, compare the rotated numbers and print the largest one.
Note:
In your original code snippet I'd suggest not to use the built-in eval method as it can be quite dangerous if you don't know what you are doing so avoid it as much as you can except you really have no other way to deal with a problem. More here:
https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
https://medium.com/swlh/hacking-python-applications-5d4cd541b3f1

python for loop wont change value

So im new to python and this question should be fairly easy for anybody in here except me obvisouly haha so this is my code
for c in range(0,20):
print("number",c+1)
number = input ("Enter number:\n")
number = int(number)
if (number < 1 or number > 9):
print("try again by inputing a positive number < 10")
c -=1
so as you may think if the number someone inputs is bigger than 9 or smaller than 0 i just want my c to stay where it is so i get 20 positive numbers from 1-9 instead it doesnt do that and it keeps increasing even tho i have the c-=1 thingy down there
First, do not use range(0,20) but range(20) instead.
Second, range returns an iterator. This means, that when you do c-=1 you do not go back in the iterator, you decrease the number returned by the iterator. Meaning that if c=5 and the number you entered in input is 20, c will become 4, but when returning to the start of the loop, c be be 6.
You probably want something of this sort:
c = 0
while c < 20:
print("number",c+1)
number = input ("Enter number:\n")
number = int(number)
if (number < 1 or number > 9):
print("try again by inputing a positive number < 10")
continue
c += 1
an alternative and simple solution to this would be:
i=20
while(i!=0):
number = input("Enter number:\n")
number = int(number)
if (number <1 or number >9):
print("Invalid no try within 0-9 ")
else
print(number)
i-=1

Categories