True if data in a row [duplicate] - python

This question already has answers here:
how to count consecutive duplicates in a python list [duplicate]
(3 answers)
Closed 6 months ago.
I want this function to print True if 200 occurs 3 times in a row. False otherwise.
def aList(n):
if n.count(200) >= 3:
return True
else:
return False
print(aList([100, 200, 200, 300, 200]))
Currently it is returning True because 200 exists 3 or more times, however it should return False because it is not occurring in a row.
Edit: Even if I iterate over the list, how can I pull True if the occurrence happens x amount of times.
for i in range(len(n)):
if i == 200:
return True
else:
return False

You need a variable to keep track of how many times you have seen the number in a row. Add one when you match the value and reset the count to 0 if you don't. Return true if you get to the threshold. If you finish the loop without hitting the threshold, return false.
def aList(n):
count = 0
for i in n:
if i == 200:
count += 1
else:
count = 0
if count == 3:
return True
return False
print(aList([100, 200, 200, 300, 200])) # -> False
print(aList([100, 200, 200, 200])) # -> True

So what you are trying to accomplish requires a consideration for positional elements... so you would need a counter to keep track of the counts and revert it back to zero when it does not match.. Little bit of pseudocode here, but something like this..
def nums_in_row(aList, target_num):
count = 0
for nums in aList:
if count ==3:
return True
elif nums == target_num:
count+=1
else:
count = 0
return False
target_num would be 200 in your example and aList would be the list itself. You could generalize your function further, but based on your question, it seems to suffice.

Related

checking duplicates in list using while loop

I'm trying to check for duplicate numbers within a list using only while loops and if statements. For some reason it is returning True for the list [1, 2, 3, 4, 5, 6] and I can't figure out why.
def has_duplicates(xs):
count = 0
while count < len(xs) and len(xs) > 1:
check = 1
while check < len(xs):
if xs[check] == xs[count]:
return True
else:
check += 1
count += 1
return False
I get the correct output using your function. However, there are certainly easier ways to get the same result, as:
def has_duplic2(xs):
return len(set(xs)) != len(xs)
In your first algorithm you shouldn't assing to the check variable the value of 1.
Otherwise on the second cycle of the loop both count and check will be 1 and you'll be comparing the element [1] of your list with itself, which will always return true.
Instead you should set the check variable to check = count + 1. So that you never compare a value with itself.

I have a Function which sometimes returns True, sometimes False. How do I count the Trues and False?

TLDR:
add
print(hundred())
to this code, and you will see the function returns sometimes True, sometimes False. How do I count these with a loop? If I use an if statement, it returns all True or all False over all iterations... Inside a loop the function is either True True True True True or False False False False... which makes no sense to me.
I have battled over this for 3 days. It's about a Coin Flip problem from Automate Boring Stuff. Been "programming" for 1 month or so with no prior exp.
So, this is the function, that returns False or True. I need to be able to count them somehow.
So, if the function is called 10 times (iterations variable), I need for each time it returns True to count them. I tried while loops, if statements, for loops, I don't get why it doesn't work... Really stuck.
import random
headtails = ['H', 'T']
resultlist = []
current = 1
total = []
count = 0
countlist = []
tries = 1
def hundred():
global resultlist, current, total, count, countlist, tries, headtails
for i in range(100):
x = random.choice(headtails)
resultlist.append(x)
if resultlist[i] != resultlist[i-1]:
current = 0
else:
current = current +1
if current >= 6:
total.append(current)
current = 0
if len(total) != 0:
return True
else:
return False
# function ends here, now we need to call it and count Trues and Falses.
# How do I do it? This doesn't work:
iterations = 0
number_of_true = 0
overalls = 0
while iterations < 10:
iterations += 1
if hundred():
number_of_true += 1
overalls += 1
elif hundred() is False:
overalls += 1
print(number_of_true, overalls)
OK I found the problem but not solution. If you call the function many times
print(hundred())
print(hundred())
print(hundred())
print(hundred())
they all going to be either False or True, which means they all point to the same value in memory. So, it's not possible to iterate its results in any way... damn, what do I do. I get a new result only when I run/stop program.
You're making two calls to hundred() each time you want to check if it's returning True or False, meaning you're not actually checking just one result, but two. Your while loop doesn't seem to have any end conditions either. Also your loop variable doesn't exist so your script throws an error. Lastly, overalls was unnecessary from what I could tell, since iterations kept track of that number anyway. Here's how I think the last section should look:
while iterations < 10:
iterations += 1
result = hundred()
if result:
number_of_true += 1
print(number_of_true, iterations)
When running the script, it either gives 10 10 or 0 10, which I'm not sure is what you want, but at least the loop part is correct. If you're having a problem with hundred() then I suggest asking another question about that specifically. I think the issue with it is due to you using too many globals, some of which need resetting each time you call the function.

Placing return false [duplicate]

This question already has answers here:
Pythonic way of checking if a condition holds for any element of a list
(3 answers)
Is there a short contains function for lists?
(6 answers)
Closed 6 months ago.
I am very new to coding, two weeks in.
So I do apologize if this is a very silly question.
I have been trying to complete the following codingbat problem:
Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4.
Why does the below code not return the correct answer?
def array_front9(nums):
if len(nums)>4:
count = 4
else:
count = len(nums)
for i in range(0,count):
if nums[i]==9:
return True
else:
return False
If the return False is placed on a new line and not in the loop it works.
Can someone please explain this to me.
On the first iteration of the loop, the loop checks if nums[0] is 9 and always returns either True or False; you're not giving any chance for the rest of the elements to be inspected. You should only return True if the element being inspected is 9, and return False only when this fails for the first four elements, i.e. outside the loop.
def array_front9(nums):
return 9 in nums[:4]
I think you need:
def array_front9(nums):
count = 4
if len(nums)<4:
count = len(nums)
if 9 in nums[:count]:
return True
return False
What's wrong with your code
if nums[i]==9:
return True
else:
return False
In above lines you're just checking for 1st value if it is 9 then it returns True else False
The problem in your code is if the first number in your list is not 9 then the loop will stop and function execution will stop it's because of return False in else condition.
def array_front9(nums):
count = [len(nums), 4][len(nums) > 5]
for i in range(count):
if nums[i] == 9:
return True
return False

How come in this code to find prime numbers, is_prime(9) returns True? [duplicate]

This question already has answers here:
Program that checks if a number is prime number
(5 answers)
Closed 4 years ago.
def is_prime(x):
if x < 2:
return False
else:
for n in range(2, x):
if x % n == 0:
return False
else:
return True
print is_prime(9) returns True instead of False.
I don't quite understand.
The range (2,9) includes this list: 2,3,4,5,6,7,8
and 9 % 3 == 0,
So how come I do not get False as the answer of that function?
This is because you don't actually loop, as you return True during the first cycle (9 % 2 == 0 is False).
Something like this should solve the problem:
def is_prime(x):
if x < 2:
return False
for n in range(2, x):
if x % n == 0:
return False
return True
You can simplify the logic a good amount by keeping your original loop and not exiting early. You can add your first conditional to your final return:
def is_prime(x):
for n in range(2, x):
if x % n == 0:
return False
return x > 2
BTW, the Sieve of Erastothenes is a pretty cool method of solving this problem in a much better run time complexity. Here's a link to a brief explanation:
https://math.stackexchange.com/questions/58799/why-in-sieve-of-erastothenes-of-n-number-you-need-to-check-and-cross-out-numbe

Looping through indices in array by 3s

I am attempting to create a function that check to see if the sum of three consecutive numbers in an array are equal to 7.
The first three indices in the list seem to work. However, my for loop does not continue throughout the entirety of the list. How do I resolve this?
def seven(array):
three = []
count = 0
for num in array[count::count+3]:
three.append(num)
if sum(three) == 7:
return True
break
else:
count += 1
continue
print(seven([1,1,5,0,6,1]))
The problem is that the array you are iterating over is created just once - on the beginning of iteration.
def seven(array):
for i in range(len(array)-2):
three = array[i:i+3]
if sum(three) == 7:
return True
return False
You can iterate through your array by steps of 3 using python's range method. range(0,len(array)-2,3) will go from 0 to 3 less than the total length of the array, adding three after each pass
Then, in your call to sum(), you can use array splitting to get the sum of the next 3 objects
def seven(array):
three = []
count = 0
for num in range(0,len(array)-2,3):
three.append(num)
if sum(array[num:num+3]) == 7:
return True
return False
print(seven([1,1,5,0,6,1]))

Categories