I feel like this should work correctly but I get an error with the count being 1 less than it should be.
def palindrome_chain_length(n):
count = 0
while str(n) != str(n)[::-1] :
n = n+n
count += 1
else:
return count
If you just get count 1 less than you want, start with count = 1.
And it seems to me that it should be:
n += int(str(n)[::-1])
instead of:
n = n + n
(see comment #alfasin).
Related
My task is to find how many times we need to multiply digits of a number until only one digit left and count how many "turns" we need to take until that 1 digit left.
Example:
39 -> 3*9=27 -> 2*7=14 -> 1*4=4, so the answer should be 3.
So far I got:
def persistence(n):
count = 1
sum = int(str(n)[0:1]) * int(str(n)[1:2])
while(n > 0 or sum > 9):
sum = int(str(sum)[0:1]) * int(str(sum)[1:2])
count = count + 1
print(sum)
print("how many times: " + count)
persistence(39)
So how I approached this task:
I take first 2 digits convert them to str and multiply them.
Already with first sum I go to while loop and keep repeating that.
So, my problem is that I keep getting this:
How can I solve it? Or should I try to approach this task differently?
You only have a couple of problems.
The while loop keeps checking n. It only needs to check sum
The final print tries to add an int to a str. Just use print arguments instead.
def persistence(n):
count = 1
sum = int(str(n)[0:1]) * int(str(n)[1:2])
while sum > 9:
sum = int(str(sum)[0:1]) * int(str(sum)[1:2])
count = count + 1
print(sum)
print("how many times: ", count)
persistence(39)
Output as expected.
However, you should not use sum as the name of a variable. You can reuse n instead:
def persistence(n):
count = 1
n = int(str(n)[0:1]) * int(str(n)[1:2])
while n > 9:
n = int(str(n)[0:1]) * int(str(n)[1:2])
count = count + 1
print(n)
print("how many times: ", count)
This should work.
def returnLength(n):
return len(str(n))
def returnProduct(n, pro=1):
n = str(n)
for i in n:
pro *= int(i)
return pro
n = int(input())
c = 0
while returnLength(n) != 1:
n = returnProduct(n)
c += 1
print(c)
So basically at the start my program had Achilles heel, because it's failed when I had 3+ digit number. I read every suggestion very carefully and my final code went like this:
def persistence(n):
def returnLength(n):
return len(str(n))
def returnProduct(n, pro=1):
n = str(n)
for i in n:
pro *= int(i)
return pro
c = 0
while n > 9:
n = returnProduct(n)
c += 1
print(c)
However, I still couldn't pass the test nevertheless everything worked fine on VScode and I did some random manual testing (I'm practicing at codewars.com and a lot of people wrote that on this task's test might have a bug). It might be that I can have only one def. I will try to figure that out. Once again, thank you all.
i have a problem when i try to find if a number is factorial
this is what I've done so far:
i = 1
count = 0
while n>1:
if n % i == 0:
n /= i
else:
break
i+=1
if n<=1:
count += 1
return count
but it returns 1 and I don't know how to fix
As written, the value of count in your example code indicates whether or not the number n is a factorial number, for a single n.
If it is, then at some point n <= 1, so count will be incremented, and the value of count returned by the function will be 1. If it is not, then at some point before n <= 1, n % i == 0 will be False, the loop will break, and the returned value of count will be 0.
Note, though, that there is an edge case not covered by your example code as is. Namely, 1 is a factorial number (1! = 1). But if n is 1, the condition on the while loop is never True, so the function immediately returns 0. So, you need to change the condition in the while loop.
E.g.
def isfactorialnumber(n):
i = 1
count = 0
while n >= 1:
if n % i == 0:
n /= i
else:
break
i += 1
if n <= 1:
count += 1
return count
I have 2 further comments about this code.
First, in the context of this new function, the variable name count is misleading. What is it counting? Nothing, really. It can only take 2 values, 1 or 0. It would be better then, to use a boolean variable, and call it result or similar. Even better, get rid of the variable and refactor your code as:
def isfactorialnumber(n):
i = 1
while n >= 1:
if n % i == 0:
n /= i
else:
break
i += 1
if n <= 1:
return True
return False
Which is equivalent but a little better.
Second, a more readable, natural way to solve the problem would be to work from bottom-up. That is, solve the problem by generating the factorial numbers, m that are less than or equal to n, then checking if the last m is equal to n. This leads to more concise and understandable code IMO.
E.g.
def isfactorialnumber(n):
m = 1
i = 1
while m < n:
m *= i
i += 1
return m == n
Finally, assuming each number in your file, is on its own line:
with open('factorials.txt') as infile:
print(len([1 for line in infile if isfactorialnumber(int(line))]))
Will print the number of factorial numbers in the file factorials.txt
count = 0
for n in listOfNumbers:
i = 1
while n>=1:
if n % i == 0:
n /= i
else:
break
i+=1
if n<=1:
count += 1
return count
def per(n,steps=0):
if len (str(n))==1:
print(n)
print "TOTAL STEPS" + str(steps)
return "DONE"
steps += 1
digits = [int(i)for i in str(n)]
result = 1
for j in digits:
result *= j
print(result)
per(result,steps)
count = 0
while True:
print count
count += 1
str(wantedresult) == 12
str(steps) >= 11
if str(steps) == str(wantedresult)
print str(n)
break
I am noob.
I have another encoded and working code in my pockets(metaphorically) but not in a loop
so i wanted my results like this example in my other code is this
if my number is 277777788888899 it has an output of this
4996238671872
438939648
4478976
338688
27648
2688
768
336
54
20
0
0
TOTAL STEPS11
ummm you might need this
my error in the first code is
File "source_file.py", line 21
if str(steps) == str(wantedresult)
^
SyntaxError: invalid syntax
I think what you're trying to accomplish is to find the smallest number with a persistance of wantedresult by brute forcing all the number one by one? If so, here's something that does not differ too much from your first version:
def per(n,steps=0,display=False):
# display the number at each iteration
if display:
print(n)
if len(str(n)) > 1:
steps += 1
digits = [int(i)for i in str(n)]
result = 1
for j in digits:
result *= j
steps = per(result,steps,display)
return steps
wantedresult = 6
persistance = 0
count = 0
while True:
count += 1
persistance = per(count)
if persistance == wantedresult:
print('The smallest number with a persistance of', wantedresult, 'is', count)
per(count,display=True) # display the iterations for this number
print('TOTAL STEPS', wantedresult)
break
However it is suitable only for small persistance number and it might take a while if you want to find 277777788888899 with this approach.
BTW the syntax error you got is because you forgot the colon after the if statement.
Hope it helped.
for homework in an introductory python class, one of the questions is to count the number of even numbers in n. here's my code so far:
def num_even_digits(n):
i=0
count = 0
while i < n:
i+=1
if n%2==0:
count += 1
return count
print(num_even_digits(123456))
Pythonic answer:
def num_even_digits(x):
return len([ y for y in str(x) if int(y) % 2 == 0])
print(num_even_digits(123456))
Disclaimer: I recognized that, for an introductory Python class, my answer may not be appropriate.
you are comparing the whole number every time. you need to convert it to a string and then loop over every number in that string of numbers, cast it back to an integer and see if its remainder is 0
def num_even_digits(numbers):
count = 0
numbers = str(numbers)
for number in numbers:
try:
number = int(number)
except ValueError:
continue
if number % 2 == 0:
count += 1
return count
print(num_even_digits(123456))
if you want to actually loop through every possible number in the range of 0 to your large number you can do this.
def num_even_digits(numbers):
count = 0
for number in range(0, numbers):
if number % 2 == 0:
count += 1
return count
print(num_even_digits(10))
problems with your current function:
def num_even_digits(n): # n is not descriptive, try to make your variable names understandable
i=0
count = 0
while i < n: # looping over every number from 0 to one hundred twenty three thousand four hundred and fifty six.
i+=1
if n%2==0: # n hasn't changed so this is always going to be true
count += 1
return count
print(num_even_digits(123456))
How do I get my num_digit function to return 1 instead of 0 whenever I put in 0 as the parameter in the function?
How do I get the function to return any integer such as negative numbers?
def num_digits(n):
count = 0
while n:
count = count + 1
n = abs(n) / 10
return count
I was working on question number 2 first. Even if I put the abs(n) in the line of code where while is, I still get an infinite loop which I still do not really understand why. I figured if I can get my n value to always be positive and input in say -24, it would convert it to 24 and still count the number of values.
On question 1, I do not know where to start, ive tried:
def num_digits(n):
count = 0
while n:
if n == 0:
count = count + 1
n = n / 10
return count
I forgot to add I have limited tools to use since I am still learning python. I have gotten up to iterations and am studying the while loops and counters. I have not gotten to break yet although I have an idea of what it does.
When in doubt, brute force is always available:
def num_digits(n):
if n == 0:
return 1
if n < 0:
return num_digits(abs(n))
count = 0
while n:
count = count + 1
n = n / 10
return count
Process the exceptional cases first, and then you only have to deal with the regular ones.
If you want to avoid the conditionals, I suggest taking abs(n) only once, at the beginning, and using an infinite loop + break for the 0 case:
def num_digits(n):
n = abs(n)
count = 0
while True:
count = count + 1
n = n / 10
if n == 0:
break
return count
For a more practical solution, you can either count the number of digits in the string (something like len(str(n)) for positive integers) or taking log base 10, which is a mathematical way of counting digits.
def num_digits(n):
if n == 0:
return 0
return math.floor(math.log10(math.abs(n)))