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 8 years ago.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
Improve this question
I am new to programming. I took a basic course in Python, so I know the basic. I am trying to practice a lot more. I am attempting this question and I don't know where to start.
You will be given a list of 32-bits unsigned integers. You are
required to output the list of the unsigned integers you get by
flipping bits in its binary representation (i.e. unset bits must be
set, and set bits must be unset).
Input Format
The first line of the input contains the list size T. T lines follow
each line having an integer from the list.
Constraints
1 ≤ T ≤ 100
Output Format
Output one line per element from the list with the requested result.
Sample Input
3 2147483647 1 0
Sample Output
2147483648 4294967294 4294967295
Explanation
Take 1 for example, as unsigned 32-bits is
00000000000000000000000000000001 and doing the flipping we get
11111111111111111111111111111110 which in turn is 4294967294
Can be done with the bitwise XOR operator, which is ^ in Python.
Example:
a = 0xF0101010
b = 0xFFFFFFFF
print(bin(a))
print(bin(b))
print(bin(a ^ b))
0b11110000000100000001000000010000
0b11111111111111111111111111111111
0b1111111011111110111111101111
foreach x in input:
x_flipped = ~x & 0xffffffff
print "bits flipped in unsigned 32-bit", bin(x_flipped)
Explained:
- (~x) flips all bits
~ (& 0xffffffff) converts 2's complement into unsigned int.
Related
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 5 years ago.
Improve this question
I have to write a program that returns ...
-1 for an empty string
0 for a single-character string
next-to-last index if the final two characters match
last index if they are different
For instance:
"tara" => 3
"baa" => 1
"adjsk" => 4
"sthkk"=> 3
"a" => 0
It seems that I'm returning index of last character wrongly:
def ends_with_pair(s):
for i in range(len(s)-1):
if s[i] == s[i+1]:
return s.index(s[i])
return s.index(s[-1])
Also, is there a way to make it more compact?
Your logic is far too complex. The problem involves only the final two characters; there's no need to loop through the string.
Check the string length; if it's 0, return -1. If it's 1, return 0.
Check the last two characters against each other s[-1] == s[-2]. If they're equal, return len(s)-2; else return len(s)-1.
I trust you can turn that into code.
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
I have 2 questions I need to ask for help with. One question I don't entirely understand so if someone could help me to that would be great.
Question One (the one I don't entirely understand):
One definition of e is
Formula for e
This can be calculated as my_e = 1/math.factorial(0) + 1/math.factorial(1) + 1/math.factorial(2) + 1/math.factorial(3) + …
Let n be the input number of the math.factorial() function. n successively takes on 0, 1, 2, 3 and so on. Find the smallest n such that the absolute value of (my_e – math.e) is less than or equal to 10-10. That is, abs(my_e - math.e) <= (10 ** -10).
I just don't entirely understand what I am being asked to do. Clarification would be great. Thanks!
Question 2:
Ask the user to type in a series of integers. Sum them up and print out the sum and the number of integers the user has entered.
My code
So what should happen is after I enter the numbers I want to enter and hit the enter key, it should calculate and print out "sum = 25 count = 3". The screenshot shows what error message I am getting.
Any help you have is welcomed and greatly appreciated.
As far as you first question goes:
>>> import math
>>> math.e
2.718281828459045
>>> sum(1.0/math.factorial(i) for i in range(5))
2.708333333333333
>>> abs(sum(1.0/math.factorial(i) for i in range(5)) - math.e) < 10**-10
False
>>> abs(sum(1.0/math.factorial(i) for i in range(30)) - math.e) < 10**-10
True
So, somewhere between n == 5 and n == 30 you get 10 decimal places for e. Create the sum term by term in a while-loop (instead of by using the sum function as I have, since you are unlikely to have seen that syntax yet). At each pass through the loop, compare the sum with math.e. Stop when you get the target accuracy. Return the final n.
the concise python code i study for is here
Question A # line 8
i do not really understand the syntax meaning for "res = res << 1" for the purpose of "get_signature"
Question B # line 49 (SOLVED BY myself through another Q&A)
"xor = r1^r2" does not really make any sense to me, which the author later tried "(d-nna(vor))" to calculate "hash_sim" -- (refer to line 50)
Question C # about hash_sim in general
that question is more to do with LSH understanding, what variable "d" (line 38) is doing in the sample code ---- which is later used to calculate hash_sim in line 50
Question D # line 20 and 24 -- synatx for "&"
not only having problem in understand the syntax "num = num & (num-1)", but also unsure what function "nnz" is doing in the context of hash_similarlity. this question may relate to my question (-b-) when the author apply the "xor" into "nnz", and again equation for "xor" (question b) looks odd to me.
p.s.
both my python and LSH understanding are at the beginner level, and I kind of entering in the loop for this problem. thanks for taking your time to going through my confusion as well as the codes
a. It's a left shift: https://docs.python.org/2/reference/expressions.html#shifting-operations It shifts the bits one to the left.
b. Note that ^ is not the "to the power of" but "bitwise XOR" in Python.
c. As the comment states: it defines "number of bits per signature" as 2**10 → 1024
d. The lines calculate the bitwise AND of num and num + 1.
The purpose of the function is documented in the comment above:
"# get number of '1's in binary"
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am trying to round some negative floating numbers, the format i want is like the below print/format way, not the round. The problem is that the print approach is not "clean", since it outputs a string with spaces, I got this code from another similar question here in Stackoverflow. The question is how to format/round the numbers like the print below. Thank you
theta = 0.33161255787892263
math = 0 + (1-0) * (1-math.cos(theta))**5
round(math,8) # Result: 4.8e-07 #
print("{:18.8f}".format(math)) # Result: ' 0.00000048' #
You say "I want the result of the print but in a float number not string" and "The result returns to a negative power floating point number, i want to keep the decimal format as the string". But you can't do that because you have no control over the internal representation of a float: they are all stored in a binary form of scientific notation. See the Wikipedia article on floating-point numbers for details.
So it doesn't matter whether you do
v = 0.00000048
or
v = 4.8e-07
both of those statements have an identical effect.
Note that many fractional numbers that terminate when written in decimal may repeat when written in binary. The only fractions that terminate when written in binary are of the form n / (2 ** b), where n and b are integers. Thus even an innocuous-looking number like 0.2 doesn't terminate when converted to binary. (See the Wiki link for a fuller explanation). Because of this issue it's generally not a good idea to round floating-point numbers until you've finished all calculations with them.
If you convert a string to float and back again it has to be converted from decimal to binary and back again. So such an operation shouldn't be used in an attempt to "clean up" a number because of the possible rounding errors at each conversion step.
Of course, sometimes you do need to apply rounding to a float that you are going to continue calculating with, but if so, you should proceed with caution and make sure you really do understand what you're doing to your data.
...
There are a few other strange things with the code you posted.
math = 0 + (1-0) * (1-math.cos(theta))**5
Firstly, you should not use the name of a module that you've imported as a variable name. After the above statement is executed math now refers to the result of the calculation, not the math module, so if you tried to do x = math.cos(0.5) you'd get an error. Similarly, don't use int, str, list, etc as variable names.
Secondly, the 0 + (1-0) * is virtually useless. So the above statement could be re-written as
result = (1 - math.cos(theta)) ** 5
And the whole code snippet would become
#! /usr/bin/env python
import math
theta = 0.33161255787892263
result = (1 - math.cos(theta)) ** 5
print round(result, 8)
print("{0:.8f}".format(result))
output
4.8e-07
0.00000048
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'm beginning to learn the basics of python. I had just learned that str() turns non-strings into strings - example: str(2) would change 2 to "2". That raised a question - what is a string and what difference does it have from a non-string? I've googled this but I could not find this question is directly answered and the general explanations don't quite make it clear for me.
"That raised a question - what is a string and what difference does it have from a non-string?"
It sounds like python is your first language. That being said, for conceptual sake, a string is text, and a 'non-string' is a number. You will see why this is not quite true as you program more, but for understanding the difference between a string and a 'non-string' this will suffice. You can do math with 'non-strings'. "2" is a string, but 2 is a 'non-string'. Adding strings is NOT the same as arithmetic addition. "2" + "2" results in another string "22" (this operation is called concatenation ), but 2 + 2 results in a 'non-string' A.K.A. the NUMBER (not string) 4, because the addition is arithmetic addition.
A string is any sequence of characters — not just numbers, but letters and punctuation and all of Unicode.
Something that isn't a string is... not that. :) (There are lots of things that aren't strings! String isn't special.) For example, 2 is an int. You can do math on an int, because it's a number. But you can't do math on a str like "2"; it's only the way we write the number in Western mathematics, not the number itself. You couldn't ask "dog" to wag its tail, either, because it's not a real dog; it's just the written word "dog".
As a more practical example:
2 + 2 gives you 4, the result of combining two numbers.
"2" + "2" gives you "22", the result of combining two written "words".
just to put another spin on this...
objects in python come with a variety of attributes and methods. attributes tend to represent data associated with the object. methods tend to represent behaviors that can be performed by the object. if we create a string and give it the name a and look at the list of attributes/methods, we see that the list encompasses many of the things you would want to know about a string or do with a string.
In [91]: a = '1' # assign a string the name 'a'
In [92]: a.
a.capitalize a.format a.isupper a.rindex a.strip
a.center a.index a.join a.rjust a.swapcase
a.count a.isalnum a.ljust a.rpartition a.title
a.decode a.isalpha a.lower a.rsplit a.translate
a.encode a.isdigit a.lstrip a.rstrip a.upper
a.endswith a.islower a.partition a.split a.zfill
a.expandtabs a.isspace a.replace a.splitlines
a.find a.istitle a.rfind a.startswith
on the other hand, if we create a number and give it the name b and look at the list of attributes/methods, we see that they are very different and focuses on things we would want to know about a number or do with a number.
In [92]: b = 1 # assign a number the name 'b'
In [93]: b.
b.bit_length b.denominator b.numerator
b.conjugate b.imag b.real