I'm writing a program that takes a number from input and generates it's palindrome number. My program only prints the first half not the second. I tried reverse, didnt work.I have incluede those lines as comment.
My Code:
def show_palindrome(maximum):
maximum = int(input("Enter Number : "))
for number in range(1, maximum + 1):
temporary = number
reverse = 0
while (temporary > 0):
reminder = temporary % 10
reverse = (reverse * 10) + reminder
temporary = temporary //10
if(number == reverse):
#number2 = number[::-1]
#print(number,number2, end = '')
print(number, end = '')
show_palindrome(3)
My output:
123
The output I need:
12321
I believe you're looking for something like this:
def show_palindrome(maximum = None):
if not maximum:
maximum = input("Enter Number : ")
output = str(maximum)
for number in range(1, int(maximum)):
output = str(int(maximum) - number) + str(output) + str(int(maximum) - number)
return output
print(show_palindrome(3))
this returns 12321 for instance
A couple of things I would do differently in your function:
If you're going to require the input in the def (The way you make it optional is to set it equal to something when you declare it like I have it set to None (maximum=None), then you don't need the input() statement.
Since you already know how long you want it to be ( you require it declared when you initialize the function, it's just 2*maximum - 1) there's really no need to use a while loop.
Other than that good job! Keep it up!
You can try something simpler like this:
def show_palindrome():
num = input("Enter Number : ")
print(num + num[:-1][::-1])
show_palindrome()
Input:
123
12
1
Output:
12321
121
1
Apart from the string slice method (as used by #PApostol), you could also use the reversed method :
def show_palindrome():
value = input("Enter Number : ")
print(value[:-1] + "".join(reversed(value)))
Input:
123
Output:
12321
def palindrome(maximum):
number = ''.join([str(num) for num in range(1, maximum + 1)])
return int(number + number[-2::-1])
print(palindrome(3))
Output:
12321
Your code seems over complicated, and I don't even know what to fix in it. What I can tell is that passing a parameter maximum to overwrite it just after with maximum = int(input("Enter Number : ")) is useless, don't pass the parameter.
So let's back to easy things
Build palindrome using strings method : slicing backwards from index -2, and reverse it with -1 increment
def show_palindrome():
value = input("Enter Number : ")
print(value + value[-2::-1])
Build palindrome using math operations : save the remainder, except the first one
def show_palindrome():
value = input("Enter Number : ")
result = value
value = int(value) // 10 # remove last char which would be redundant
while value > 0:
result += str(value % 10)
value = value // 10
print(result)
show_palindrome()
Related
I have a function that converts an integer to binary.
def conversion(num):
if num >= 1:
conversion(num // 2)
i = str(num % 2)
return i
num = int(input('Enter number'))
print(conversion(num))
This returns 1 which is only the first value in the actual answer
The code below gets me the answer I am looking for (101) but I want to be able to return that value instead of having the function perform the print
def conversion(num):
if num >= 1:
conversion(num // 2)
i = str(num % 2)
print(i,end=' ')
return
num = int(input('Enter number'))
conversion(num)
The only reason this prints the answer all on one line is because of the end=' '
How do I actually store the value as 101 all on one line and return it as i?
You can notice that you have called the function inside it. That concept's name is recursion. And every time the recursing is performed, you should save the result of that recursing step or do something with the result...
Your second funtion did that, it print out the results of every step you divide the number by two, so on the output you can see them in order.
In your first one, you forget to use the result so try to move conversion(num // 2) to the place it should be in.
And I'm sure you realize that PRINTING the answer is very different from RETURNING the answer. What you need to do is build up the components in a list, then join the list into a string:
def conversion(num):
answer = []
while num > 0:
answer.insert(0, str(num%2))
num = num // 2
return ''.join(answer)
num = int(input('Enter number'))
print(conversion(num))
Note that I use "insert" to add the digits in the proper order, since the higher bits have to go in the left side.
This question already has answers here:
Python Memory Error while iterating to a big range
(3 answers)
Closed 6 years ago.
Sorry I have to ask such a simple question, but I've been trying to do this for a while with no luck, despite searching around.
I'm trying to define a function that will get user input for X, and then add every integer from 0 to X, and display the output.
For example, if the user inputs 5, the result should be the sum of 1 + 2 + 3 + 4 + 5.
I can't figure out how to prompt the user for the variable, and then pass this variable into the argument of the function. Thanks for your help.
def InclusiveRange(end):
end = int(input("Enter Variable: ")
while start <= end:
start += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, start))
Just delete argument "end" from function header and use your function.
InclusiveRange()
or define code in other way:
def InclusiveRange(end):
while start <= end:
start += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, start))
end = int(input("Enter Variable: ")
InclusiveRange(end)
Here's an itertools version:
>>> from itertools import count, islice
>>> def sum_to_n(n):
... return sum(islice(count(), 0, n + 1))
>>>
>>> sum_to_n(int(input('input integer: ')))
input integer: 5
15
You should take the user input out of the function, and instead call the function once you have received the user input.
You also need to store the sum in a separate variable to start, otherwise you're only adding 1 each iteration. (I renamed it to index in this example as it reflects it's purpose more).
def InclusiveRange(end):
index = 0
sum = 0
while index <= end:
sum += start
index += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, sum))
end = int(input("Enter Variable: "))
InclusiveRange(end)
Demo
Instead of using a loop, use a range object, which you can easily send to sum(). Also, you're never actually using the passed end variable, immediately throwing it away and binding end to a new value. Pass it in from outside the function.
def inclusive_range(end):
num = sum(range(end+1))
print("The total of the numbers, from 0 to {}, is: {}".format(end, num))
inclusive_range(int(input("Enter Variable: ")))
You can also use a math formula to calculate the sum of all natural numbers from 1 to N.
def InclusiveRange(end):
''' Returns the sum of all natural numbers from 1 to end. '''
assert end >= 1
return end * (end + 1) / 2
end = int(input("Enter N: "))
print(InclusiveRange(end))
number1 = int(input('Number #1: '))
number2 = int(input('Number #2: '))
l = len(str(number1))
l1 = len(str(number2))
print()
def addition():
print(' ',max(number1,number2))
print('+')
print(' ',min(number1,number2))
print('-'*(max(l,l1)+2))
print(' ')
print(' ',number1+number2)
def carries():
while (int(str(number1)[::-1])+int(str(number2)[::-1]))>=10:
carries = 0
carries = carries + 1
return carries
addition()
print()
print('Carries : ',carries())
I am trying to make a program that does the addition of two user input numbers and calculates the answer while also stating how many carries there are. Carries being if 9+8=17, then there would be 1 carry and so forth. I am having issues with having my program go beyond 1 carry. So this program so far is only applicable for user input numbers that when added are below 99. If you could explain to me how I would go about altering this program to make it applicable to any numbers, that would be great. I was thinking about using the len(number1) and len(number2) and then inputting the string of the user input backwards so it would look like str(number1[::-1])) but I do not think it works like that.
Fun one-liner solution
def numberOfCarryOperations(a, b):
f=lambda n:sum(map(int,str(n)));return(f(a)+f(b)-f(a+b))/9
# f is the digitSum function :)
Explanation
Asserting a,b >=0, you can proof mathematically: every time you have a carry, the digitSum decreases by 9.
9, because we are in number system 10, so we "lose 10" on one digit if we have carry, and we gain +1 as the carry.
Readable solution
def digitSum(n):
return sum(map(int,str(n)))
def numberOfCarryOperations(a, b)
# assert(a >= 0); assert(b >= 0);
return (digitSum(a) + digitSum(b) - digitSum(a+b)) / 9
I rewrote your carry function so it works, but the implementation is totally different. You first make the numbers strings so you can iterate through them. Then you make them equal length by appending 0's, and loop through each digit to check whether their sum (plus the carry) is over 9. If it is, increment the counter. Hope this helps:
number1 = int(input('Number #1: '))
number2 = int(input('Number #2: '))
l = len(str(number1))
l1 = len(str(number2))
print()
def addition():
print(' ',max(number1,number2))
print('+')
print(' ',min(number1,number2))
print('-'*(max(l,l1)+2))
print(' ')
print(' ',number1+number2)
def carries():
num1 = str(number1)
num2 = str(number2)
carry = 0
carries = 0
c1 = l
c2 = l
if (l < l1):
while (c1 < l1):
num1 = '0' + num1
c1+=1
if (l1 < l):
while (c2 < l):
num2 = '0' + num2
c2+=1
i = c1
while (i > 0):
if (int(num1[i-1])+int(num2[i-1])+carry > 9):
carry = 1;
carries+=1
else:
carry = 0
i-=1
return carries
addition()
print()
print('Carries : ',carries())
Edited with quick fix
Your while loop is fatally flawed.
You set carries to 0 every time, and then add 1, so there's no way to return anything but 0.
The return is inside the loop, so you will always return after the first iteration.
If the ones digits don't provide a carry, then you never get into the loop, and return None.
You don't provide for multiple carries, such as the three carries in 999 + 1.
If you remove the return from the while loop, you have an infinite loop: the terms of the condition never change. You don't iterate through anything.
You gave a function and a variable the same name. This is not good practice.
Here's a start for you, based loosely on your original routine.
Set the count of carries to 0.
Convert the two numbers to strings and find the common (shorter) length.
So long as you have digits in both numbers, grab the digits (moving from the right end) and see whether their numeric sum requires a carry. If so, increment the count.
def carries():
carry_count = 0
str1 = str(number1)
str2 = str(number2)
for digit_pos in range(1, min(len(str1), len(str2)) + 1):
if int(str1[-digit_pos]) + int(str2[-digit_pos]) >= 10:
carry_count += 1
return carry_count
Sample output:
Number #1: 77077
Number #2: 4444
77077
+
4444
-------
81521
Carries : 3
This still has deficiencies for you to fix. Most notably, it doesn't handle multiple carries. However, it should get you moving toward a solution.
How do I display the number of one's in any given integer number?
I am very new to python so keep this in mind.
I need the user to input a whole number.
Then I want it to spit out how many one's are in the number they input.
i am using python 3.3.4
How would I be able to do this with this following code?
num = int(input ("Input a number containing more than 2 digits"))
count = 0
for i in range (0):
if num(i) == "1":
count = count + 1
print (count)
I don't know what i'm doing wrong
it gives me 'int' object is not callable error
Something like this:
Int is not iterable so you may need to convert into string:
>>> num = 1231112
>>> str(num).count('1')
4
>>>
str(num).count('1') works just fine, but if you're just learning python and want to code your own program to do it, I'd use something like this, but you're on the right track with the code you supplied:
count = 0
for i in str(num):
if i == "1":
count = count + 1 # or count += 1
print(count)
Just to help you, here is a function that will print out each digit right to left.
def count_ones(num):
while num:
print(num % 10) # last digit
num //= 10 # get rid of last digit
num = 1112111
answer = str(num).count("1")
num = int(input (" Input a number to have the number of ones be counted "))
count = 0
for i in str(num):
if i == "1":
count = count + 1 # or count += 1
print (' The number of ones you have is ' + str(count))
So i took the user input and added it to the correct answer since when i tried the answer from crclayton it didn't work. So this works for me.
I must create two functions. One that can tell whether one number is odd or even by returning t/f, and the other will call the first function then return how many even numbers there are.
This is my code so far:
Even = [0,2,4,6,8]
IsEvenInput = int(input("Please enter a number: "))
def IsEvenDigit(a):
if a in Even:
return True
else:
return False
y = IsEvenDigit(IsEvenInput)
print(y)
def CountEven(b):
count = 0
for a in b:
if IsEvenDigit(a):
count+=1
return count
d = input("Please enter more than one number: ")
y = CountEven(d)
print(y)
This keeps outputting 0 and doesn't actually count. What am I doing wrong now?
d = input("Please enter more than one number: ")
This is going to return a string of numbers, perhaps separated by spaces. You'll need to split() the string into the sequence of text digits and then turn those into integers.
There's a general approach to determining whether a number is odd or even using the modulus / remainder operator, %: if the remainder after division by 2 is 0 then the number is even.
Here is another approach:
def is_even(number):
return number % 2 == 0
def even_count(numbers_list):
count = 0
for number in numbers_list:
if is_even(number): count += 1
return count
raw_numbers = input("Please enter more than one number: ")
numbers_list = [int(i) for i in raw_numbers.split()]
count = even_count(numbers_list)
print(count)
This will take care of all other numbers too.
So by calling CountEvent(d) outside the scope of the function CountEven, you aren't using recursion, you're simple calling the function after it's been defined.
Try reducing the amount of code outside of your functions.
#Start by declaring your functions:
def isEven(n):
return n % 2 == 0
def countEven():
count = 0
string_of_numbers = input("Please enter numbers separated by spaces: ")
list_of_number_characters = string_of_numbers.split(' ')
for number in list_of_number_characters:
number_as_int = int(number)
if isEven(number_as_int) == True:
count = count + 1
print("There were " + str(count) + " even numbers found.")
countEven() #Call the function that runs your program
You are counting whether the integers - [0, 2, 4, 6, 8] etc. - are characters in a string - "0", "2", "4", "6", "8" etc. Currently, IsEvenDigit(a) will never be true, because a character in a string will not be in the list of even integers, so the code beneath the if statement will never be executed. You need IsEvenDigit(int(a)) in the CountEven function.
On another topic, a commenter to your post suggested reading PEP 8. Your code is actually formatted pretty well, its just in Python, CamelCase is used just for classes, and words_seperated_by_underscores is used for variables and function names.
Or if you want brevity and unreadability, some code:
main = lambda: sum(map(lambda x: int(x) % 2 == 0, (i for i in input("Enter a number: "))))
main()
It does define 2 (anonymous) functions!
A possible solution:
def is_even(n):
return not n % 2
def count_even(numbers)
return sum(map(is_even, numbers))
nums = input("Enter numbers separated by spaces: ")
nums = map(int, nums.split())
print(count_even(nums))