I have a code that outputs a whole bunch of numbers after doing some maths on them. At one point in the code they are rounded off with numpy.rint, and in certain cases (I believe when a 9 is rounded to a 10) I end up with a trailing zero that I do not want. I have some code that looks sort-of like this
ra3n = ra3/60 * 10
ra3n = np.rint(ra3n)
ra3n = ra3n.astype(str) ##there is a good reason that this needs to be a string
I need all of the resulting ra3n to be 5 characters long, but occasionally one pops out as 6 characters long. How would I format this properly? Keep in mind I'm a total python noob, so I might need it spelled out for me =)
EDIT:
Here's my output:
00244-2451
00244-2702
00278-0629
00286-1614
00295-1101
002910-0546
00303+0711
00305+2246
00348+2604
003410+0423
00355-0204
00359+1236
00360-0931
00386-1210
The instances where there are six digits instead of 5 in the first half of the string are the erroneous ones; those trailing zeroes should not be there.
ra3n = ra3n[:-1] if ra3n[-1] == '0' else ra3n
There's probably a better solution, but I'm not sure I really understand your issue without seeing some output.
You change the type of ra3n, which is poor programming practice. Try this.
ra3n = format(ra3/60.*10., '5f')[:5]
This gives exactly five characters. Note that if the string would usually be six characters long, this cuts off the last character, for good or for bad. Note also that I included decimal points in the 60 and 10 numbers: this guarantees that floating-point division will be used, rather than integer division if this is done in Python 2.
Related
I want to generate all the possibilities of a set of alphanumeric "abcdef0123456789" in a length of 64
I know that the number of possibilities are petabytes huge, so I want to limit it with 3 conditions:
the letter or number shouldn't be used more than 8 times in a single string,
ex: aaababaabaab not acceptable
aaabaaabaa is acceptable
there is no more than 3 adjacent identical letters or numbers
ex: aaaab not acceptable
aaaba is acceptable
the option of excluding the use 1 or 2 characters of the set
ex: "bcdef0123456789" with no a
I have searched over the internet for 3 days and never got an answer, could you please help?
Thank you in advance
The internet doesn't have answer to all concrete questions :) You need to break your problem into small pieces and search for them.
If you want to solve these kind of problems you might want to lookup backtracking. It's a generic way to solve constraint problems. You'll do recursion, start with empty string and in each step you'll try to add a character to your string. If one of rules are broken you'll return out of recursion.
Anyway I don't think it's possible, my educated guess is the number of possibilities is much much more than "peta byte".
>>> 16 ** 64
115792089237316195423570985008687907853269984665640564039457584007913129639936
Of course your constraints will reduce this but I don't think more than a mere few digits.
I am making a code in which every character is associated with a number. To make my life easier I decided to use alphanumeric values (a=97, b=98, z=121). The first step in my code would be to get a number out of a character. For example:
char = input"Write a character:"
print(ord(char.lower()))
Afterwards though, I need to know the total number of alphanum characters that exist and nowhere have I found my answer...
Your question is not very clear. Why would you need total number of alphanum characters?
thing is, that number depends on the encoding in question. If ASCII is in question then:
>>> import string
>>> len(string.letters+string.digits)
Which is something you could do by counting manually.
And this is even not really the total count, as there is a few more alpha from other languages within 0-128 ASCII range.
If unicode, well, then you will have to search for the specification to see how many of these are there. I do not even know how many alphabets are crammed into unicode or UTF-8.
If it is a question of recognizing alpha-numeric characters in a string, then Python has a nice method to do so:
>>> "A".isalnum()
>>> "0".isalnum()
>>> "[".isalnum()
So please, express yourself more clearly.
I am working on an encryption puzzle and am needing to take the exclusive or of two binary numbers (I'm using the operator package in Python). If I run operator.xor(1001111, 1100001) for instance I get the very weird output 2068086. Why doesn't it return 0101110 or at least 101110?
Because Python doesn't see that as binary numbers. Instead use:
operator.xor(0b1001111, 0b1100001)
The calculated answer is using the decimal values you provided, not their binary appearance. What you are really asking is...
1001111 ^ 1100001
When you mean is 79 ^ 97. Instead try using the binary literals as so...
0b1001111 ^ 0b1100001
See How do you express binary literals in Python? for more information.
Because 1001111 and 1100001 are not binary numbers. 1001111 is One million, one thousand, one hundred and eleven, while 1100001 is One million, one hundred thousands and one. Python doesn't recognize these as binary numbers. Binary numbers have to be prefixed with 0b to be recognized as binary numbers in Python/Python 3. So the correct way is this:
operator.xor(0b1001111, 0b1100001)
But hey! We get 46 as output. We should fix that. Thankfully, there IS a built-in in Python/Python 3. It's the function bin(n). That function prints a number a binary, prefixed with 0b. So our final code would be:
bin(operator.xor(0b1001111, 0b1100001))
If we want to hide the 0b (mostly in cases where that number is printed to the screen), we should use [2:] like this:
bin(operator.xor(0b1001111, 0b1100001))[2:]
A shorter way (warning looks like a tutorial for something you *should* already know)
Well, operator.xor() is too big for an operator :)
If that is the case (99.9%), instead you should use a^b. I think you already know this but why to import a whole module just for the xor operator? If you like to type the word xor instead, import the operator module like this: from operator import a, b.... Then use like this: bin(xor(a,b)). I hope you already know that stuff but I want to make sure you enjoy coding even more :)
First off all, thanks for the attention, I'm new to this site ^^ so excuse me if I do something wrong...
I have a huge problem with my Python code... I'm new to programming, and I'm new to Python as well.
I need to take a floating point number and move the point right so it becomes an integer, like taking 60.27 and getting 6027.
The algorithm that I'm using is recursively multiplying num*10 until num%2==0, then getting the int(num).
The problem is, when I multiply (for example) 602.47*10 it returns 6024.700000000001 and it obviously doesn't work :-)
Is there any way to fix it, or any other technique or other way to do this recursively?? I'm allowed to use anything I need, but its got to be recursive: no for or while...
Thanks for the help!! My first language is not english, so I beg your pardon if it's hard to read...
>>> str(60.27).translate(None, '.')
'6027'
Use lstrip('0') to guard against decimals below 1.
From the docs:
S.translate(table [,deletechars]) -> string
Return a copy of the string S, where all characters occurring
in the optional argument deletechars are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256.
Floating point representations have that issue.
Are you looking to change:
1.2345
12.345
123.45
1234.5
all to 12345?
For floats which have no exact representation (you mention 6024.70), do you expect to get 6024700000000001, since that's the output of the closest thing to 6024.70 which can be stored in float?
You could try something like:
x = 60.27
newx = int(str(x).replace('.',''))
Edit: as a side note, the string .replace and .translate have similar performance for various sized floats
%timeit int(str(4.73285).replace('.',''))
100000 loops, best of 3: 2.65 us per loop
%timeit int(str(4.73285).translate(None, '.'))
100000 loops, best of 3: 3.02 us per loop
It would be more reliable an algorithm to just parse the number as a string and do a string manipulation. Any numerical calculation involving floating-point numbers are bound to inaccuracy, as you've witnessed. There's no going around that.
Since you can't (reliably) use floating point to do what you want, an easy hack is to convert the number to a string then rip out the decimal point:
int(str(num).replace('.',''))
That will work with any number that isn't represented in scientific notation. If your numbers are big (or small) enough that they do end up represented in scientific notation, have a look at this.
Just taking a wild stab in the dark here, but do your numbers represent amounts of money that you're trying to convert between (say) dollars and cents? If so, you need to stop what you are doing and convert everything to cents, and only use "dollar" values when actually presenting things to the user. Using floating point numbers for money values is a very, very bad idea.
If not, ignore me :-)
I have a massive string im trying to parse as series of tokens in string form, and i found a problem: because many of the strings are alike, sometimes doing string.replace()will cause previously replaced characters to be replaced again.
say i have the string being replaced is 'goto' and it gets replaced by '41' (hex) and gets converted into ASCII ('A'). later on, the string 'A' is also to be replaced, so that converted token gets replaced again, causing problems.
what would be the best way to get the strings to be replaced only once? breaking each token off the original string and searching for them one at a time takes very long
This is the code i have now. although it more or less works, its not very fast
# The largest token is 8 ASCII chars long
'out' is the string with the final outputs
while len(data) != 0:
length = 8
while reverse_search(data[:length]) == None:#sorry THC4k, i used your code
#at first, but it didnt work out
#for this and I was too lazy to
#change it
length -= 1
out += reverse_search(data[:length])
data = data[length:]
If you're trying to substitute strings at once, you can use a dictionary:
translation = {'PRINT': '32', 'GOTO': '41'}
code = ' '.join(translation[i] if i in translation else i for i in code.split(' '))
which is basically O(2|S|+(n*|dict|)). Very fast. Although memory usage could be quite substantial. Keeping track of substitutions would allow you to solve the problem in linear time, but only if you exclude the cost of looking up previous substitution. Altogether, the problem seems to be polynomial by nature.
Unless there is a function in python to translate strings via dictionaries that i don't know about, this one seems to be the simplest way of putting it.
it turns
10 PRINT HELLO
20 GOTO 10
into
10 32 HELLO
20 41 10
I hope this has something to do with your problem.