getting incorrect answer. what is wrong with this code? - python

x=raw_input('what is your favorite number? ')
n=x*10
print n
If I plug in 5, I don't get 50. I get 5555555
I have tried declaring float(n) and tooling around with it. nothing helped. I realize this is minor league, but I am just starting to teach myself python.
Thanks, Todd

You are taking in your number as raw_input, meaning, it is returned to the program as a string. When you multiply a string by an integer and print the result, it just prints the string x times, in your case 10 because you attempted to multiply by 10. To prove this, change, the 10 to 20 and watch what happens.
There are two ways to fix this. The first would be to use input() instead of raw_input(), so that it returns a number as a result.
x=input("Please enter a number here.\n")
The second way would be to reassign x to the integer equivalent of the string, using the function int().
x=int(x) # Will turn "10", which is what you have, into 10
This should solve your problem.
Best of luck, and happy coding!

This is because the default data type of raw_input() is string. You have to cast the string input to an integer for achieving the desired result.

When you read a value in from user input like this it is as a string. So x actually equals the string '5' but what you actually want is the number 5.
int(x) * 10

Related

Why am I not getting 333 in Python

num=int(input("what is your number"))
total=int(input("how many times do you want this number to appear"))
new_num=0
for i in range (total):
new_num=num*10
new_num=new_num+num
print (new_num)
I keep getting 33, even when i changed my range to (total+1). What must I do to get 333
When you have a problem like this use a debugger (python includes one in pdb) to step through the code and see how variables change.
In simple cases just use print. In this case put a print(new_num) after each time you assign to new_num.
In this case you will notice where new_num gets set to the wrong value.
You keep assigning new_num=num*10 instead of multiplying new_num by 10
As I understood from your question, the value of num you are taking as 3. And for total as well the same 3.
Note: Always try to provide some examples while posting your problem so that the answerers could read, understand & suggest, help.
I have a quick solution for you here, just try and try to modify for other purposes.
int(f'{num}' * total) is sufficient to give you that. You can change it a bit and do for floats as well.
>>> num=int(input("what is your number: "))
what is your number: 3
>>>
>>> total=int(input("how many times do you want this number to appear: "))
how many times do you want this number to appear: 3
>>>
>>> int(f'{num}' * total)
333
>>>
Thanks.

Python: Finding the length of a float with zeros at the end

I have several float values that have necessary zeros at the ends.
One number that I have is 0.0013790.
When finding the length of this, I get 8 when I should be getting 9, since the zero at the end is dropped. I can not use .format(), since some numbers are shorter than others and there is no concrete length that I want them set to. If I had a float that was seven digits long after the decimal and set the format to 8, I would get an extra zero which should NOT belong there.
I can not afford to have my program adding zeros through format when they are not always necessary, since some numbers will be shorter than others. How do I find the actual length of these numbers when a zero is at the end?
I can not make an if statement that checks if the number .endswith 0, because it never does. The zero is always dropped! I am already checking the length of the string of the float and still the zero is dropped! Many numbers will not end with zero, so I can not simply add one to the length found. Please help!
Numbers to test:
When inputting _, you should get _. If you can get the below to work along with some other numbers, please give me the solution. I've been racking at my brain for hours!! Thanks.
WANTED RESULTS: 0.12345 -> 7, 0.123450 -> 8, 0.1234500 -> 9.
UPDATE:
Thank you for your solutions, but the numbers are not inputs. I have them set to the eval() function, since I have roughly 1000 variables that need to be accessed dynamically from a websocket. Values are retrieved just fine, but if I am not mistaken, eval() defaults to float. Switching it from float to string has not done me much good, since I am guessing that eval() is always a float. Any solutions??
You need to store your values as strings if you want to track length independent of the value of the float.
Floating point values have no length, and trailing 0s do not affect the value so they produce identical floats. This means after it gets defined, there is no way to determine whether 0.12345 was defined using 0.12345 or 0.12345000000.
0.12345 is 0.123450 # True
0.12345 is 0.1234500 # True
len(0.12345) # TypeError: object of type 'float' has no len()
Everything works fine for the string representation of those floats:
"0.12345" is "0.123450" # False
"0.12345" is "0.1234500" # False
len("0.12345") # 7
Thus you should store these values as strings, and convert them to float when necessary.
If you first convert the input to a number, and then to a string, you'll lose any insignificant digits.
If you are asking the user to enter the value:
>>> foo = input('Enter the number here: ')
Enter the number here: 0.0013790
>>> len(foo)
9
If you are using Python 2, make sure you use raw_input and not input
As long as you don't cast the value to a float, you should get correct values for len().
Then we have to store the float as a string value. Following lines may be answer to the question where it is a default behaviour.
mynum = input('Enter your number: ')
print('Hello', mynum)
print(len(mynum))

Why do I have to change integers to strings in order to iterate them in Python?

First of all, I have only recently started to learn Python on codeacademy.com and this is probably a very basic question, so thank you for the help and please forgive my lack of knowledge.
The function below takes positive integers as input and returns the sum of all that numbers' digits. What I don't understand, is why I have to change the type of the input into str first, and then back into integer, in order to add the numbers' digits to each other. Could someone help me out with an explanation please? The code works fine for the exercise, but I feel I am missing the big picture here.
def digit_sum(n):
num = 0
for i in str(n):
num += int(i)
return num
Integers are not sequences of digits. They are just (whole) numbers, so they can't be iterated over.
By turning the integer into a string, you created a sequence of digits (characters), and a string can be iterated over. It is no longer a number, it is now text.
See it as a representation; you could also have turned the same number into hexadecimal text, or octal text, or binary text. It would still be the same numerical value, just written down differently in text.
Iteration over a string works, and gives you single characters, which for a number means that each character is also a digit. The code takes that character and turns it back into a number with int(i).
You don't have to use that trick. You could also use maths:
def digit_sum(n):
total = 0
while n:
n, digit = divmod(n, 10)
num += digit
return num
This uses a while loop, and repeatedly divides the input number by ten (keeping the remainder) until 0 is reached. The remainders are summed, giving you the digit sum. So 1234 is turned into 123 and 4, then 12 and 3, etc.
Let's say the number 12345
So I would need 1,2,3,4,5 from the given number and then sum it up.
So how to get individuals number. One mathematical way was how #Martijn Pieters showed.
Another is to convert it into a string , and make it iterable.
This is one of the many ways to do it.
>>> sum(map(int, list(str(12345))))
15
The list() function break a string into individual letters. SO I needed a string. Once I have all numbers as individual letters, I can convert them into integers and add them up .

Split day-of-month integers into digits, sum them repeatedly until get a single-digit integer

I am attempting to take two-digit integers representing day-of-month, split the digits into single digits by taking each character in the single digit and adding them together to form a new number.
e.g. If the value for day was an integer 29, then the program would turn that into strings and split them into '2' and '9'. The program would then turn 2 and 9 into integers and add them together to equal 11. Since this is still a double digit number, the program would loop and 1 and 1 would be added together and the final value that would print would be 2. According to the code below(mostly the last ~5 lines), if I enter day=29, then the final answer I keep getting is 4 which is incorrect. Can someone help me fix this:
Note someone mentioned that I didn't re-enter dayStringSum and I accidentally deleted their post am not sure what that means at all.
dayString = str(int(day))
# Turns value day into int
dayStringA = int(str(dayString[0]))
# If day=29 then this variable represents the 2...
dayStringB = int(str(dayString[1]))
# ...and this represents the 9
dayStringSum = (dayStringA + dayStringA)
while(dayStringSum >=10):
dayStringA = int(str(dayStringSum[0]))
# Since daystringsum is now 11, this code changes the value of daystringA into a new value of 1, likewise for below.
dayStringB = int(str(dayStringSum[1]))
print(dayStringSum)
dayStringSum is an integer, so dayStringSum[n] makes no sense. You'll want to turn it into a string first, and then look at its individual characters.
Also, you do not assign a new value to dayStringSum inside the while loop, so if it is >= 10 upon entering the loop, it will remain so, resulting in an infinite loop. You say that you got a final result of 4, but I fail to see how you would get a final result at all.
Try something like this:
daySum = int(day) # Ensure that day is an int before we start.
while(daySum >= 10):
newString = str(daySum)
dayIntA = int(newString[0])
dayIntB = int(newString[1])
daySum = dayIntA + dayIntB # Will be checked on next iteration.
print(daySum)
I'm guessing the reason you're getting the wrong answer is that you add dayStringA + dayStringA when you meant to add dayStringA + dayStringB, i.e. it's just a typo.
The other thing you need to fix is that in the loop, you don't change dayStringSum. This hasn't been a problem so far because dayStringSum is less than 10 in your example, so the loop never executes in the first place, but once you fix that typo, you're going to get an infinite loop and the program will never stop.
Here's what I mean: suppose your day is 29. When you get to this line:
while(dayStringSum >=10):
then dayStringSum will be 11. So then you set dayStringA to 1,
dayStringA= int(str(dayStringSum[0]))
and also dayStringB to 1.
dayStringB= int(str(dayStringSum[1]))
Then that's the end of the loop. So Python goes back to this line:
while(dayStringSum >=10):
What's dayStringSum? Why, it's still 11! You never changed it. So Python will keep looping, going through the same logic over and over again.
Now beyond that, there are a bunch of things that make this code way more complicated than it needs to be. I'm not going to go through them (Code Review would be the place for that), but in general, you don't need to convert things to ints if they are already ints, and likewise you don't need to use str on something that is already a string.
try sum(map(int,"265"))
that maps them to ints and sums them ...
>>> sum(map(int,"254"))
11
or
>>> sum(map(int,str(29)))
11
oh well since its homework I cant really just give away the answer ....
but
its similar to
sum1=0
for integer in [1,2,3]: sum1 += integer
print sum1
Easier way is to take modulus 9 of the number
>>> print(29%9)
2
day = 29
while day >= 10:
day = sum(int(digit) for digit in str(day))
(Also, whenever you're doing major manipulations of the individual digits of an integer, decimal.Decimal is useful, in particular its method
Decimal(29).as_tuple().digits which gives you (2, 9)).

an error in taking an input in python

111111111111111111111111111111111111111111111111111111111111
when i take this as input , it appends an L at the end like this
111111111111111111111111111111111111111111111111111111111111L
thus affecting my calculations on it .. how can i remove it?
import math
t=raw_input()
l1=[]
a=0
while (str(t)!="" and int(t)!= 0):
l=1
k=int(t)
while(k!= 1):
l=l+1
a=(0.5 + 2.5*(k %2))*k + k % 2
k=a
l1.append(l)
t=raw_input()
a=a+1
for i in range(0,int(a)):
print l1[i]
this is my code and it works for every test case except 111111111111111111111111111111111111111111111111111111111111
so i guess something is wrong when python considers such a huge number
It looks like there are two distinct things happening here. First, as the other posters have noted, the L suffix simply indicates that Python has converted the input value to a long integer. The second issue is on this line:
a=(0.5 + 2.5*(k %2))*k + k % 2
This implicitly results in a floating point number for the value of (0.5 + 2.5*(k %2))*k. Since floats only have 53 bits of precision the result is incorrect due to rounding. Try refactoring the line to avoid floating point math, like this:
a=(1 + 5*(k %2))*k//2 + k % 2
It's being input as a Long Integer, which should behave just like any other number in terms of doing calculations. It's only when you display it using repr (or something that invokes repr, like printing a list) that it gets the 'L'.
What exactly is going wrong?
Edit: Thanks for the code. As far as I can see, giving it a long or short number makes no difference, but it's not really clear what it's supposed to do.
As RichieHindle noticed in his answer, it is being represented as a Long Integer. You can read about the different ways that numbers can be represented in Python at the following page.
When I use numbers that large in Python, I see the L at the end of the number as well. It shouldn't affect any of the computations done on the number. For example:
>>> a = 111111111111111111111111111111111111111
>>> a + 1
111111111111111111111111111111111111112L
>>> str(a)
'111111111111111111111111111111111111111'
>>> int(a)
111111111111111111111111111111111111111L
I did that on the python command line. When you output the number, it will have the internal representation for the number, but it shouldn't affect any of your computations. The link I reference above specifies that long integers have unlimited precision. So cool!
Another way to avoid numerical errors in python is to use Decimal type instead of standard float.
Please refer to official docs
Are you sure that L is really part of it? When you print such large numbers, Python will append an L to indicate it's a long integer object.

Categories