I'm studying python and at the moment I'm focusing on Lists.
The book that I'm reading for it, uses this code as example for creating a third list it doesn't repeat elements that exists in both lists:
first = []
second = []
while True:
e = int(input("Enter a value for the first list (0 to end):"))
if e==0:
break
first.append(e)
while True:
e = int(input("Enter a value for the second list (0 to finish):"))
if e==0:
break
second.append(e)
third = []
two_lists = first[:]
two_lists.extend(second)
x=0
while x < len(two_lists):
y = 0
while y < len(third): #**THIS LINE IS MY QUESTION**
if two_lists[x] == third[y]:
break;
y=y+1
if y == len(third):
third.append(two_lists[x])
x=x+1
x=0
while x < len(third):
print(third[x])
x=x+1
So, when he says while y < len(third) I don't understand why the len(third) is 1 and not 0, since third is set empty before the while part. Is there's something I'm missing?
Thanks.
On the first iteration of the loop at line 18, len(third) is indeed 0 and not 1.
So we don't get into the while loop of line 20, but instead, get into the if clause at line 24, only from that part on len(third) would be positive.
That is true the first time it comes to that while loop.
However, the outer loop populates the third list.
the length of third for the initial iteration should be 0 so that whole while loop will be jumped.
Then the following if statement will test true as 0 is equal to 0 and an element would then be added to your third array.
Related
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
Here is the function i defined:
def count_longest(field, data):
l = len(field)
count = 0
final = 0
n = len(data)
for i in range(n):
count = 0
if data[i:i + l] is field:
while data[i - l: i] == data[i:i + l]:
count = count + 1
i = i + 1
else:
print("OK")
if final == 0 or count >= final:
final = count
return final
a = input("Enter the field - ")
b = input("Enter the data - ")
print(count_longest(a, b))
It works in some cases and gives incorrect output in most cases. I checked by printing the strings being compared, and even after matching the requirement, the loop results in "OK" which is to be printed when the condition is not true! I don't get it! Taking the simplest example, if i enter 'as', when prompted for field, and 'asdf', when prompted for data, i should get count = 1, as the longest iteration of the substring 'as' is once in the string 'asdf'. But i still get final as 0 at the end of the program. I added the else statement just to check the if the condition was being satisfied, but the program printed 'OK', therefore informing that the if condition has not been satisfied. While in the beginning itself, data[0 : 0 + 2] is equal to 'as', 2 being length of the "field".
There are a few things I notice when looking at your code.
First, use == rather than is to test for equality. The is operator checks if the left and right are referring to the very same object, whereas you want to properly compare them.
The following code shows that even numerical results that are equal might not be one and the same Python object:
print(2 ** 31 is 2 ** 30 + 2 ** 30) # <- False
print(2 ** 31 == 2 ** 30 + 2 ** 30) # <- True
(note: the first expression could either be False or True—depending on your Python interpreter).
Second, the while-loop looks rather suspicious. If you know you have found your sequence "as" at position i, you are repeating the while-loop as long as it is the same as in position i-1—which is probably something else, though. So, a better way to do the while-loop might be like so:
while data[i: i + l] == field:
count = count + 1
i = i + l # <- increase by l (length of field) !
Finally, something that might be surprising: changing the variable i inside the while-loop has no effect on the for-loop. That is, in the following example, the output will still be 0, 1, 2, 3, ..., 9, although it looks like it should skip every other element.
for i in range(10):
print(i)
i += 1
It does not effect the outcome of the function, but when debugging you might observe that the function seems to go backward after having found a run and go through parts of it again, resulting in additional "OK"s printed out.
UPDATE: Here is the complete function according to my remarks above:
def count_longest(field, data):
l = len(field)
count = 0
final = 0
n = len(data)
for i in range(n):
count = 0
while data[i: i + l] == field:
count = count + 1
i = i + l
if count >= final:
final = count
return final
Note that I made two additional simplifications. With my changes, you end up with an if and while that share the same condition, i.e:
if data[i:i+1] == field:
while data[i:i+1] == field:
...
In that case, the if is superfluous since it is already included in the condition of while.
Secondly, the condition if final == 0 or count >= final: can be simplified to just if count >= final:.
The goal of the program is to define a procedure that takes in a string of numbers from 1-9 and outputs a list with the following parameters:
Every number in the string should be inserted into the list.
If a number x in the string is less than or equal to the preceding number y, the number x should be inserted into a sublist. Continue adding the following numbers to the sublist until reaching a number z that is greater than the number y.
Then add this number z to the normal list and continue.
#testcases
string = '543987'
numbers_in_lists(string)
result = [5,[4,3],9,[8,7]]
def numbers_in_lists(string):
# Convert the sequence of strings into an array of numbers
i = 0
conv_str_e = []
while i < len(string):
conv_str_e.append(int(string[i]))
i += 1
#official code starts here
normal_list = []
list_of_small_nums = [[]]
# This will help me keep track of elements of the normal_list.
previous_e_pos = -1
e_pos = 0
# this one will be used to decide if the element should go into the
#normal_list or list_of_small_nums
check_point = 0
for e in conv_str_e:
#The first element and every elements bigger the element with
#check_point as it's index
#will be put into the normal_list as long as the list inside
#list_of_small_nums is empty
if e_pos == 0 or e > conv_str_e[check_point]:
#If the list inside list_of_small_nums is not empty
if list_of_small_nums[0] != []:
#concatenate the normal_list and list_of_small_nums
normal_list = normal_list + list_of_small_nums[0]
#Clear the list inside list_of_small_nums
list_of_small_nums[0] = []
#Add the element in the normal_list
normal_list.append(e)
# Update my trackers
e_pos += 1
previous_e_pos += 1
# (not sure this might be the error)
check_point = e_pos
#The curent element is not bigger then the element with the
#check_point as index position
#Therefor it goes into the sublist.
list_of_small_nums[0].append(e)
e_pos += 1
previous_e_pos += 1
return list
What you were doing wrong was exactly what you pointed out in your comments. You just kept increasing e_pos and so check_point eventually was greater than the length of the list.
I took the liberty of changing some things to simplify the process. Simple programs make it easier to figure out what is going wrong with them. Make sure you always try to think about the simplest way first to solve your problem! Here, I replaced the need for e_pos and previous_e_pos by using enumerate:
string = '543987'
# Convert the sequence of strings into an array of numbers
conv_str_e = [int(i) for i in string]
#official code starts here
normal_list = []
list_of_small_nums = []
# this one will be used to decide if the element should go into the
#normal_list or list_of_small_nums
check_point = 0
for ind, e in enumerate(conv_str_e):
#The first element and every elements bigger the element with
#check_point as it's index
#will be put into the normal_list as long as the list inside
#list_of_small_nums is empty
if ind == 0 or e > conv_str_e[check_point]:
#If the list inside list_of_small_nums is not empty
if list_of_small_nums != []:
#concatenate the normal_list and list_of_small_nums
normal_list.append(list_of_small_nums)
#Clear the list inside list_of_small_nums
list_of_small_nums = []
#Add the element in the normal_list
normal_list.append(e)
# Update my trackers
check_point = ind
else:
#The curent element is not bigger then the element with the
#check_point as index position
#Therefore it goes into the sublist.
list_of_small_nums.append(e)
# If there is anything left, add it to the list
if list_of_small_nums != []:
normal_list.append(list_of_small_nums)
print(normal_list)
Result:
[5, [4, 3], 9, [8, 7]]
I am sure you can change it appropriately from here to put it back in your function.
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
im running a for to check a list of tuples. something in the lines of
for i in range of b:
actual=i
temp1=(actual[0]+1,actual[1])
temp2=(actual[0],actual[1]-1)
temp3=(actual[0],actual[1]+1)
temp4=(actual[0]-1,actual[1])
And i want to make sure the temp's NEVER take the value of the tuple verified on the cycle before. Any idea on how to do this?
First, it seems that there's a problem with your code. range accepts integer input, so if b is an integer, for i in range(b) will give you integers [0, 1, 2, .. , b-1 ] in a list. You can't index into i using [], as you do on the next two lines.
If b is not an integer, but a collection, then you should use something like:
# Assuming b is a collection
for i in range(len(b)):
actual=b[i]
temp1=(actual[0]+1,actual[1])
temp2=(actual[0],actual[1]-1)
temp3=(actual[0],actual[1]+1)
temp4=(actual[0]-1,actual[1])
# Check if this is the first one. If it is, previous won't exist.
if i == 0:
continue
previous = b[i-1]
if previous in [ temp1, temp2, temp3, temp4 ]:
# This is what you want not to happen. Deal with it somehow.
pass
Here's my two cents.
Note that this will make temp(1-4) None if any match.
# assuming b is a collection
for i in range(len(b)):
actual=b[i]
if i!=0:
prev = b[i-1]
if i==0:
prev = [[['something']],[['ridiculous']]] #this is so that the rest of the code works even if index is 0
if (actual[0]+1,actual[1]) != prev: #if it is not the previous item
temp1=(actual[0]+1,actual[1]) #assign temp1
else:
temp1 = None #temp1 would otherwise automatically take on the value of (b[i-1][0]+1,b[i-1][1])
if (actual[0],actual[1]-1) != prev:
temp2=(actual[0],actual[1]-1)
else:
temp2 = None
if (actual[0],actual[1]+1) != prev:
temp3=(actual[0],actual[1]+1)
else:
temp3 = None
if (actual[0]-1,actual[1]) != prev:
temp4=(actual[0]-1,actual[1])
else:
temp4 = None