Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I had to write a script that generates some fixture file with increasing fake MAC addresses.
To do that, I decided to have some fun and try to make it as compact as I could. I ended up with:
def mac_address(i):
return ':'.join(['%02x'] * 6) % tuple([(i >> (8 * j)) & 0xFF for j in reversed(range(6))])
Which actually works pretty well. Obviously, writing this that way is the best way to get slapped by the future person that must work on it, but I did it for the fun (and wrote a more readable version in comment).
But now I'm curious, can you think of any more compact way of writing that ? (That is without removing the spaces).
What about
':'.join('%02x' % (i>>(8*j) & 0xFF) for j in reversed(range(6)))
That is more compact and easier to understand.
def mac_address(i):
return ':'.join(a+b for a, b in zip(*[iter('{:012x}'.format(i))]*2))
The first step is to get a hex string zero filled so that it is exactly 12 digits, which is what '{:012x}'.format(i) does. Then we break that string up in two-character chunks using the method of grouping items from the zip() documentation, and join the result on ':'.
Maybe:
from struct import pack, unpack
def mac_address(i):
return ":".join(["%02x"] * 6) % unpack("BBBBBB", pack("!Q", i)[2:])
Related
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 last year.
Improve this question
I am trying to randomly generate a string of n length from 5 characters ('ATGC '). I am currently using itertools.product, but it is incredibly slow. I switched to itertools.combinations_with_replacement, but it skips some values. Is there a faster way of doing this? For my application order does matter.
for error in itertools.product('ATGC ', repeat=len(errorPos)):
print(error)
for ps in error:
for pos in errorPos:
if ps == " ":
fseqL[pos] = ""
else:
fseqL[pos] = ps
If you just want a random single sequence:
import random
def generate_DNA(N):
possible_bases ='ACGT'
return ''.join(random.choice(possible_bases) for i in range(N))
one_hundred_bp_sequence = generate_DNA(100)
That was posted before post clarified spaces need; you can change possible_sequences to include a space if you need spaces allowed.
If you want all combinations that allow a space, too, a solution adapted from this answer, which I learned of from Biostars post 'all possible sequences from consensus':
from itertools import product
def all_possibilities_w_space(seq):
"""return list of all possible sequences given a completely ambiguous DNA input. Allow spaces"""
d = {"N":"ACGT "}
return list(map("".join, product(*map(d.get, seq))))
all_possibilities_w_space("N"*2) # example of length two
The idea being N can be any of "ACGT " and the multiple specifies the length. The map should specify C is used to make it faster according to the answer I adapted it from.
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.
The community is reviewing whether to reopen this question as of 11 months ago.
Improve this question
Hy,I am newbie in python programming.I am trying to improve my programming skills.I recently joined a code learning platform called code wars for improving my coding skills. The platform is great. I am having trouble reading some code there as I am not a experienced programmer.
Write a function that adds the digits of an integer. For example, the input receives a number: 10023. The result should be - 6 (1 + 0 + 0 + 2 + 3)
For example I found the answer that is rated higher for the above question.
def sum_digits_of(n:int) -> int:
return sum(map(int, str(n)))
SumDigitsOf = sum_digits_of
For the above solution I did not understand '(n:int) -> int' and 'map(int, str(n))'
It's not that I don't know programming but I can't understand the code like above.I know simpler methods for solving this. But how to write and understand much more efficient code. It would be great help if any of you guys suggest how will I get better or is it wise to post the code which I don't understand here [ already tried googling :) ], Cheers!
The code you show “casts” an int to a str, then takes it digit by digit (map applies a function to something iterable, simply put), “casts” each digit back to int and finally sums the digits. (And it is indented incorrectly.)
The final assignment merely creates an alias name for the function, it doens’t “do” anything.
In any case, strings (str) do not have to be necessarily involved:
def sum_digits_of(n, base=10):
result = 0
while n:
result += n % base
n //= base
return result
print(sum_digits_of(123456))
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 7 years ago.
Improve this question
I apologize because I am coming from Perl and I am new to Python.
The following example looks very long to me:
#!/usr/bin/python
import re
r = re.compile('(?i)m(|[ldf])(\d+)')
m = r.match(text)
if m:
print m.group(2)
In Perl for example it is only one line and it's pretty readable.
#!/usr/bin/perl
print $2 if /m(|[ldf])(\d+)/i
How can I rewrite my Python example to be simpler. If possible to be as light as it is with Perl.
I am planning to write plenty tests and if I want to keep my code readable I would like to avoid consuming lines that will not help people to understand my program. I guess that something like this below would be more readable that my first solution:
r = R()
if r.exec('(?i)m(|[ldf])(\d+)', text): print r.group(2)
if r.exec('(?i)k(|[rhe])(\d{2})', text): print r.group(2)
Unfortunately in this case I have to write a class for this.
The Python way values clarity over brevity, so things are generally going to be more verbose than they are in Perl. That said, the re.compile step is optional.
m = re.match('(?i)m(|[ldf])(\d+)', text)
if m:
print m.group(2)
In Python, assignments are not expressions; they can't be used as values. So there's no way to skip the separate assignment statement (m = ...) or combine it with the if . And if you want to refer to the match object later, you do need an explicit assignment - there's no global implicit state analogous to the Perl $n variables that stores the capture groups automatically.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
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
Improve this question
I have a number which I want to split into smaller numbers of equal length.
Suppose, I have the number 212313454
I, now want to split it into 3 numbers of 3 digits each:
212, 313 and 454
What if I want to randomly split it? I mean
212313454 into
213, 354, 114
Is there any way to do this?
You can use modulus operator % and division operator / and form the divisor as 10^n where n is number of digits in each result of split.
Convert them to a string and then split them. Like:
s = str(212313454)
a = s[0:3]
b = s[3:6]
c = s[6:]
Use a loop for a variable length number.
I'm sorry to ask but your question is vague (yes I know people have "answered" the question...).
"split [a number] into smaller numbers of equal length". Your example and hence everyone's answers assume you just have 9 decimal digits and want three smaller integers back, but what if you have a longer or shorter number, or want more/less subdivisions?
and randomly splitting "212313454 into 213, 354, 114". What is the correlation of these smaller numbers with the larger # exactly? 213 isn't in 212313454 if my eyes are working properly. If you want to pick random digits from an integer you can do that.
Lastly if you are just experimenting for fun, cool, but you should think a bit about making integers into strings and back and forth. A lot of math routines in python you should checkout are in the standard library, e.g. math module, random module, and bitwise operators too.
Im not going to write the code for you but here is a simple way to do it:
Make the int a string
split the string each 3 characters
once you do that iterate the list and turn the strings back into ints
I think you can figure it out if you try!
Good luck :)
The easiest way to convert the integer to a string adn then change it back to int again...
Here is how I would do...
Code:
c = 212313454
def splits(c,length):
l = [c[i:i+3] for i in range(0,len(c),3)]
print map(int,l)
if __name__=='__main__':
splits(str(c),3)
Output:
[212, 313, 454]
Hope this helps :)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am just learning Python with ebook of A Byte in Python and some youtube tutorial. I have reached up to For loop statement. Its not that I don't understand it, but the beginner examples only show: " for i in range..." My question is why only 'in range' option is given. I know how this statement, both for and range, works. But are there other options instead of range?
Can you give me a simple Syntax for usage of for loop? They don't have it in this ebook. Thanks and sorry if I was irritating and confusing. I am just learning by myself.
Of course, there are many ways to use a for-loop. for i in range() is commonly used to loop through something a specific amount of times, or just do something a repeated amount of times with a counter.
Infact, you don't even have to iterate over lists. You can iterate over a string:
>>> for char in 'hello':
... print char
...
h
e
l
l
o
Or even a dictionary:
>>> for key in {'foo':'bar','cabbage':'cake'}:
... print key
...
cabbage
foo
Python does not have the typical for loop construct that the "c-family" languages like java, c, c++, etc have. Python isn't the only scripting language that does this ( I believe bash does it too but don't quote me ). If you want something as true as can be to the "normal" for loop ( and I'm assuming you do ) :
for( int i = 0; i < n; i++ ){ /* do something */ }
I would suggest a while loop in python
i = 0
while ( i < n ) :
// do something
Or use xrange
for i in xrange( 0, n ) :
// do something
xrange is a lot like range, but it doesn't store all the values simultaneously : http://docs.python.org/2/library/functions.html#xrange
I personally would use xrange, I don't know of a better solution. Good luck!