How to compare all elements of a list [closed] - python

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 1 year ago.
Improve this question
This code in under is will let the user enter the number of elements of list and the user need enter the elements ( User will need type number_of_elements_of_list times) and then count how many positive number, negative number, zero number. The code is like this:
the_number_of_elements_of_the_list = int(input())
number_list = []
for i in range(1, the_number_of_elements_of_the_list + 1):
number_list.append(int(input()))
positive_number_count = 0
negative_number_count = 0
zero_number_count = 0
if number_list == 0:
zero_number_count += 1
elif number_list == 1 or number_list > 1:
positive_number_count += 1
elif number_list < 0:
negative_number_count += 1
print(positive_number_count, negative_number_count, zero_number_count)
The code have a problem: The list can not compare like that. It will be error but i don't know how to compare the elements of list. Can you help me solve this problem?

Firstly, as teambob pointed out, add indent to the for-loop block.
Secondly, as DarkKnight pointed out, put the count variables outside the for-loop.
Thirdly, for each iteration, in order to use that value alone, use number_list[i-1] instead of number_list. (The index is i-1 rather than i because the range in your code starts from 1 rather than 0)
The final code would look like:
the_number_of_elements_of_the_list = int(input())
positive_number_count = 0
negative_number_count = 0
zero_number_count = 0
number_list = []
for i in range(1, the_number_of_elements_of_the_list + 1):
number_list.append(int(input()))
if number_list[i-1] == 0:
zero_number_count += 1
elif number_list[i-1] == 1 or number_list[i-1] > 1:
positive_number_count += 1
elif number_list[i-1] < 0:
negative_number_count += 1
print(positive_number_count, negative_number_count, zero_number_count)

Related

counting number of steps to reduce integer to 0 [closed]

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 1 year ago.
Improve this question
so I'm new to learning def function() in python. And I'm implementing a code that counts the number of steps to reduce an integer to zero.
I have defined a function that makes a list of the integer input by the user, and another function that counts the steps.
the problem is in the second function: currentlynumberOfSteps only takes the first input, but it needs to take all user inputs listed by the first function UserEntryList
def UserEntryList ():
integerEntry = input("Please enter: ")
integerEntry = integerEntry.split()
listOfInt = []
for i in integerEntry:
try:
listOfInt.append(int(i))
except ValueError:
continue
return(listOfInt)
def numberOfSteps():
counter = 0
listofnumbers = UserEntryList()
for i in listofnumbers:
while i > 0:
if i % 2 == 0:
i /= 2
else:
i -= 1
counter += 1
return counter
desired output:
Please enter a set of space-separated positive integers: 10 15 59
[(10, 5), (15, 7), (59, 10)]
First off, couple of things:
always use snake_case in Python, instead of camelCase or PascalCase. More on naming conventions in Python here
return statement in Python should not be enclosed by brackets, unless you're returning a tuple. More on this here.
in the function numberOfSteps(), you have entered the return statement within the for loop. this will not work, as the program will terminate after processing the first item in your loop. So, append your results from each iteration to a list/dict (dict example is shown below.) and return it in the end after the for loop has completed.
def numberOfSteps():
counter = 0
listofnumbers = UserEntryList()
counter_dict = {}
for i in listofnumbers:
temp = i
while i > 0:
if i % 2 == 0:
i /= 2
else:
i -= 1
counter += 1
counter_dict[temp] = counter
return counter_dict
And to answer your question, you can just do append this at the end of your code:
if __name__ == "__main__":
counter = numberOfSteps()
print("Counter = " + str(counter))
Here is a proper way of defining the main function and call sub-function from main function. You will not need to pass any arguments to any functions since you are directly calling UserEntryList from numberOfSteps, which gets executed from the main function.
def UserEntryList ():
integerEntry = input("Please enter: ")
integerEntry = integerEntry.split()
listOfInt = []
for i in integerEntry:
try:
listOfInt.append(int(i))
except ValueError:
continue
return(listOfInt)
def numberOfSteps():
counter = 0
listofnumbers = UserEntryList()
for i in listofnumbers:
while i > 0:
if i % 2 == 0:
i /= 2
else:
i -= 1
counter += 1
return counter
def main():
counter = numberOfSteps()
print("Counter = " + str(counter))
if __name__ == "__main__":
main()

list index out of range with if condition [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
num_array = list()
num = int(raw_input("Enter how many elements you want:"))
print 'Enter numbers in array: '
for i in range(int(num)):
n = raw_input("num :")
num_array.append(int(n))
print 'ARRAY: ',num_array
b = 0
count = 0
while b< num -1 or b>0:
count = count+1
if num_array[b]!= 0:
b = b + num_array[b]
else:
b = (b + num_array[b])*2
print count
i am trying to get an array as an input anD storing a index value in a variable which is updating its values. But i am getting an error of list out of range
Please help me
Your condition while b < num-1 or b>0 does not make sense. The or b>0 part makes it True for all values larger than num-1. Instead, you should use and:
while b < num-1 and b > 0:
Or shorter, using comparison chaining:
while 0 < b < num-1:
Also, note that array indices go from 0 to num-1 (num being the length), so actually the condition should probably be (not tested, though):
while 0 <= b < num:

Replacing numbers ending in 3 and 7 in a string [closed]

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 6 years ago.
Improve this question
Write a program that generates and prints a list of n elements (n informed by the user) containing the natural numbers (starting with 1) and replacing multiples of 3 by the word 'ping', multiples of 7 by the word 'pong', and multiples of 3 and 7 by the word 'ping-pong'
Here is the code for that
result = []
number = eval(input("Enter a whole number: "))
for index in range(number):
if index % 7 == 0 and index % 3 == 0:
result.append("ping-pong")
elif index % 3 == 0:
result.append("ping")
elif index % 7 == 0:
result.append("pong")
else:
result.append(index)
print(result) == 0
Now also replaces numbers ending in 3 by the word ‘PING’ and numbers ending in 7 by the word ‘PONG’ this I am not sure how to go about doing.
I tried to make your code do what you want while doing as few modifications to it as possible.
Do NOT use eval. Ever. Bad, bad, bad eval. To cast an string to an int, use int().
Your code was starting at 0 when it was asked that it started at 1, I
changed the range.
To know the last digit, I calculated the number modulo 10, based on the clever comment by #Renuka Deshmukh. Other less clever solutions could have been to check the end of the number casted as a string, with str(index).endswith("7") or str(index)[-1] == "7", for example.
What was your print(result) == 0 trying to do? I removed the ==0.
Here is the resulting code:
result = []
number = int(input("Enter a whole number: "))
for index in range(1,number+1):
if index % 7 == 0 and index % 3 == 0:
result.append("ping-pong")
elif index % 3 == 0 or index % 10 == 3:
result.append("ping")
elif index % 7 == 0 or index % 10 == 7:
result.append("pong")
else:
result.append(index)
print(result)

How to end a nested loop? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I wrote a script to perform a connectivity search in a binary image (the possible values for the array are 0 and 1). For each pixel, the code looks at how many neighbours have intensity 1, and if there are at least 5 neighbours with I=1, it assigns 1 as a value of the considered pixel. I want the code to repeat the process until no new pixels are assigned intensity 1. At present the code is not performing the connectivity search iteratively; do you have any suggestion on how to fix this?
pixel_count = 0
pixel_counter = [0] * 100
for p in range(1, 100):
if p < 3:
continue
else:
if pixel_counter[p-1] > pixel_counter[p-2]:
continue
else:
break
for q in range(1, ran_x-1):
for r in range(1, ran_y-1):
counter = 0
if neighbours_mask_1[q,r] == 1:
counter = counter +1
if neighbours_mask_2[q,r] == 1:
counter = counter +1
if neighbours_mask_3[q,r] == 1:
counter = counter +1
if neighbours_mask_4[q,r] == 1:
counter = counter +1
if neighbours_mask_5[q,r] == 1:
counter = counter +1
if neighbours_mask_6[q,r] == 1:
counter = counter +1
if neighbours_mask_7[q,r] == 1:
counter = counter +1
if neighbours_mask_8[q,r] == 1:
counter = counter +1
if counter > 5:
mask_1[q,r] = 1
pixel_count = pixel_count + 1
print pixel_count
else:
mask_1[q,r] = 0
pixel_counter[p] = pixel_count
This section of the code:
for p in range(1, 100):
...
if pixel_counter[p-2] > pixel_counter[p-1]:
continue
else:
break
... dead code ...
will slurp all of the execution, the part where I've marked dead code, which contains your counters are never executed because they're unreachable.
I'm not quite sure what your trying to do there.
To answer the question in the title: the easiest way to exit a nested loop is to just move the loops into a function and return from that. E.g.
def f():
for i in range(10):
for j in range(10):
if i + j == 9: return

check consecutive number in two lists [closed]

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
pseudocode:
A = [1,2,3,4,5,6,7,8,9]
B = [4,5,6,7,1,2,6,7,8]
count = 0
for i in range(len(A)):
for j in range(len(B)):
if A[i:i+3] == B[j:j+3]: #check 3 consecutive numbers if are equal
count += 1
print x[i:i+3]
print count
Question: how can I implement when A[4,5,6] == B[4,5,6], then skip to A[6,7,8]==B[6,7,8], instead of A[5,6,7]==B[5,6,7]
You can use a flag variable:
A = [1,2,3,4,5,6,7,8,9]
B = [4,5,6,7,1,2,6,7,8]
count = 0
skip = False #this is a flag variable
for i in range(len(A)):
for j in range(len(B)):
if skip:
skip = False
continue
if A[i:i+3] == B[j:j+3]: #check 3 consecutive numbers if are equal
count += 1
print x[i:i+3]
skip = True
print count

Categories