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 10 months ago.
Improve this question
import random
for i in range(5):
print(random.randint(1, 10))
Is it the number of integers that we want to print? But we didn't specify that it's the number of integers in the code, so how does python understand?
The Python for construct requires a variable name between for and in. Conventional practice is to use _ (underscore) as the variable in cases where a variable is required but not actually used/relevant. Note that _ is a valid variable name.
for i in range(5):
do this action
Is (the Python way of saying
"for each element in range(5)
do this action".
range(5) can be replaced by any iterable collection.
In this example the variable i is not used. We might write
for i in range(5):
print(i)
which would print out all the values from the expression range(5).
As you guessed, i in that code will be the number of random integers to be printed. That is because, in python, the range constructor will generate a sequence of integers when specified in the way you are showing.
If only one argument is specified, python will assume that you want to begin by the number zero, incrementing by one unit until it reaches the number one unit below the specified argument.
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 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 2 years ago.
Improve this question
I need to pass a variable '3-123' to a method in python, but if I do str(3-123) I get '-120'. Tried iterating, but I got an error cause it's an int.
You simply pass the string "3-123".
Your expression str(3-123) tells Python to first evaluate what is in parentheses, which is very clearly the arithmetic expression 3-123. That evaluation mandates a subtraction.
UPDATE PER USER COMMENT
Since you just got it returned from REST, then it's already a string. It seems that your problem is that you're building an expression string to be evaluated in SQL. In this case, you need to build the string you're going to send to SQL, at the character level. For this one item you would extend your 3-123 string with quotation marks:
from_rest = "3-123" # In practice, this comes directly from your REST return value.
to_sql = '"' + from_rest + '"'
This leaves you with a variable that contains the string "3-123" -- seven characters, rather than the original five.
Is that what you needed?
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 3 years ago.
Improve this question
Currently I am learning Python from the book 'The Coders Apprentice' and I have stumbled upon an exercise which I have the feeling that I have nearly solved, but I get an error when I execute the program.
This is the exercise:
Write a program that takes a string and produces a new string that contains the exact characters that the first string contains, but in order of their ASCII-codes.
For instance, the string "Hello, world!" should be turned into " !,Hdellloorw". This is
relatively easy to do with list functions, which will be introduced in a future chapter, but for now try to do it with string manipulation functions alone.
I have added the code below and the error message as a picture.
from pcinput import getString
entString=getString("Enter your string here: ")
yourString=entString.strip()
def positioner(oldPosition):
newPosition=0
x=0
while x<len(yourString):
if ord(yourString[oldPosition])>ord(yourString[x]):
newPosition+=1
x+=1
return newPosition
i=0
y=0
newString=""
while y<len(yourString):
if positioner(i)==y:
newString+=yourString[i]
y+=1
elif positioner(i)<y:
newString+=yourString[i]
if i<len(yourString):
i+=1
else:
i=0
print(newString)
What have I done wrong? I am new to programming.
You are getting an index error because the line if positioner(i)==y: is being called with a value of i equal to the length of yourString. yourString[oldPosition] is then accessing an index which doesn't exist.
This is happening because the loop condition (y<len(yourString)) isn't doing any checking on the value of i, which is the one causing problems.
Some other quick comments:
You can use yourString = input("Enter your string here: ") to replace the first four lines, as I'm not sure what pcinput is - and couldn't find any packages of the same name.
Instead of using the while/x+=1 construct, you could instead use a for x in range(len(yourString)), which is a little neater.
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 9 years ago.
Improve this question
Is it possible to combine the two statements inside 'for' loop.
num_pro=raw_input("ENTER THE NUMBER OF PRODUCTIONS: ")
right=[];left=[];
for i in range(int(num_pro)):
l,r=raw_input("ENTER PRODUCTION"+str(i+1)+" : ").split('->')
right.append(r);left.append(l)
sample input: E->abc
Append tuples to one list, then split out the lists using zip():
entries = []
for i in range(int(num_pro)):
entries.append(raw_input("ENTER PRODUCTION"+str(i+1)+" : ").split('->'))
left, right = zip(*entries)
zip(*iterable) transposes the nested list; columns become rows. Because you have two 'columns' (pairs of values), you end up with two rows instead.
Not without making it more complex. Each method needs to be called individually, and the only way to do that is either explicitly, as you have done, or in a loop.
If you are willing to store the whole production (which isn't necessarily a bad idea, since it keeps both sides synchronized) then just append the split result instead.
productions = []
for ...
productions.append(....split('->'))