How to anagram digit in python? [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is my problem ? I want act inverse number--example : 123 ==>321
def loop(a):
i=0
while(a>=1)
print(a%10)
s=s/10
i=i+1

Your solution has a few problems, aside from the indentation and the missing colon.
First of all your are using print which automatically adds a line break, so that might not be what you want the result to look like. You could store the result in a string which you append the latest character to and then print it once at the end.
Further, you are using a variable s which was never used before. In thise case it should be a as you want to strip off the last digit using an integer division by 10. Note that in this case, this will only work like that in Python 2, as Python 3 will use a float division there (e.g. 15 / 10 == 1.5). You can prevent that by explicitly using the integer division there (this will also make your intend more clear): s = s // 10 (note the two slashes).
Lastly, you are incrementing the variable i without ever using it, so you can just get rid of it.
In the end, it might look like this:
def reverse (a):
rev = ''
while a > 1:
rev += str(a % 10)
a = a // 10
A shorter solution, utilizing the fact that you can just reverse strings:
>>> num = 123
>>> rev = int(str(num)[::-1])
>>> rev
321
If you leave out the int(), you can even keep trailing/leading zeros and get a string instead:
>>> num = 3210
>>> str(num)[::-1]
'0123'

Few issues:
Your indentation does not match. PEP 8 suggests 4 spaces for indentation.
You're missing a colon after while(a>=1)
Although this isn't an issue, you don't need the parentheses in the while loop, it can just be while a >= 1
s = s/10 might not return what you expect. For example, 12/10 == 1 (unless you're dealing with floats here).
This can all be simplified using slicing:
>>> print int(str(123)[::-1])
321

It is important to indent correctly. (And don't mix tabs and spaces.)
def loop(a):
i = 0
while a >= 1:
print(a % 10)
a = a / 10
i = i + 1
You were also missing a colon after the while condition.

Related

Why my output result doesnt show 0 when it's supposed to show exact number in reverse order in Python.Without changing parameter variable to string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Why my output result doesn't show 0 when it's supposed to show exact number in reverse order in Python.Without changing the parameter variable to string.
parameter = int(input())
sum = 0
while parameter > 0:
digit = parameter % 10
sum = sum * 10 + digit
parameter = parameter // 10
print(sum)
A couple of things are going on here. First, you're converting the input to an int. This means that when reversing the number you'll lose all trailing 0s. This is because for an int there is no reason to show a leading 0. Instead, you can simply print out each digit in reverse. Another thing to note is you shouldn't use sum as a variable since it will overwrite the built in sum function.
parameter = int(input())
while parameter > 0:
digit = parameter % 10
print(digit, end='')
parameter = parameter // 10
print("")
You can do this by printing the output right-justified in a field of the same width as the original number. This doesn't really avoid the fact that string manipulation is required, but at least it allows you to store the number as a number and not a string:
from math import ceil, log10
...
digits = ceil(log10(parameter + 1)) or 1
...
print(f'{sum:>0{digits}}')

Why are there spaces in the middle of printed integers? [duplicate]

This question already has answers here:
Print without space in python 3
(6 answers)
Closed 3 years ago.
I am currently doing a tutorial in repl.it, and have used this website a little bit for web development. I cannot understand how to do this problem, and I think I got everything else right, except that there is a whitespace in the middle of what Python 3 prints out.
The question is:
Given a two-digit integer, swap its digits and print the result.
The code I have written is this:
a = int(input())
b = int(a / 10)
c = int(a % 10)
print(c, b)
When I put the sample input in, 79, it seems to swap correctly, but it leaves a space, of which I know is technically a character and is wrong.
Input: 79
Output: 9 7
Thanks for answering!
The Problem
The comma in the print statement tells python to put a space.
The Solution
You want to put both integers together as strings, so this is your best route:
a = int(input())
b = int(a / 10)
c = int(a % 10)
print("{0}{1}".format(c, b))
Experimenting with the Code
I invite you to try some variations on the format string to understand best how it works.
ex1
print("{0} and {1}".format(7, 9))
# output: 7 and 9
Examine what happens when you change the characters inside the string, or in the format function.
ex2
print("My first name is {0} and {0} likes {1}!".format("Samy", "pie"))
# output: My first name is Samy and Samy likes pie!
I hoping it becomes clear that the format function preforms substitutions in strings.
"{0}" gets replaced with the first argument to the format call.
"{1}" gets replaced with the first argument to the format call.
and so on..
You can have additional arguments:
ex3
print("My favorite numbers are {0}, {1}, {2}, and {3}.".format(9, 23, 45, 97))
# output: My favorite numbers are 9, 23, 45, and 97.
More information
My favorite way to learn python was always trial and error, and experimenting with the code. It has always felt like the language wanted me to do that, but another great way to learn is to read specifications.
Visit the specification of the format function: https://docs.python.org/3.4/library/string.html#format-string-syntax
You will learn everything there is to know about the function.
Most notably,
The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument. If the numerical arg_names in a format string are 0, 1, 2, ... in sequence, they can all be omitted (not just some) and the numbers 0, 1, 2, ... will be automatically inserted in that order.
Notice that field_name refers to what's on the inside of {}

PyCharm Tutorial , While Loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
square = 0
number = 1
while number < 10:
square = number ** 2
print(square)
number += 1
It's my answer for this question :" Print all squares from 0 to 99(1,4,..,81)Use number variable in while loop."
Pycharm says it doesn't match with its answer.
I think i should print those numbers in a single line but i couldn't deal with it.How can i do that ?
Your code will print each number in a newline, because, in Python, the call to print() comes with an implicit newline (see the end argument per the documentation).
Next, you're making an assumption about output formatting. As I see it, there are two primary issues with this assumption:
1) Calls to functions (e.g. print()) in a while loop "execute" when they're called -- there's no delay to see if a future pass through the loop will provide extra data to the function.
2) You're assuming that the Python interpreter will guess that printed numbers (in a while loop) are desired to be returned in a comma separated list. Computers are machines that do what you tell them to do -- if you don't write logic to explain what you need, the machine cannot give you this.
You can express your desired output in the following ways:
1) Collect the numbers (as strings) in a list, then output them after you're done looping:
square = 0
number = 1
# think of this as a result container
number_result_list = []
while number < 10:
square = number ** 2
# place that number at the end of your container:
number_result_list.append(str(square))
number += 1
# join all your number strings together, using a comma
print(",".join(number_result_list))
# prints 1,4,9,16,25,36,49,64,81
2) Specify that you want to use a comma in the call to print. Make special note of the trailing comma -- you now know why this happens:
square = 0
number = 1
while number < 10:
square = number ** 2
print(square, end=",")
number += 1
# prints 1,4,9,16,25,36,49,64,81,

Decimal points in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have some floating point values, these all values are dynamically generated:
float_a = 12.200
float_b = 14.0
float_c = 14.01880
I want to remove the decimal point from them.
Expected Result
"12200"
"140"
"1401880"
I must be careful as these are not fixed-point values and I don't have any control on how many decimal places my input will go up to. More examples from the comments:
1.10
1.110
2.0
2.1340
Expected result:
"110"
"1110"
"20"
"21340"
This question seems to be a permutation of another question that has already been answered:
The concept of leading zeros is a display concept, not a numerical
one. You can put an infinite number of leading zeros on a number
without changing its value. Since it's not a numeric concept, it's not
stored with the number.
You have to decide how many zeros you want when you convert the number
to a string. You could keep that number separately if you want.
SOURCE: Python Force python to keep leading zeros of int variables
It looks like the only way to do what you are asking is if your initial "Float" is in string form, otherwise the trailing 0's will be dropped. If you manage to get the "Float" as a string (before it ever becoming a Float), then you can use the int('12.200'.replace('.', '')) method mentioned above
If you're starting off with a string, which I think you are. I would use something like:
>>> int('12.200'.replace('.',''))
12200
It just removes the . and parses the resulting string as an int. Otherwise just cast whatever you have to str first.
It is just a formatting issue. Either of these work to get trailing zeroes:
>>> '{:.3f}'.format(1.2)
'1.200'
>>> '%0.3f' % (1.2,)
'1.200'
Then:
>>> '{:.3f}'.format(12.2).replace('.','')
'12200'
To get what you want from your examples:
vals=(1.10, 1.110, 2.0, 2.134)
def wid(f):
w=1
while True:
s='{:.{w}f}'.format(f, w=w)
if s[-1]=='0' or w>5:
break
w+=1
return w
for e in vals:
s='{:.{w}f}'.format(e, w=wid(e)).replace('.','')
print '{:10} => {}'.format(e, s)
Prints:
1.1 => 110
1.11 => 1110
2.0 => 20
2.134 => 21340
If you want to remove the decimal, why not multiply by 1000?
float_a = 12.200
print str(int(float_a*1000))
When you have
float_a = 1.110
float_b = 1.1100
float_c = 1.11000
Python is discarding the trailing zeros, and the above 3 are the exact same. These trailing zeros are non-significant digits, and so if you want to actually preserve them, your original data type will need to be a String.
If you make that change, then it is simple to do
float_a = "1.110"
print float_a.replace('.', '') # "1110"
If you're asking how to turn float_a = 12.200 into the string "12200", simply multiply it by 1000 before converting it into a string, for example:
print(str(float_a * 1000))
However, if the number contains more than 4 decimal places, you'll still have decimals.
However, since you're talking about it "always removing the 0's", I suspect you may have missed a . in your expected output. In this case, to display a float with a fixed number of decimals, just use Python's built-in string formatting:
float_a = 12.200
expected_result = '%.2f' % float_a
print expected_result
> 12.20
If this doesn't make sense, please clarify your question a bit and I'll edit! :)
Edit
Upon your further clarification of the question, it seems that you want to define a float with trailing zeros and have them preserved and the float converted to a string with the leading zeros preserved. I'm afraid this is impossible if your input type is float, since float won't preserve those trailing zeros to begin with:
In [1]: float_a = 3.1400
In [2]: float_a
Out[2]: 3.14
This is a "limitation" of the data type and there's nothing you can do about it. You want a fixed-point type or something to handle "decimal numbers", not a float.

what's the meaning of this program? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I know that the program convert Decimal to Binary,in fact I'm just a beginner in programming and python is my starting language.
answering these questions will help me a lot.
def bin(i):
s = "" # what do we mean by s="" ? does it mean s=0?
while i: # where is the condition ?
if i & 1: # what is the equivalent for '&'? when I put 'and' instead of '&' I get differnt results?why?
s = "1" + s # ?
else:
s = "0" + s
i = i//2 # why?
return s
the problem is that I want to undestand what happen between the input and the output?
one more thing can we extend this code to floating numbers how ?
Let me try to answer your questions one at a time; you should then be able to piece them all together:
s = "" # what do we mean by s="" ? does it mean s=0?
s is now an empty string. You could add other strings to it, to concatenate them. Indeed, this is what is done later on, in the line s = "1" + s. Take a look:
In [21]: "1" + ""
Out[21]: '1'
In [22]: "1" + "2"
Out[22]: '12'
In [23]: s = ""
In [24]: "1" + s
Out[24]: '1'
See how string concatenation works?
Next:
while i: # where is the condition ?
Ah! there is a nuance in many programming languages (including python) that an integer whose value is 0 evaluates to a boolean of False, when used in a conditional statement (like if or while). All non-zero values evaluate to True.
Therefore, this while loop is saying while i does not take the value of 0. Note that because of the division on i later on, i will never take on a negative value, and this loop therefore terminates.
Next:
if i & 1: # what is the equivalent for '&'? when I put 'and' instead of '&' I get differnt results?why?
i&1 is a bit-wise AND operator. Suppose i has the value of 5. Then, the binary representation of i is 101. the binary representation of 1 is simply 1, or 001 (since we are comparing it with 101). So now, we perform the bit-wise AND, which basically compares each pair of corresponding bits, outputting 1 if they are both 1s (0 otherwise). The result of comparing 101 and 001 thusly, is 001, which translates to a value of 1. All this means is that when you divide i by 2, you get a remainder of 1. Since the only possibilities for this are 1 (which evaluates to True in the if-statement) or 0 (which evaluates to False in the if-statement), it lends itself to be very easily used in such a dichotomous fashion (to add either a "0" or a "1" to s)
Next:
i = i//2
This is a truncated division with an integer casting. Watch:
In [27]: i = 4
In [28]: i/2
Out[28]: 2.0
In [29]: i//2
Out[29]: 2
In [30]: i = 5
In [31]: i/2
Out[31]: 2.5
In [32]: i//2
Out[32]: 2
Get it?

Categories

Resources