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 6 years ago.
Improve this question
I have a question as such: How many ways are there to change order of letters in "avocadojuice" so that the vowel comes up first, for example "ovacadojuice" is a solution? The starting point - "avocadojuice" is also a solution.
I know that itertools.permutations can do things like this, but if the word is too long it pops up a memory error. Is there a way to prevent this, or maybe there is another built in module, which can solve this? Thank you in advance!
P.S. I know how to turn permutation tuples into strings.
This is a case were brute-forcing the problem probably isn't feasible. You need to compute the number of unique permutations of n elements, accounting for the fact that some elements are repeated.
There is a mathematical formula for this, and some excellent answers on other stack exchange sites.
Only a and o are repeated, so the number of unique permuations of avocadojuice is
(12!) / (2!2!)
or 119750400
At roughly 45 bytes per 12-character string (on my machine at least), that's over 5 gigs of memory just to store the nearly 120 million permutations! You can see why brute forcing this isn't such a great idea.
You have one extra requirement in your problem though, which is that the permutations must start with a vowel. Given that there are only 5 vowels, you should be able to calculate the possible permutations with each of the given vowels as the first character.
(11! / 2!) + # a (only o is repeated)
(11! / (2!2!)) + # e
(11! / (2!2!)) + # i
(11! / 2!) + # o (only a is repeated)
(11! / (2!2!)) + # u
Related
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 11 months ago.
Improve this question
This is my first time posting to Stackoverflow.
I'm trying to solve this problem here: https://codingbat.com/prob/p270692?parent=/home/konstans#stuy.edu/all
When looking at all hailstone sequences from 1 to z, maxHail(z) will return the starting number that creates the longest sequence. In other words, maxHail(n) looks at hailLen(1), hailLen(2) ... hailLen(n) and returns the number from 1-n that had the largest hailstone sequence. You should look at the hailLen() problem before working on this. You should use your solution from the hailLen() problem. ( http://codingbat.com/author/p264289 ) since hailLen(3) is larger than the hailLen of 4 or 5, maxHail of 3,4,5 all return 3. Since 6 has a longer sequence, maxHail(6) gives us 6. remember: Use the hailLen function you already wrote!
Here's my code and the output:
However, I'm not sure where this goes wrong - I checked line-by-line and couldn't see anything wrong. Could anyone help me fix this? Thank you!
I see what is wrong - hailLen returns lenght of sequence and the question is about index for which the sequence is the longest. Just store it in variable
if (res := hailLen(i)) > counter: # it's python 3.8 syntax
counter = res
index = i
return index
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 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 5 years ago.
Improve this question
I have a list as below:
a=[0,0,2,4,4,6,6,9,12,13,13,16,16,21,21,24,26,26,28,28,31,34,34,37,37]
The list satisfies:
1.sorted in ascending order
2.each number occurs 1-2 times
How to count all AABB-like occurrence in the list?
In the above example the answer should be 5
(4,4,6,6) (13,13,16,16) (16,16,21,21) (26,26,28,28) (34,34,37,37)
There are many ways to do this. The simplest I could think of is using 'enumerate' and list comprehension with a condition to test for 'aabb' patterns.
result = len([x for idx,x in enumerate(a) if idx<len(a)-3 and x == a[idx+1] and x!=a[idx+2] and a[idx+2] == a[idx+3]])
The idx < len(a) - 3 avoids index problems.
Although it may not seem that way at first (because you are processing a list of ints) this is actually an example of a string searching algorithm.
If you look at the wikipedia article (linked to above) you will see that there are quite a few uses for such algorithms, beyond simply searching strings, one major one being searching DNA sequences for a given pattern, so it is quite an important area of computer science.
As well as multiple uses there are multiple implementations so you could approach this several ways.
The naive approach is to simple iterate through the list and check to see if the next element matches the current element and then if the following elements also match. The problem here is that you have to go through the whole list and then iterate through each sublist to check if it matches the given pattern. In big O notation we say this approach has a complexity of O(nm) where n is the length of the list and m is the length of the pattern you are searching, so it is not very efficient.
There are many ways to improve on the naive approach, and there may even be some that are unknown. I'll leave that to you to figure out, but hope this gives you some pointers.
Just loop through - and compare the pairs
a=[0,0,2,4,4,6,6,9,12,13,13,16,16,21,21,24,26,26,28,28,31,34,34,37,37]
for i in range(len(a)-3):
if (a[i]==a[i+1] and a[i+2]==a[i+3]):
print(str(a[i])+str(a[i+1])+str(a[i+2])+str(a[i+3]))
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 concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Basically, I'm working on a Python fill in the letters type of game (kind of like Hangman).
The problem is I can't seem to get the program to record duplicate points.
What I mean is:
The program asks the user for a word. That word, let's say....football, is converted into a masked string (ex. **)
Then it continually asks the user for letter inputs. Let's say the user enters:
f
o
t
b
a
l
And then it fills out the word. For each letter that is guessed correctly, the user is awarded ONE point. But the problem is that for a word like football,only 6 points are awarded because some of the letters are duplicates.
Basically, the way I've coded it, each time a correct letter is guessed, another point is added on top of the overall total points. Is there a better way of doing this that can include the duplicate letters?
You could perhaps use count() on the word to see how many times the letter is in the word:
word = 'football'
# Code here to take input
# if input is in word:
points = word.count(the_input)
award_player(points)
You could try a list comprehension combined with sum():
>>> s = "foot**ll"
>>> sum([1 for x in s if x != '*'])
6