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
Related
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.
I tried solving the question below on codingbat:
"Given an array of integers, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere".
This was my solution which returned with the error "index out of range":
def array123(nums):
for i in range(len(nums)):
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
return False
This was Codingbat's solution:
def array123(nums):
for i in range(len(nums)-2):
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
return False
I know I'm missing a trick here. Please could someone explain why I have to iterate over range(len(nums)-2)??
Thank you.
thats not exactly an amazing solution either, this would be proper:
def array123(nums):
for i in range(len(nums)-2):
if nums[i:i+3] == [1,2,3]:
return True
return False
print(array123([1,2,3]))
True
the main differences between your code and codingbat's is how the range is used
your range is the length of the list right? so since you are adding to the index by 2 at the highest case, we only should iterate until the length - 2, because anything over reaches past the highest index
They have used len(num) -2 , so that the num [i+2] points to the last element and not a index outside of the num
Thats because you are checking i th , i+1 th and i+2 th elements in the loop.
The requirement is to check 1,2,3 in the array anywhere.
and in python indices starting at zero, so range(len(num)-2) makes it to iterate over 0 to 7, if it is 10 elements array.
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
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 9 years ago.
I'm trying to write a program in which I can input a list and if all the values in the list are equal, it returns the boolean Yahtzee as True. When I run it, it works 99% of the time. However, index 3 can be different than the other values in the list and isYahtzee() will still return Yahtzee as True. Can someone help me debug this?
#Determine whether all of them are the same and returns a Boolean.
def isYahtzee(aList):
#This tells the program to look down the entire length of the list
for i in range (0,len(aList)):
#Since I will be working with a list with no more than 5 numbers, I se
#This equal to 5 indexs (0-4)
if aList[0] == aList[1] and aList[1] and aList[2] and aList[3] and aList[4]:
#If all of them are equal, the boolean Yahtzee = True
Yahtzee = True
#If they are not all equal to eachother
if aList[0] != aList[i]:
#The Boolean Yahtzee = False
Yahtzee = False
#Return the value of the Boolean
return Yahtzee
You could check to see if the list is length 5 and if the set of the list is length 1.
#Determine whether all of them are the same and returns a Boolean.
def isYahtzee(aList):
return (len(aList) == 5 and len(set(aList)) == 1)
That being said, your problem is that you're only testing for equality of aList[0] == aList[1] -- the and aList[1] and aList[2] and aList[3] and aList[4] segment only checks to make sure that the other values exist, not that they are equal to aList[0].
If you wanted to make it more strict, you could also add and all(isinstance(item, int) for item in aList) in order to check that all values are integers, and and max(aList) <= 6 and min(aList) >= 1 in order to check if all the values are valid (standard) die values.
I would take a slightly different approach, to avoid an expensive set build when you don't need one.
def isYahtzee(aList):
return all(item==aList[0] for item in aList)
This will require that two items don't test True for equivalency when they're not actually the same, but unless you're building custom classes for dice and including those (rather than the die rolls they produce) in your list, it shouldn't be an issue in this implementation.
def array_front9(nums):
end = len(nums)
if end > 4:
end = 4
for i in range(end):
if nums[i]==9:
return True
return False
I need to understand the above python code and why two return statement in 'for loop'. This is seriously confusing me.
This could be rewritten much simpler (that is, "more pythonic") as this:
def array_front9(nums):
return 9 in nums[:4]
The first half of the code is setting the loop limit to the first 4 elements, or less if the array nums is shorter. nums[:4] does essentially the same thing by creating a copy that only contains up to the first 4 elements.
The loop is checking to see if the element 9 is found in the loop. If found, it returns immediately with True. If it's never found, the loop will end and False is returned instead. This is a longhand form of the in operator, a built-in part of the language.
Let me explain:
def array_front9(nums): # Define the function "array_front9"
end = len(nums) # Get the length of "nums" and put it in the variable "end"
if end > 4: # If "end" is greater than 4...
end = 4 # ...reset "end" to 4
for i in range(end): # This iterates through each number contained in the range of "end", placing it in the variable "i"
if nums[i]==9: # If the "i" index of "nums" is 9...
return True # ...return True because we found what we were looking for
return False # If we have got here, return False because we didn't find what we were looking for
There are two return-statements in case the loop falls through (finishes) without returning True.
The second return isn't in the for loop. It provides a return value of False if the loop "falls through", when none of nums[i] equal 9 in that range.
At least, that's how you've indented it.
You could rewrite this to be more clear using list slicing:
def array_front9(nums):
sublist = nums[:4]
if 9 in sublist:
return True
else:
return False