extract value from loop within a loop - python

I have a list of lists and i am trying to loop through to create a new value in the second list based on two elements with the second list.
for line in input_list[1:]:
i = 0
for element in line:
if i == 13:
if line[7] > line[8]:
line[13] == 1
else:
line[13] == 0
i += 1
I am trying to set the value of line[13] based on the condition that line[7] is greater than line[8].
The code does not flag any errors, so syntactically it is correct, but when i print for the new list, it does not display any values (0 or 1) for line[13].
Any help would be much appreciated.
Thanks,
Ed

Use line[13] = 1 instead of line[13] == 1. == is for comparison.

It will not show the correct output because you haven't use assignment operator . use line[13] = 1 instead of line[13] == 1
Example :- list= [[1,2],[3,4,5]]
For this list -
for line in list[1:]:
i=0
for element in line:
if i==1:
if line[0]>line[1]:
line[1]=1
else:
line[1]=200
i=i+1
It will work

for line in input_list[1:]:
i = 0
for element in line:
if i == 13:
if line[7] > line[8]:
line[13] = 1
else:
line[13] = 0
i += 1
code updated

Related

How is my python code going out of bound?

I've been trying to encode a string (ex: aabbbacc) to something like a2b3a1c2
this is the code i've tried:
string_value = "aabbbacc"
temp_string = ""
for i in range(0, len(string_value)):
if i != len(string_value) or i > len(string_value):
temp_count = 1
while string_value[i] == string_value[i+1]:
temp_count += 1
i += 1
temp_string += string_value[i] + str(temp_count)
print(temp_string)
the problem is even though I've added an if condition to stop out of bounds from happening, I still get the error
Traceback (most recent call last):
File "C:run_length_encoding.py", line 6, in <module>
while string_value[i] == string_value[i+1]:
IndexError: string index out of range
I've also tried
string_value = "aabbbacc"
temp_string = ""
for i in range(0, len(string_value)):
count = 1
while string_value[i] == string_value[i+1]:
count += 1
i += 1
if i == len(string_value):
break
temp_string += string_value[i]+ str(count)
print(temp_string)
now, I know there might be a better way to solve this, but I'm trying to understand why I'm getting the out of bounds exception even though i have an if condition to prevent it, at what part of the logic am I going wrong please explain...
The problem is here:
for i in range(0, len(string_value)): # if i is the last index of the string
count = 1
while string_value[i] == string_value[i+1]: # i+1 is now out of bounds
The easiest way to avoid out-of-bounds is to not index the strings at all:
def encode(s):
if s == '': # handle empty string
return s
current = s[0] # start with first character (won't fail since we checked for empty)
count = 1
temp = ''
for c in s[1:]: # iterate through remaining characters (string slicing won't fail)
if current == c:
count += 1
else: # character changed, output count and reset current character and count
temp += f'{current}{count}'
current = c
count = 1
temp += f'{current}{count}' # output last count accumulated
return temp
print(encode('aabbbacc'))
print(encode(''))
print(encode('a'))
print(encode('abc'))
print(encode('abb'))
Output:
a2b3a1c2
a1
a1b1c1
a1b2
First this check is odd :
if i != len(string_value) or i > len(string_value):
Second, you check i but read value for i+1, and potentially next...
So my suggestion is to put the condition inside of your while.
And do not allow string_value[i] to be read after you have checked that i==len(string_value).
(I remind you that : "The break statement, like in C, breaks out of the innermost enclosing for or while loop.")
Iterate thru each char in the string then check if the next char is the same with current. If yes, then add one else add the count to temp string and reset the count to 1.
string_value = "aabbbacc"
temp_string = ""
count = 1
for i in range(len(string_value)-1):
if string_value[i] == string_value[i+1]:
count += 1
else:
temp_string += string_value[i]+ str(count)
count = 1
#add the last char count
temp_string += string_value[i+1]+ str(count)
print(temp_string)
Out: a2b3a1c2

Is there a way to increment the iterator if an 'if' condition is met

I'm solving this HackerRank challenge:
Alice has a binary string. She thinks a binary string is beautiful if and only if it doesn't contain the substring '010'.
In one step, Alice can change a 0 to a 1 or vice versa. Count and print the minimum number of steps needed to make Alice see the string as beautiful.
So basically count the number of '010' occurrences in the string 'b' passed to the function.
I want to increment i by 2 once the if statement is true so that I don't include overlapping '010' strings in my count.
And I do realize that I can just use the count method but I wanna know why my code isn't working the way I want to it to.
def beautifulBinaryString(b):
count = 0
for i in range(len(b)-2):
if b[i:i+3]=='010':
count+=1
i+=2
return count
Input: 0101010
Expected Output: 2
Output I get w/ this code: 3
You are counting overlapping sequences. For your input 0101010 you find 010 three times, but the middle 010 overlaps with the outer two 010 sequences:
0101010
--- ---
---
You can't increment i in a for loop, because the for loop construct sets i at the top. Giving i a different value inside the loop body doesn't change this.
Don't use a for loop; you could use a while loop:
def beautifulBinaryString(b):
count = 0
i = 0
while i < len(b) - 2:
if b[i:i+3]=='010':
count += 1
i += 2
i += 1
return count
A simpler solution is to just use b.count("010"), as you stated.
If you want to do it using a for loop, you can add a delta variable to keep track of the number of positions that you have to jump over the current i value.
def beautifulBinaryString(b):
count = 0
delta = 0
for i in range(len(b)-2):
try:
if b[i+delta:i+delta+3]=='010':
count+=1
delta=delta+2
except IndexError:
break
return count
You don't need to count the occurrences; as soon as you find one occurrence, the string is "ugly". If you never find one, it's beautiful.
def is_beautiful(b):
for i in range(len(b) - 2):
if b[i:i+3] == '010':
return False
return True
You can also avoid the slicing by simply keeping track of whether you've started to see 010:
seen_0 = False
seen_01 = False
for c in b:
if seen_01 and c == '0':
return False
elif seen_1 and c == '1':
seen_01 = True
elif c == '0':
seen_0 = True
else:
# c == 1, but it doesn't follow a 0
seen_0 = False
seen_01 = False
return True

I have a list and I want to count the occurrence of items at a certain position in my list

I have a file which was transformed to a list. Now I want to count the occurrence of specific elements in a list at a specific position. Here is my code so far:
Inpu = open("I.txt","r")
entries = []
for line in Inpu:
line=line.lstrip()
if not line.startswith('#'):
row = line.split()
entries.append(row)
count0 = 0
count1 = 0
for item in entries:
try:
if item[3] == '1':
count1 += 1
if item[3] == '0':
count0 += 1
print item
except IndexError:
continue
This for loop statement works fine and gives me total of count1 and count0 in my file.
for line in Inpu:
line=line.lstrip
if not line.startwith('#'):
rows=line.split()
peptide_count.append(row)
for line in Inpu:
for i in line:
while i in line[0]=='1':
peptide_length+=1
if i in line[3] == '1':
count1= str(line[3]).count(1)
print (count1)
if i in line[3] == '0':
count0=str(item[3]).count(0)
print str(count0)
else:
if i in line[0]=='>':
break
print ("peptide_Lengths|1s|0s")
print(str(peptide_length) + "\t" + str(countones) + "\t" + str(countz))
This on the other hand is suppose to count the number of occurrences of zero's and ones's in line 3 when line[0] position starts with 1 and should break when it comes a cross '>' in line[0] in my file. But here is the out put I get which is obviously wrong:
peptide_Lengths|1s|0s
0 0 0
Is there anything I'm doing wrong or missing?

Looping over webservice results not working

I'm trying to use a webservice and loop over the result set.
For some reason it only gives me back the first result which in this case is:
Overall Rank: 537316 Level: 1419 Xp: 6407333
It seems to stop and not cycle through the rest of the results in the list of list which is from stat_list from the grab_api function.
stat_list is a list in a list with strings of numbers inside.
import urllib2
import re
def grab_api():
stat_list = []
response = urllib2.urlopen('http://services.runescape.com/m=hiscore/index_lite.ws?player=taroboxx')
html = response.read()
stat_list.append(re.split(r"[,\n]", html))
return stat_list
def check_score(hiscore_html):
stats = ["Overall", "Attack", "Defence", "Strength", "Constitution", "Ranged", "Prayer", "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecrafting", "Hunter", "Construction", "Summoning", "Dungeoneering", "Divination"]
hiscore = 0
stat = 0
for i in hiscore_html[0]:
if hiscore == 0:
print stats[stat],
print "Rank:", i,
stat += 1
hiscore += 1
elif hiscore == 1:
print "Level:", i,
hiscore += 1
elif hiscore == 2:
print "Xp:", i
hiscore += 1
else:
hiscore == 0
check_score(grab_api())
In your else block you are doing hiscore == 0 instead of hiscore = 0.
As an output of the first function your get a list of lists, so there is no iteration inside the list you want: you go to a list (hiscore_html), and inside you find one more list which is the only item of hiscore_html.
In order to avoid it, you can refer to the first element of hiscore_html. But I just saw your update -- it's exactly what you're doing, and the other mistake was fixed below.

Appending a new line to file

I am wondering how to append a newline every time the list reaches the size of the checker board (8). Heres my code so far. It works but I want to put a newline every 8 characters.
saveFile=input("Please enter the name of the file you want to save in: ")
outputFile=open(saveFile,"w")
pieceList=[]
for row_index in range (self.SIZE):
for column_index in range(self.SIZE):
pieceRow=[]
char=" "
if self.grid[row_index][column_index]==Piece(Piece.WHITE):
char="w"
elif self.grid[row_index][column_index]==Piece(Piece.RED):
char="r"
pieceRow.append(char)
pieceList.append(pieceRow)
for item in pieceList:
for char in item:
outputFile.write("%s" %char)
Use
if row_index % 8 == 0:
# put newline
saveFile=input("Please enter the name of the file you want to save in: ")
outputFile=open(saveFile,"w")
pieceList=[]
characterCounter =0
for row_index in range (self.SIZE):
for column_index in range(self.SIZE):
pieceRow=[]
char=" "
if self.grid[row_index][column_index]==Piece(Piece.WHITE):
char="w"
elif self.grid[row_index][column_index]==Piece(Piece.RED):
char="r"
pieceRow.append(char)
characterCounter++
if characterCounter==8:
pieceRow.append("\n")
characterCounter=0
pieceList.append(pieceRow)
for item in pieceList:
for char in item:
outputFile.write("%s" %char)
cnt = 0
for item in pieceList:
for char in item:
outputFile.write("%s" %char)
cnt += 1
if cnt == 8:
outputFile.write("\n")
cnt = 0
Do you mean you want to append newline after each row?
Why not add
pieceRow.append("\n")
before
pieceList.append(pieceRow)
You could use enumerate,
For instance,
CONST_SIZE = 8
for index, item in enumerate(item_list):
output_file.write(item)
if index % 8 == 0: output_file.write('\n')
This will append a newline each time you've written 8 items to the file.

Categories

Resources