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 5 years ago.
Improve this question
Thanks for taking the time to ready thru my question.
At the moment I'm creating a method for a class, and below is what I've got so far.
def scramble_words_password(self, words):
if words:
words = words.split()
words_count = range(len(words))
while True:
num = random.choice(words_count)
del(words_count[num])
password = [letter for letter in list(words[num])]
A few months ago i came across a tutorial, that explained how to assing functions to variables, and use something like random on them but i cant find it again...
What I want in my function/method is a way to randomly use letter.lower() and letter.upper() on the comprehension on the bottom line of my function/method, but how can i achieve that and still keep it all in the comprehension.
FYI, I know that the function ATM is an infinity loop, so no smart remarks please ;)
User random.choice over a list of methods to call:
def scramble_words_password(self, words):
if words:
words = words.split()
words_count = range(len(words))
words_funcs = [str.upper, str.lower]
while True:
num = random.choice(words_count)
del(words_count[num])
password = [random.choice(words_funcs)(letter) for letter in list(words[num])]
Main call explain, random.choice(words_funcs)(letter), will choose a random element from the list, as they are callables you can just pass the letter to them. Keep in mind that all methods from strings (also other built-in types) can be called statically, so a list with str.lower and str.upper will do.
Function names act much like variables. You can pass them into other functions as parameters or make a list of functions. I suggest you create a list of functions and randomly select a list element.
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 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 1 year ago.
Improve this question
I have a list in Python of scores that are integers. I want to sort them from lowest to highest. I have tried looking it up, but I find that I don’t understand what most of them mean. I have heard of sorted(), but I’m not sure how it works. How can I sort a list of numbers? Will sorted() help?
Try sorted(scoreList).
Get the reference here.
Some problems with your approach:
You're not defining a scoreList variable in the code you posted. Maybe you want to pass it as parameter:
def sortList(scoreList):
You access the index of a list using [], and not ():
if scoreList[w] < scoreList[all]:
You don't check if all elements are greater than an element using [all]. Instead, use the all function:
if all(scoreList[w] < element for element in scoreList):
You assign a variable using =, and not ==:
scoreList[w] = scoreList[1]
Your logic is also wrong, there are some basic algorithms you can look up if you want to do it by hand, such as bubble sort or insertion sort.
Of course, there's always the sorted function.
I'm not sure what scoreList is since you used brackets after it.
If it's a list it should be done as [].
Assuming scoreList is a list:
scoreList = [3,5,67,83,555,38,22,1]
sortedList = []
for i in range(len(scoreList)):
sortedList.append(max(scoreList))
scoreList.remove(max(scoreList))
print(sortedList[::-1])
Remove [::-1] if you want in descending order.
This is of course you don't want to use scoreList.sort()
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 3 years ago.
Improve this question
I have been struggling with a task to check if a password has different attributes without for loop. Such as if it has lower case letters, upper case letters, numbers, symbols and so on. would really appreciate some help on the matter. I am new to recursive functions so I would be more than pleased if someone has an idea for a solution not involving them in python.
My attempt so far:
def strength(password):
if password[1:].isnumeric:
score = 0
if password[1:].isalpha():
score += 3
if password[1:].islower():
score += 2
if password[1:].isupper():
score += 2
if password[1:].isalpha():
score += 3
return score
Sorry that I didn't put this earlier, I'm still a little new to the site. This code only checks whether the entire password is numeric or lowercase or so on to my understanding. How can I extend this to check for other criteria, such as containing symbols?
You can create functions to check on each of those attributes (some of those already exist for Python's str object but it's a good exercise). The any operator will be your friend here:
def contains_upper(string):
uppers = 'ACBDEFGHIJKLMNOPQRSTUVWXYZ'
return any(s in uppers for s in string)
def contains_lower(string):
# etc... you should implement functions to check other attributes
Now create another function to assess if a given string pass all those tests:
def is_valid_password(string):
if not contains_upper(string):
return False
if not contains_lower(string):
return False
# do this for all attributes you want to check
return True
Using regular expressions:
import re
regexp = re.compile(r'[a-z]')
if regexp.search(mystring):
print("lower case found")
Then same with [A-Z] and so on
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
How should one name a list variable with ending s:
fpss,frame_rates, audios,
or
fps_records = []
frame_rate_records = []
audio_records = []
I don't think adding _records to the end adds anything of value. Avoid adding length to names that don't add clarity or insight for future reviewers, which will certainly include yourself. Adding meaningless verbiage will only serve to make your code harder to read and therefore harder to maintain.
If you think you're going to look at fps later and forget it's a list, use fps_list, which directly tells what type it is to any reader.
Please no-one interpret me as suggesting Hungarian notation. But I do do this when I'm starting out with a list, realize order doesn't matter and I need set-like behavior, and then realize I actually needed a mapping in the first place. Using that sort of convention allows me to implement my new structure completely without breaking the old.
For example, see this Python-style pseudo-code:
Iteration 1
def foo():
data = []
get_data_from_source()...
Iteration 2
def foo():
data_list = []
data_set = set()
get_data_from_source()...
Iteration 3
def foo():
data_set = set()
data_dict = {}
get_data_from_source()...
Iteration 4
def foo():
data = {}
get_data_from_source()...
return data
I agree with #Arone, however if required I would go with adding lst(like lst_records) with list(same we follow in legacy lang like vb) variables so if you would start typing lst immediately IDE would start suggesting all list.
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