Looping over webservice results not working - python

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.

Related

I have a defined a variable inside a for loop, but when printing it outside of the loop it doesn't print correctly

Here is the code:
count_1 = 0
count_0 = 0
list = ('001111011011','000110001010','011010111111')`
for i in list:
index = 0
y = i[index]
if y == "1":
count_1 = count_1 + 1
if y == "0":
count_0 = count_0 + 1
if count_1 > count_0:
for i in list:
final_after_1 = []
if i[0] == "1":
final_after_1.append(i)
formatted = (','.join(final_after_1))
if count_0 > count_1:
for i in list:
final_after_1 = []
if i[0] == "0":
final_after_1.append(i)
formatted = (','.join(final_after_1))
if count_0 == count_1:
for i in list:
final_after_1 = []
if i[0] == "1":
final_after_1.append(i)
print(final_after_1)
formatted = (','.join(final_after_1))
print(formatted)
(Apologies in advance if this question is worded badly, this is my first time asking a question).
This piece of code is working fine except for this one issue. It is designed to identify the first index of each 12-digit number in the list, and then work out if a 1 or 0 is more common in this position. It then selects all the numbers with the more common number in the first position and adds them to a list. I want to print this list at the end of the program.
I have defined a variable (called formatted) to be equal to a list of various numbers. When I print it out within the loop I have defined it in, it prints all the numbers that should be in the list, like this:
When I print it outside of the loop as in the code above it returns only the final number:
011010111111
Whereas printing it inside the loop like this:
if count_0 > count_1:
for i in list:
final_after_1 = []
if i[0] == "0":
final_after_1.append(i)
formatted = (','.join(final_after_1))
print(formatted)
does return this full desired list:
001111011011
000110001010
011010111111
Any ideas why this is happening?
Within you loop(s) the value of formatted is updated for each iteration. After the last iteration it is no longer updated and that last value is the output of the last print statement.
A simpler example:
for x in range(100):
pass//looping over, x is 0..99
print(x)
This will print out 99, the last value held by the variable "x".
Problably your code is updateing the variable for each iteration so in a for loop you need to append the values and not overwrite them, for example:
a = 0
b = 0
for i in 10:
a = 1
b = b + 1 # using the last value
print(a) # 1
print(b) # 9
First of all you shouldn't use "list" as a variable name because is a built-in name to instanciate lists or arrays. In second your code is repeated 3 times just for count a bit, let me show a better way with list compreenssions:
l = ('001111011011','000110001010','011010111111')
first_elements = list()
for x in l:
v = x[0] # first element
first_elements.append(int(v))
# [0,0,0]
count_0 = first_elements.count(0)
# count_0 = 3
count_1 = first_elements.count(1)
# count_1 = 0
Using list compreenssion
first_elements = [int(x[0]) for x in l]
# [0,0,0]
References: list compreenssions, list, list.count

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

extract value from loop within a loop

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

making a function that takes a list as input and return count of the string “bebo” in that list

I want a function called bebo_count that takes a list x as input and returns the count of the string “bebo” in that list.
For example, bebo_count(["bebo","buzz","bebo"]) should return 2
i have made a code like this
def bebo_count(x):
for a in x:
count = 0
if a == "bebo":
count += 1
return count
but it doesn't work it's always return 1 to me,can any one please modify this code to be working well?!
You keep resetting count = 0 in your loop, move it outside:
def bebo_count(x):
count = 0
for a in x:
if a == "bebo":
count += 1
return count
do not reinvent the wheel :-)
There is a built in method count
x = [ "bebo", "bv", "bebo" ]
x.count("bebo")
> 2
x.count("b")
> 0
You are setting count = 0 inside the for loop. That means that at each loop iteration, irrespective of what the value of count was before, it gets set back to zero. You should initialize count outside the loop. Note also that I have corrected your indentation.
def bebo_count(x):
count = 0
for a in x:
if a == "bebo":
count += 1
return count
For your reference, here is another way you might write this same function:
def bebo_count(x):
return len([a for a in x if a == "bebo"])
Your problem is: count = 0 is inside your for loop.
To fix your code :
def bebo_count(x):
count = 0 # initialize the count before you start counting
for a in x:
if a == "bebo":
count += 1
return count
However, a more pythonic way could be using list comprehension:
big_list = ["bebo", "something else", "bebo"]
def bebo_count(big_list) :
return len( [x for x in big_list if x=="bebo" ] )
print( bebo_count(big_list))

how to change the value of a variable inside an if loop each time the if loop is triggered ?

i am trying to use codeacademy to learn python. the assignment is to "Write a function called fizz_count that takes a list x as input and returns the count of the string “fizz” in that list."
# Write your function below!
def fizz_count(input):
x = [input]
count = 0
if x =="fizz":
count = count + 1
return count
i think the code above the if loop is fine since the error message ("Your function fails on fizz_count([u'fizz', 0, 0]); it returns None when it should return 1.") only appears when i add that code.
i also tried to make a new variable (new_count) and set that to count + 1 but that gives me the same error message
I would appreciate your assistance very much
The problem is that you have no loop.
# Write your function below!
def fizz_count(input):
count = 0
for x in input: # you need to iterate through the input list
if x =="fizz":
count = count + 1
return count
There is a more concise way by using the .count() function:
def fizz_count(input):
return input.count("fizz")
Get rid of x = [input], that just creates another list containing the list input.
i think the code above the if loop is fine
ifs don't loop; you're probably looking for for:
for x in input: # 'x' will get assigned to each element of 'input'
...
Within this loop, you would check if x is equal to "fizz" and increment the count accordingly (as you are doing with your if-statement currently).
Lastly, move your return-statement out of the loop / if-statement. You want that to get executed after the loop, since you always want to traverse the list entirely before returning.
As a side note, you shouldn't use the name input, as that's already assigned to a built-in function.
Putting it all together:
def fizz_count(l):
count = 0 # set our initial count to 0
for x in l: # for each element x of the list l
if x == "fizz": # check if x equals "fizz"
count = count + 1 # if so, increment count
return count # return how many "fizz"s we counted
def fizz_count(x): #DEFine func
count = 0 #set counter to zero
for item in x:
if item == "fizz" :
count += 1 #iterate counter +1 for each match
print count #print result
return count #return value
fizz_count(["fizz","buzz","fizz"]) #call func
Try this:
# Write your function below!
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count = count + 1
return count
def fizz_count(input)
count = 0
for x in input:
count += 1 if x=="fizz" else 0
return count

Categories

Resources