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
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 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 2 years ago.
Improve this question
I have a large string of text which I wish to search for certain words. The words are stored in a list. Is it possible (and if so then how) to compare the string with the words in the list so that python returns all the found words and their locations, like this;
text = 'Theres a voice that keeps on calling me. Down the road, thats where Ill always be. Every stop I make, I make a new friend. Cant stay for long, just turn around and Im gone again. Maybe tomorrow, Ill want to settle down, Until tomorrow, I’ll just keep moving on.'
search_list = ['voice', 'Until', 'gone']
print(compare(text, search_list))
#returns something like: {voice: 11, Until: 112, gone: 54}
#p.s. the locations are random since I couldn't be bothered to count the characters
#but the format is something like {found_term: position of first character}
#(compare doesn't necessarily have to return the results in dictionary format)
I have tried searching on stack overflow and google but most similar questions are about comparing 2 strings or 2 lists.
Thank you in advance.
You can use .index() on a string to get the position of a substring:
from typing import List, Dict
def compare(text: str, search_list: List[str]) -> Dict[str, int]:
return {
word: text.index(word)
for word in search_list
}
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 4 years ago.
Improve this question
Forexample : the world is very beauty by describing color:blue and water,air,fire etc,.
I need to get the word next to word "color".
For that I did small python script by getting the word "describing" index and also the index of word "and".So I can able to print within the index range there color:blue.
But In some cases, the word before "color" will dynamically change and after the word "blue" also dynamically change.So, in this scenraio, I am struggling here to how to put the regular expression to get the word "blue".
And the word next to color:blue.sometimes be like color:green.
I am just updating the question like,
I have set of string like For example "HELLO:rosa I am fine and you Good_Morning:U look very beauty temple:Will be in town.
Here I need to extract the string next to the word "Good_morning:"
SO if,
Input: "HELLO:rosa I am fine and you GOOD_MORNING:U look very beauty TEMPLE:Will be in town"
Output:U look very beauty
So the script need to do search for the string next to GOOD_MORNING which is small letters and it need to stop before the next Capital WORD(TEMPLE).and print that small letters alone there.
For that I did python script to get that string next to GOOD_MORNING but getting the whole string next to GOOD_MORNING like :U look very beauty TEMPLE:Will be in town" but not" U look very beauty".
You might try color:(\w+\b). It will always find the word next to color: (no spaces allowed).
https://regex101.com/r/IOkH1j/1
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 7 years ago.
Improve this question
I have a program that
Takes a text file with several sentences
Asks the user if they want to compress/decompress the file.
If Compress is chosen, the sentence will have all the unique words and the positions of these words needed to recreate the sentence again.
If decompress is chosen, the compressed text file will need to be found and using the position list given and the unique words - decompressed - the several sentences in the files need to be on separate lines.
Here is the code I have managed to create. It is a subroutine and it's rather faulty.
uniqueWords = []
positions = []
file =
def valChoice():
choice = (" ")
while choice not in ["compress", "decompress"]:
choice = input("Choose compress or decompress").lower()
if choice not in ["compress", "decompress"]:
print("Please input compress or decompress")
finalChoice = valChoice()
if finalChoice = ("compress"):
print("This where i get confused..")
elif finalChoice = ("decompress"):
print("This where i get confused..")
What is wrong with this code? How can I fix it?
With my caveat above, I'll take a shot at what I think you're asking.
To compress the file, iterate through the input words. Store each word reference in a dictionary: the word itself is the key, and its position is the value. If the word is already in the dictionary, then add the new position reference to the existing list of references.
Decompression works in reverse: make a sequence of positions and words. Sort that sequence into ascending order. Concatenate the words to make the original text.
Is that the level of help you need right now?
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
the following problem in python please .....
Assuming that s is a string of lower case characters.
how would I write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then my program would print
'Number of times bob occurs is: 2'
I am a completely new to python and appreciate any help
If you didn't want to count overlapping bobs as separate values, this would be easy:
s.count('bob')
But you apparently do. (I had to guess that, based on the fact that your intended output is 2 rather than 1… in the future, it would be better to explain your problem instead of leaving it ambiguous.) As the help says, count returns "the number of non-overlapping occurrences of substring sub…", so that won't do any good.
So, for that, you will have to do it manually. I'll show an example that should have enough to get you started:
for i in range(len(s)):
if s[i:].startswith('bob'):
print('Found a bob')
A slightly smarter way to do this would be to use the find method on strings. You can find details on this in the online docs, or by typing help(str.find) in the interactive console. Notice that find takes a start argument. You should be able to figure out how this would help you; it may take a bit of work to get the details right, but if you get stuck, you can always post a new question asking for specific help.
You can try this way
string = "BOBOBOBOBOABCDE"
search = "BOB"
print len([i for i in range(len(string)) if string.startswith(search, i)])