How do I calculate something inside a 'for' loop? - python

I'm doing an assignment in which I have to move a simulated robot across the screen in a loop - I've got that part down, however, between loops, I also have to print the percentage of area covered with each movement - that's my issue.
I googled a bit and even found someone with the same problem, however, I'm not sure if I'm doing it properly.
This code was offered:
percent_complete = 0
for i in range(5):
percent_complete += 20
print('{}% complete'.format(percent_complete))
However, after an error, further googling revealed that only worked with certain versions
so I used this code:
percent_complete = 0
for i in range(5):
percent_complete += 20
print '% complete' % (percent_complete)
And, at the very least, it now executes the code, however, the output when printing is the following:
Here we go!
hello
omplete
hello
(omplete
hello
<omplete
hello
Pomplete
hello
domplete
What is the cause of this? I assume because one of the codes had to be edited, the other parts do as well, but I'm not sure what needs to be done.

for i in range(5):
percent_complete += 20
print '%d complete' % (percent_complete)
You were missing the d specifier.

The first version only works in Python 3 because it uses print as a function. You're probably looking for the following:
percent_complete = 0
for i in xrange(5):
percent_complete += 20
print '{0} complete'.format(percent_complete)
Your other code doesn't do what you intend to do because it now display the number as a string. What you want is that the number is properly converted to a string first and then displayed in the string. The function format does that for you.
You can also use Ansari's approach which explicitly specifies that percent_complete is a number (with the d specifier).

To add to/correct above answers:
The reason your first example didn't work isn't because print isn't a function, but because you left out the argument specifier. Try print('{0}% complete'.format(percent_complete)). The 0 inside the brackets is the crucial factor there.

Related

python program runtime taking so long/won't end

so i'm doing the dna problem for cs50 wherein i have to count the number of times a STR repeats in a dna sequence. i had an idea on how to solve the problem so i took one of the data and ran my code but the problem is that the program doesn't end and keeps running i think it has been about 10 minutes now from when i started the program and it still like this. here's the code:
text="AAGGTAAGTTTAGAATATAAAAGGTGAGTTAAATAGAATAGGTTAAAATTAAAGGAGATCAGATCAGATCAGATCTATCTATCTATCTATCTATCAGAAAAGAGTAAATAGTTAAAGAGTAAGATATTGAATTAATGGAAAATATTGTTGGGGAAAGGAGGGATAGAAGG"
length=len(text)
AGAT=0
tmp=0
for i in range(length):
while text[i]=="A" and text[i+1]=="G" and text[i+2]=="A" and text[i+3]=="T":
tmp+=1
if tmp>AGAT:
AGAT=tmp
else:
AGAT=AGAT
print("done")
As mentioned in the comments there is an infinite loop in your while loop, you could just remove it and choose to use a sliding window technique where you go over the text looking at neighbouring slices of 4 adjacent characters at a time:
text = "AAGGTAAGTTTAGAATATAAAAGGTGAGTTAAATAGAATAGGTTAAAATTAAAGGAGATCAGATCAGATCAGATCTATCTATCTATCTATCTATCAGAAAAGAGTAAATAGTTAAAGAGTAAGATATTGAATTAATGGAAAATATTGTTGGGGAAAGGAGGGATAGAAGG"
search_seq = "AGAT"
count = 0
for i in range(len(text) - len(search_seq) + 1):
if text[i:i+len(search_seq)] == search_seq:
count += 1
print(f"Sequence {search_seq} found {count} times")
Output:
Sequence AGAT found 5 times
I know this is a weird way to solve your problem but i wanted to do something a bit different...
Try this:
agat_string="AAGGTAAGTTTAGAATATAAAAGGTGAGTTAAATAGAATAGGTTAAAATTAAAGGAGATCAGATCAGATCAGATCTATCTATCTATCTATCTATCAGAAAAGAGTAAATAGTTAAAGAGTAAGATATTGAATTAATGGAAAATATTGTTGGGGAAAGGAGGGATAGAAGG"
agat_list=[AGAT for AGAT in range(len(agat_string)) if agat_string.find("AGAT", AGAT) == AGAT] #finds the indices of "AGAT" ;-)
print(len(agat_list))
The output:
5
Also, as someone said, tmp has nothing to do with the while condition. It just throws you in an infinite loop....

Beginning Equations in Code not being Shown in Output

Relatively new to Python. Equations I've written work alone, but I can't seem to figure out why only the last bit of the code is being shown in output.
I've tried using concatenation to no avail.
X = input('Enter X:')
Y = input('Enter Y:')
X1=int(X)
Y1=int(Y)
(X1+Y1)/(X1-Y1), (X1-Y1)**3,
Answer = X1+Y1
print ('The last digit of X+Y is ' + str(Answer)[1])
I know the answer is most likely going to be quite simple, but any bit of advice helps!
In jupyter notebook by default give output at the end of the line code in single code cell unless you explicitly define print statement
Eg:
X=10
X*3
X*45
#op
450
In above code it will give only last line output
If you had print statement every line then you will get all the line output
X=10
print(X*3)
print(X*45)
#op
30
450
Only the last statement was being printed because that was the only one with a print statement. Just adding print to (X1+Y1)/(X1-Y1), (X1-Y1)**3, will fix the problem. So like this: print((X1+Y1)/(X1-Y1), (X1-Y1)**3)

Using a class-object's function output later in the program [Python 2.7]

I would first like to apologize for how much of a beginner I am, however I have hit this wall after many other hurdles. The basis of this is to retrieve a value from a website, modify it using variables and print the final value. My knowledge of classes and objects is very very minimal. I just cannot figure out how I can take the value numTotal from my function getPlays and use it later to print as Final. The value prints correctly from within the function I just need to store that value for later use as a variable.
class GetPlaycount(object):
def getPlays(self):
print "Working"
browser = webdriver.PhantomJS('C:\Python27\phantomjs-2.0.0-windows\phantomjs.exe')
browser.get('https://osu.ppy.sh/u/4973241')
time.sleep(1)
Plays = browser.find_element_by_xpath('//*[#id="general"]/div[8]').text
numPlays = int(re.sub('[^0-9]', '', Plays))
numTime = int(numPlays) * int(numLength)
numTotal = int(numTime) * float(numVar)
print int(numTotal)
return numTotal
myClassObject = GetPlaycount()
myClassObject.getPlays()
Final = ????
print Final
raw_input("wait")
Thank you for your help and patience.
If I understand the question correctly
final = myClassObject.getPlays()
print final
Should be all you need.

Why while loop is sticking at raw_input? (python)

In the following code i am trying to make a "more" command (unix) using python script by reading the file into a list and printing 10 lines at a time and then asking user do you want to print next 10 lines (Print More..).
Problem is that raw_input is asking again and again input if i give 'y' or 'Y' as input and do not continue with the while loop and if i give any other input the while loop brakes.
My code may not be best as am learning python.
import sys
import string
lines = open('/Users/abc/testfile.txt').readlines()
chunk = 10
start = 0
while 1:
block = lines[start:chunk]
for i in block:
print i
if raw_input('Print More..') not in ['y', 'Y']:
break
start = start + chunk
Output i am getting for this code is:-
--
10 lines from file
Print More..y
Print More..y
Print More..y
Print More..a
You're constructing your slices wrong: The second parameter in a slice gives the stop position, not the chunk size:
chunk = 10
start = 0
stop = chunk
end = len(lines)
while True:
block = lines[start:stop] # use stop, not chunk!
for i in block:
print i
if raw_input('Print More..') not in ['y', 'Y'] or stop >= end:
break
start += chunk
stop += chunk
Instead of explaining why your code doesn't work and how to fix it (because Tim Pietzcker already did an admirable job of that), I'm going to explain how to write code so that issues like this don't come up in the first place.
Trying to write your own explicit loops, checks, and index variables is difficult and error-prone. That's why Python gives you nice tools that almost always make it unnecessary to do so. And that's why you're using Python instead of C.
For example, look at the following version of your program:
count = 10
with open('/Users/abc/testfile.txt', 'r') as testfile:
for i, line in enumerate(testfile):
print line
if (i + 1) % count == 0:
if raw_input('Print More..') not in ['y', 'Y']:
break
This is shorter than the original code, and it's also much more efficient (no need to read the whole file in and then build a huge list in advance), but those aren't very good reasons to use it.
One good reason is that it's much more robust. There's very little explicit loop logic here to get wrong. You don't even need to remember how slices work (sure, it's easy to learn that they're [start:stop] rather than [start:length]… but if you program in another language much more frequently than Python, and you're always writing s.sub(start, length), you're going to forget…). It also automatically takes care of ending when you get to the end of the file instead of continuing forever, closing the file for you (even on exceptions, which is painful to get right manually), and other stuff that you haven't written yet.
The other good reason is that it's much easier to read, because, as much as possible, the code tells you what it's doing, rather than the details of how it's doing it.
But it's still not perfect, because there's still one thing you could easily get wrong: that (i + 1) % count == 0 bit. In fact, I got it wrong in my first attempt (I forgot the +1, so it gave me a "More" prompt after lines 0, 10, 20, … instead of 9, 19, 29, …). If you have a grouper function, you can rewrite it even more simply and robustly:
with open('/Users/abc/testfile.txt', 'r') as testfile:
for group in grouper(testfile, 10):
for line in group:
print line
if raw_input('Print More..') not in ['y', 'Y']:
break
Or, even better:
with open('/Users/abc/testfile.txt', 'r') as testfile:
for group in grouper(testfile, 10):
print '\n'.join(group)
if raw_input('Print More..') not in ['y', 'Y']:
break
Unfortunately, there's no such grouper function built into, say, the itertools module, but you can write one very easily:
def grouper(iterator, size):
return itertools.izip(*[iterator]*size)
(If efficiency matters, search around this site—there are a few questions where people do in-depth comparisons of different ways to achieve the same effect. But usually it doesn't matter. For that matter, if you want to understand why this groups things, search this site, because it's been explained at least twice.)
As #Tim Pietzcker pointed out, there's no need of updating chunk here, just use start+10 instead of chunk.
block = lines[start:start+10]
and update start using start += 10.
Another alternative solution using itertools.islice():
with open("data1.txt") as f:
slc=islice(f,5) #replace 5 by 10 in your case
for x in slc:
print x.strip()
while raw_input("wanna see more : ") in("y","Y"):
slc=islice(f,5) #replace 5 by 10 in your case
for x in slc:
print x.strip()
this outputs:
1
2
3
4
5
wanna see more : y
6
7
8
9
10
wanna see more : n

Possible Google Riddle?

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.
t-shirt
So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.
My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying.
Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help.
I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses.
I hope someone knows better.
#This code interprets the google t-shirt as a binary code, each box 4 bits.
# I try every permutation of counting the bits and then try to interpret these
# interpretations as letters, or hex numbers, or ip addresses.
# I need more interpretations, maybe one will find a pattern
import string
#these represent the boxes binary codes from left to right top to bottom
boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001']
#changing the ordering
permutations = ["1234", "1243", "1324", "1342", "1423", "1432",
"2134", "2143", "2314", "2341", "2413", "2431",
"3124", "3142", "3214", "3241", "3412", "3421",
"4123", "4132", "4213", "4231","4312", "4321"]
#alphabet hashing where 0 = a
alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d',
'0100':'e', '0101':'f', '0110':'g', '0111':'h',
'1000':'i', '1001':'j', '1010':'k', '1011':'l',
'1100':'m', '1101':'n', '1110':'o', '1111':'p'}
#alphabet hasing where 1 = a
alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c',
'0100':'d', '0101':'e', '0110':'f', '0111':'g',
'1000':'h', '1001':'i', '1010':'j', '1011':'k',
'1100':'l', '1101':'m', '1110':'n', '1111':'o'}
hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3',
'0100':'4', '0101':'5', '0110':'6', '0111':'7',
'1000':'8', '1001':'9', '1010':'a', '1011':'b',
'1100':'c', '1101':'d', '1110':'e', '1111':'f'}
#code to convert from a string of ones and zeros(binary) to decimal number
def bin_to_dec(bin_string):
l = len(bin_string)
answer = 0
for index in range(l):
answer += int(bin_string[l - index - 1]) * (2**index)
return answer
#code to try and ping ip addresses
def ping(ipaddress):
#ping the network addresses
import subprocess
# execute the code and pipe the result to a string, wait 5 seconds
test = "ping -t 5 " + ipaddress
process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE)
# give it time to respond
process.wait()
# read the result to a string
result_str = process.stdout.read()
#For now, need to manually check if the ping worked, fix later
print result_str
#now iterate over the permuation and then the boxes to produce the codes
for permute in permutations:
box_codes = []
for box in boxes:
temp_code = ""
for index in permute:
temp_code += box[int(index) - 1]
box_codes.append(temp_code)
#now manipulate the codes using leter translation, network, whatever
#binary
print string.join(box_codes, "")
#alphabet1
print string.join( map(lambda x: alphabet1[x], box_codes), "")
#alphabet2
print string.join( map(lambda x: alphabet2[x], box_codes), "")
#hex
print string.join( map(lambda x: hex[x], box_codes), "")
#ipaddress, call ping and see who is reachable
ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2])
ip = ""
for code in ipcodes:
bin = bin_to_dec(code[0] + code[1])
ip += repr(bin) + "."
print ip[:-1]
#ping(ip[:-1])
print
print
t-shirt.
I emailed the Website Optimizer Team, and they said "There's no secret code, unless you find one. :)"
I think Google are just trying to drive their point home - here are a bunch of different representations of the same page, test them, see which is best.
Which block do you like best?
I think it's simply a design, nothing secret, or mysterious.
What if it doesn't mean anything, what if it is just a neat design they came up with?
It says: "You are getting closer".
Well, I can't see an immediate pattern. But if you are testing IP, why not take two blocks of 4 as a single binary number.
Probably it's a base 4 notation?
I would try that, but I don't have any approach to this.
It reminded me of cellular automata:
http://www.wolframalpha.com/input/?i=rule+110
Anyone going that direction?

Categories

Resources