kaprekar numbers - python

def kaprekar_num(num):
count = 0
while count <= num:
n = 1
sqr = n ** 2
digits = str(sqr)
length = len(digits)
for x in range(1, length):
left = int("".join(digits[:x]))
right = int("".join(digits[x:]))
if (left + right) == n:
print("Number: " + str(n) + ", Left: " + str(left) + " + " + " Right: " + str(right) + " = " + str(n))
n += 1
count += 1
else:
n += 1
kaprekar_num(5)
hello guys,
I'm new to python programming and I got a task in class to print the first 5 kaprekar numbers.
(I only have C programming background...)
I have a problem with the "for x in range..." line.. the code doesn't enter the loop and I don't know why.
the program needs to print:
Number: 9, Left: 8 + Right: 1 = 9
Number: 10, Left: 10 + Right: 0 = 10
Number: 45, Left: 20 + Right: 25 = 45
Number: 55, Left: 30 + Right: 25 = 55
Number: 99, Left: 98 + Right: 1 = 99
I will appreciate some insights :)

for loop was fine, you had some logic issue, which you haven't handled, like when n==1 and when len(sqr)==1.
def kaprekar_num(num):
count = 0
n=1
while count <= num:
sqr = n ** 2
digits = str(sqr)
length = len(digits)
if sqr==1:
print("Number: " + str(n) + " = " + str(n))
count+=1
n+=1
elif length>1:
for x in range(1,length):
left = int("".join(digits[:x]))
right = int("".join(digits[x:]))
if (left + right) == n:
print("Number: " + str(n) + ", Left: " + str(left) + " + " + " Right: " + str(right) + " = " + str(n))
n += 1
count += 1
else:
n += 1
else:
n+=1
kaprekar_num(5)

How you're managing the n value is incorrect. It should be set before the loop starts, then after each try, regardless of the outcome, it should increment.
def kaprekar_num(num):
count = 0
# Start n at one, and don't reset it on each loop
n = 1
while count <= num:
sqr = n ** 2
digits = str(sqr)
length = len(digits)
for x in range(1, length):
left = int("".join(digits[:x]))
right = int("".join(digits[x:]))
if (left + right) == n:
print("Number: " + str(n) + ", Left: " + str(left) + " + " + " Right: " + str(right) + " = " + str(n))
count += 1
# This number is a Kaprekar number, so break out of the loop
break
# Regardless of the status of this number, try the next one
n += 1
kaprekar_num(5)
And as a recommendation: I'd highly recommend you look into stepping through the code with a debugger in the future. If you had done so, you'd have seen that n is not changing fairly quickly.

you've set the loop to repeat once i think, if you meant to put n instead of 1, i think thats the problem.
Try to set the loop to this instead
for x in range(n, length):

Related

How can i add a While loop to detect errors in the input in python

So, i am trying to write a code to not only do arithmetic equations, but also, give feedback if there is an error as well as give me 3 tries max. any advice?
arithmetic=input("Enter an arithmetic operation:")
arithmetic= arithmetic.replace(" ", "")
w=arithmetic.split('/')
x= arithmetic.split('-')
y=arithmetic.split('+')
z=arithmetic.split('*')
if ("+" in arithmetic):
a= int(y[0])
b= int(y[1])
sum = a + b
print("The result is = " + str(sum))
elif ("*" in arithmetic):
a= int(z[0])
b= int(z[1])
result = a * b
print("The result is = " + str(result))
elif ("/" in arithmetic):
a= int(w[0])
b= int(w[1])
result = a / b
result = round(result,3)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x)==3):
a= int(x[1])
b= int(x[2])
result = a + b
result = result * (-1)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x)==2):
a= int(x[0])
b= int(x[1])
result = a - b
print("The result is = " + str(result))
#tries = 0
#while(tries < 3):
# arithmetic=input("Enter an arithmetic operation:")
# match = arithmetic.find('+')
# print(match)
# if(match == -1):
# print ("Invalid")
# tries += 1
# else:
# tries= 3
I tried to add the while in the beginning. However, when i put an input such as 11 and 12 without the + sign, it just printed the input without giving me an error. why is that?
tries = 0
while tries < 3:
arithmetic = input("Enter an arithmetic operation:")
arithmetic = arithmetic.replace(" ", "")
w = arithmetic.split('/')
x = arithmetic.split('-')
y = arithmetic.split('+')
z = arithmetic.split('*')
try:
if ("+" in arithmetic):
a = int(y[0])
b = int(y[1])
sum = a + b
print("The result is = " + str(sum))
elif ("*" in arithmetic):
a = int(z[0])
b = int(z[1])
result = a * b
print("The result is = " + str(result))
elif ("/" in arithmetic):
a = int(w[0])
b = int(w[1])
result = a / b
result = round(result, 3)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x) == 3):
a = int(x[1])
b = int(x[2])
result = a + b
result = result * (-1)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x) == 2):
a = int(x[0])
b = int(x[1])
result = a - b
print("The result is = " + str(result))
else:
print("Invalid")
tries += 1
continue
break
except ValueError: # for case split not working good due cases like first input is a negative number
print("Invalid")
tries += 1
At the end of your if / else if chain, just add:
else:
print("invalid")
tries += 1
Replace everything you have inside your while loop currently with the uncommented code above it and that should work.

space-separated string of all positive numbers that are divisible by 2.For example, even_numbers(6) returns “2 4 6”

def even_numbers(maximum):
return_string = ""
for x in ___:
return_string += str(x) + " "
return return_string.strip()
print(even_numbers(1)) # No numbers displayed
def even_numbers(maximum):
return_string = ""
for x in range(1,maximum+1):
if x%2==0:
return_string += str(x) + " "
return return_string.strip()
You can use this
def even_numbers(maximum):
return_string = ""
for x in range(2, maximum + 1, 2):
return_string += str(x) + " "
return return_string.strip()
print(even_numbers(6)) # prints 2, 4, 6
def even_numbers(maximum):
return_string = ""
for x in range(0, maximum + 1):
if x != 0 and x % 2 == 0:
return_string += str(x) + " "
return return_string.strip()
print(even_numbers(6)) # Should be 2 4 6
print(even_numbers(10)) # Should be 2 4 6 8 10
print(even_numbers(1)) # No numbers displayed
print(even_numbers(3)) # Should be 2
print(even_numbers(0)) # No numbers displayed

How to make output of python function stdout format?

I'm trying to solve a problem where I need to create a function but I need the output to be in stdout format. This is the code i have been working on:
def oddNumbers(l, r):
s = ""
if l % 2 == 0:
if r % 2 == 0:
for i in range(l + 1, r, 2):
s += str(i) + " "
else:
for i in range(l + 1, r + 1, 2):
s += str(i) + " "
else:
if r % 2 == 0:
for i in range(l, r, 2):
s += str(i) + " "
else:
for i in range(l, r + 1, 2):
s += str(i) + " "
return s
This code works for single digit outputs but doesn't work for double digit or triple digit answers. How do I get the proper output in stdout format? Any help would be appreciated. thanks!
for example, for oddNumbers(2, 6), I get the ouput:
3
5
which is correct
but for double-digit outputs such as oddNumbers(96, 97), I get the output:
9
7
which is not correct.
i am supposed to get
97
i don't know how to fix this.
Not sure what you mean. The code works for all answers.
def oddNumbers(l, r):
s = ""
if not l % 2:
if not r % 2:
for i in range(l+1, r, 2):
s += str(i) + " "
else:
for i in range(l+1, r+1, 2):
s += str(i) + " "
else:
if not r % 2:
for i in range(l, r, 2):
s += str(i) + " "
else:
for i in range(l, r+1, 2):
s += str(i) + " "
return s
print(oddNumbers(0,10**4))
outputs every other number from 1 to 9999

What is wrong with my nested while loop for counting the element

I just want to figure out how often each element of F occurs within N and print it out. I have used the nested for loop, it works. But when I used nested while loop, it did not work as expected. I checked my code but cannot find out why.
F = [4,7,2]
N = [2,3,4,2,5,6,3,2,6,7,3,4]
Nested for loop version, works as expected:
four_count = 0
seven_count = 0
two_count = 0
for n in N:
for f in F:
if n == f and f == 4:
four_count += 1
elif n == f and f == 7:
seven_count += 1
elif n == f and f == 2:
two_count += 1
print(str(F[0]) + " occurs in N " + str(four_count) + " times")
print(str(F[1]) + " occurs in N " + str(seven_count) + " times")
print(str(F[2]) + " occurs in N " + str(two_count) + " times")
This is correct output:
4 occurs in N 2 times
7 occurs in N 1 times
2 occurs in N 3 times
Nested while loop version, wrong output:
four_count = 0
seven_count = 0
two_count = 0
N_Count = 0
F_Count = 0
while N_Count < len(N):
while F_Count < len(F):
if N[N_Count] == F[F_Count] and F[F_Count] == 4:
four_count += 1
elif N[N_Count] == F[F_Count] and F[F_Count] == 7:
seven_count += 1
elif N[N_Count] == F[F_Count] and F[F_Count] == 2:
two_count += 1
F_Count += 1
N_Count += 1
print(str(F[0]) + " occurs in N " + str(four_count) + " times")
print(str(F[1]) + " occurs in N " + str(seven_count) + " times")
print(str(F[2]) + " occurs in N " + str(two_count) + " times")
Wrong output from nested while loop:
4 occurs in N 0 times
7 occurs in N 0 times
2 occurs in N 1 times
You have to reset F_Count = 0 after while N_Count < len(N):, otherwise list F is only looped once. So it would be:
...
while N_Count < len(N):
F_Count = 0
while F_Count < len(F):
...
But unless you're learning about loops, this would not be the best way to do what you want. Something using count would be better, like:
counts = [N.count(f) for f in F]
or similar

Why won't values between 100 and 1000 work when playing Four is Magic, excluding values by 100

Everything works besides values between 100 and 999, except values divisible by 100 work.
The game is as follows:
Four is magic. Write a Python program (called q3.py) that given an integer from 0 to 1000 does the “4 is magic” transformation. The steps are as follows:
Convert the integer n into English and count the number of letters (i.e. 21 is “twenty one” and consists of 9 letters, 102 is “one hundred two” and consists of 13 letters, 1000 is “one thousand” and consists of 11 letters).
Let nlen be the length of the English word equivalent for the integer n.
a. If nlen is 4, output “four is magic.” Then, terminate the transformation process.
b. Otherwise output “ is nlen.” Repeat
step (a), where the integer n is set to nlen.
Suppose the user inputs the integer 26. Then, the transformation proceeds as follows.
26 is 9. , where twenty six is the 9-letter English word equivalent of 26.
9 is 4. , where nine is the 4-letter English word equivalent of 9.
4 is magic.
def convert(number_str):
# Enter your code here.
count = 0
index = 0
x = ['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
y = ['zero','ten','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
while (number_str != '4'):
if 0 <= int(number_str) <= 19:
a = len(x[int(number_str)])
print(x[int(number_str)],'is',a)
number_str = str(a)
elif 20 <= int(number_str) <= 99:
if number_str[1] == "0":
a = len(y[int(number_str[0])])
print(y[int(number_str[0])],'is',a)
number_str = str(a)
else:
a = len(y[int(number_str[0])]) + len(x[int(number_str[1])])
print(y[int(number_str[0])] + ' ' + x[int(number_str[1])],'is',a)
number_str = a
elif 100 <= int(number_str) <= 999:
rem = int(number_str) % 100
div = int(number_str) // 100
if rem == 0:
a = len(x[div]) + 7
print(x[div] + ' hundred is',a)
number_str = str(a)
else:
if (number_str[1] == '0'):
a = len(x[div]) + 7 + len(convert(str(rem)))
print(x[div] + ' hundred ' + convert(str(rem)) + ' is '+ str(a))
number_str = str(a)
elif (number_str[1] != '0'):
a = len(x[div]) + 6 + len(convert(str(rem)))
print(x[div] + ' hundred ' + convert(str(rem)) + ' is '+ str(a))
number_str = str(a)
elif number_str == '1000':
a = 11
print('one thousand is '+ str(a))
number_str = str(a)
return 'four is magic'
def main():
''' The program driver. '''
user_input = input('> ')
while user_input != 'quit':
print(convert(user_input))
user_input = input('> ')
main()
My question is what is wrong with this area:
else:
if (number_str[1] == '0'):
a = len(x[div]) + 7 + len(convert(str(rem)))
print(x[div] + ' hundred ' + convert(str(rem)) + ' is '+ str(a))
number_str = str(a)
elif (number_str[1] != '0'):
a = len(x[div]) + 6 + len(convert(str(rem)))
print(x[div] + ' hundred ' + convert(str(rem)) + ' is '+ str(a))
number_str = str(a)
convert always returns "four is magic" It looks like you want it to return some value based on its input.
def convert(number_str):
# Enter your code here.
count = 0
index = 0
x = ['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
y = ['zero','ten','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
while (number_str != '4'):
if 0 <= int(number_str) <= 19:
a = len(x[int(number_str)])
print(x[int(number_str)],'is',a)
number_str = str(a)
elif 20 <= int(number_str) <= 99:
if number_str[1] == "0":
a = len(y[int(number_str[0])])
print(y[int(number_str[0])],'is',a)
number_str = str(a)
else:
a = len(y[int(number_str[0])]) + len(x[int(number_str[1])])
print(y[int(number_str[0])] + ' ' + x[int(number_str[1])],'is',a)
number_str = a
elif 100 <= int(number_str) <= 999:
rem = int(number_str) % 100
div = int(number_str) // 100
print(div)
if rem == 0:
a = len(x[div]) + 7
print(x[div] + ' hundred is',a)
number_str = str(a)
else:
if (number_str[1] == '0'):
a = len(x[div]) + 7 + len(str(x[rem]))
print(x[div] + ' hundred ' + str(x[rem]) + ' is '+ str(a)) # error was here
number_str = str(a)
elif (number_str[1] != '0'):
a = len(x[div]) + 6 + len(str(x[rem]))
print(x[div] + ' hundred ' + str(x[rem]) + ' is '+ str(a)) # error was here
number_str = str(a)
elif number_str == '1000':
a = 11
print('one thousand is '+ str(a))
number_str = str(a)
return 'four is magic'
def main():
''' The program driver. '''
user_input = input('> ')
while user_input != 'quit':
print(convert(user_input))
user_input = input('> ')
main()
Where I commented #error you were doing recursion which was not what you wanted ( I think). But fixed it and it should work now. When you call recursive functions (calling the same function) it execute the newest call on the stack, returning the value it came back with, which isn't how your program worked.
Also I noticed you weren't calling x[rem] like you were suppose to for a look up on the spelling, fixed that too.
Next time please include desired output instead of making us fish for information.

Categories

Resources