This question already has answers here:
Does Python support short-circuiting?
(3 answers)
Closed last year.
For the following exercise I am expecting an IndexError for certain test inputs, but it is not occurring.
Goal: Write a function that takes in a list of integers and returns True if it contains 007 in order
My Function:
def spy_game(nums):
for x in range(len(nums)):
print(x)
try:
if nums[x]==0 and nums[x+1]==0 and nums[x+2]==7:
return(True)
except IndexError:
return(False)
Test Cases:
#Case 1
spy_game([1,2,4,0,0,7,5])
#Case 2
spy_game([1,0,2,4,0,5,7])
#Case 3
spy_game([1,7,2,0,4,5,0])
Question:
I included the print statement in the function to try to understand the issue. Case 1 prints 0 1 2 3 and returns True which is expected. Case 2 prints 0 1 2 3 4 5 6 and does not return anything. Case 3 prints 0 1 2 3 4 5 6 and returns False. For both Case 2 and 3 I would expect it to print up to 5 and at that point result in an IndexError. I am not sure why Case 2 reaches 6 and has no IndexError and why Case 3 reaches 6 and does have one. Thanks in advance!
The reason it is not giving you an IndexError comes from how and operations occur in the code. Case 2 will not get to the point of looking for x+2 because it fails on the other operations before.
a = [True, True, True]
if a[0] == False and a[100000] == None:
for example, will never give you an IndexError because it fails on the first if.
Related
I'm trying to solve "Bad Prices" on Codeforces. The problem asks you to find the number of integers in the array, such that there is a smaller integer after them in the array. Here's a sample test:
5
6
3 9 4 6 7 5
1
1000000
2
2 1
10
31 41 59 26 53 58 97 93 23 84
7
3 2 1 2 3 4 5
The first number is the number of test cases, the following are the testcases, consisting of the length of the array and the array itself.
Here's my code:
for _ in range(int(input())):
count=0
a=input()
x=input().split(' ')
for i in x:
for j in x[x.index(i):]:
if int(i)>int(j):
count+=1
if count%2==0:
print(int(count/2))
else:
print(int(count))
count=0
x=[]
For some reason, the code works, but only for 4 of 5 test cases, completely ignoring the last one. What did I do wrong?
for j in x[x.index(i):]:
index() function always gives you the first occurrence.
Ex: array is 2 1 3 2 4 5 6
x.index(2)=0,x.index(1)=1,x.index(3)=2,x.index(2)=0,x.index(4)=4,x.index(5)=5,
x.index(6)=6.
Though there are multiple occurrences of 2, the index() functions cosiders the first occurrence always. So,When i=2(index=3), j iterates from the index(0) to index(6) and not from index(3) to index(6).
To overcome this you can make use of variable a(length of the array) and change it like this:
for i in range(int(a)):
for j in range(i,int(a)):
if int(x[i])>int(x[j]):
count+=1
if count%2==0:
print(int(count/2))
else:
print(int(count))
These conditions are not necessary.
If you find an element that is smaller than the current element u can increase the count and break from the inner loop and continue the process for the next element.
After the count+=1, you can add a break statement.
Replace the if, else condition with a print(count) statement.
3.
Initializing the count variable with zero at the beginning of a new test case is enough, no need to do it twice. Initializing x=[] will make no difference because the existing data will be overridden when you assign new data to the variable x[]
Tim Roberts identified the issue in the comments, the problem is your use of the index method. As he suggested, using the index generated fromenumerate will allow you to avoid that issue.
Note, slices are not indices, so whereas [cur_index + 1] may be an invalid index, [cur_index + 1:] is always a valid slice even though it may be an empty one.
Example:
num_sets = int(input())
for _ in range(num_sets):
_ = input()
prices_per_day_str = input()
prices_per_day = list(map(int, prices_per_day_str.split()))
bad_price_count = 0
for cur_index, cur_price in enumerate(prices_per_day):
for future_price in prices_per_day[cur_index + 1:]:
if cur_price > future_price:
bad_price_count += 1
break
print(bad_price_count)
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
I'm doing python bats and the question 'has23' says the following:
Given an int array length 2, return True if it contains a 2 or a 3.
I have written this code so far expecting it to work as intended with the else statement but I cannot trigger the False if 2 or 3 is not found within the array.
def has23(nums):
if 2 or 3 in nums:
return True
else:
return False
You need to completely write conditions that are separated by and or or. You code was actually checking if 2 or if 3 in nums. if 2 actually checks if 2 is nonzero, which is always true.
def has23(nums):
if 2 in nums or 3 in nums:
return True
else:
return False
Writing 2 or 3 in nums actually means, in Python, (2) or (3 in nums). Which will always evaluate to True because 2 is a truthy value. What you should write instead to perform your intent here is 2 in nums or 3 in nums.
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
This question already has answers here:
How can I iterate over overlapping (current, next) pairs of values from a list?
(12 answers)
Closed 6 years ago.
if given a command like:
python 1.py ab 2 34
How to print the next argument while you are currently sitting on the one before. e.g if x is ab then I want to print 2:
import sys
for x in sys.argv[1:]:
print next element after x
I am unsure what you want to print but this syntactic sugar can help:
for x in sys.argv[1::2]:
print x
This prints every other element. So this will return ab 34
for x in sys.argv[2::2]:
print x
This will return 2
The number after the :: is how many slots in the array.
Edit:
To answer your specific question:
val = 1
for index, x in enumerate(sys.argv[1::2]):
val += 1
print sys.argv[index+val]
The index increases by 1 each time, and the val by 1 too, meaning every loop we skip 2 variables. Hence for something like python yourcode.py a 1 b 2 c 3 d 4 output will be 1 2 3 4
I was reading through the answers earning a "reversal" badge and I found a question regarding recursion where the OP didn't bother to do much of their homework assignment up front. Aside from some really funny answers, #machielo posted an answer in python that I had to run on my machine to get a grip on. I'm still not understanding it.
def recursive(x):
if x > 10:
print recursive(x/10)
return x%10
>>> recursive(2678)
2
6
7
8
I tried out my first guess, but I know it's wrong
>>> 2678/10
267
>>> 267/10
26
>>> 26/10
2
>>> 2%10
2
Okay...that's the two. How does this evaluate the output of the other numbers in x?
EDIT
It's the print statement that I don't get here. I modified the code as such:
>>> def recursive(x):
if x > 10:
print x
print recursive(x/10)
return x%10
>>> #I will comment the interpreter session here...
>>> recursive(2345)
2345 # first feed in...print the raw number `x`
234 # 2345/10 does equal 234...the 5 is being held back somewhere...
23 # and each pass through the recursive loop removes the last digit...
2 # but where was it being stored at, so that each evaluation of
3 # x > 10 finally started returning False
4 # and returns the number, exiting the function
5 # ...
I'm thinking that during each run through, the call to print recursive(x/10) creates a new function object, each with it's own brand new base case and input...
Another hint, anyone?
FINALLY
Thanks to everyone. I feel I understand this now...the trick wasn't so much print as it was x%10. 2345%10 == 5...
>>> def recursive(x):
print "Raw `x`:", x
if x > 10:
print "Recurse `x`:", x
print recursive(x/10)
print "Last `x`:", x
return x%10
>>> recursive(2345)
Raw `x`: 2345
Recurse `x`: 2345
Raw `x`: 234
Recurse `x`: 234
Raw `x`: 23
Recurse `x`: 23
Raw `x`: 2
Last `x`: 2
2
Last `x`: 23
3
Last `x`: 234
4
Last `x`: 2345
5
Also, credit to whoever went in and updated the initial answer that I previously linked to...I'm about to upvote your comment:
>>> def recursive(x):
if x >= 10:
print recursive(x/10)
return x%10
I think that adding a few print statements it's really helpful:
def recursive(x):
print '[start] recursive({0})'.format(x)
if x > 10:
print recursive(x/10)
print '[return] recursive({0}) = {1}'.format(x, x%10)
return x%10
print recursive(2678)
The output is:
[start] recursive(2678)
[start] recursive(267)
[start] recursive(26)
[start] recursive(2)
[return] recursive(2) = 2
2
[return] recursive(26) = 6
6
[return] recursive(267) = 7
7
[return] recursive(2678) = 8
8
Stepping through your example in pseudocode (number of dashes indicates recursion depth):
-call recursive(2678)
--2678 > 10, call recursive(267)
---267 > 10, call recursive(26)
----26 > 10, call recursive(2)
-----return 2%10 (which is 2)
----print 2, then return 26 % 10 (which is 6)
---print 6, then return 267 % 10 (which is 7)
--print 7, then return 2678 % 10 (which is 8)
-return 8
This function prints out the digits of the number.
It works like this:
def recursive(x):
if x > 10:
# Divide x by 10 and round down. This chops off the last decimal place.
# Now feed that new x without the last decimal place back into recursive()
# return x's last digit
Basically, it won't print anything until x is a single digit number.
The part you're confused about is probably why it's printing out each decimal place in that order. This happens because while the function recurses, the parent function is still running.
Just try and expand the code for that single number.
Edit: I'm confusing myself as well.
Your code calls print before return, which means that when the last level of recursion finishes, the second-to-last prints out the first digit. The same goes for the next layers.
Keep in mind the call stack when considering recursion. The recursive call is pushing all recursive() function calls onto the stack before anything is printed so what you end up with on the stack is
recursive(2) # end condition is met so returns 2%10
recursive(26)
recursive(267)
recursive(2678) # the initial call
once the end condition is reached 2%10 (2) is returned to the previous function's print statement and printed, then that function returns 26%10 (6), and this continues until all the recursive function calls on the stack have returned. The result is this series of print calls:
print 2
print 6
print 7
8
8 is not actually printed; it is just returned which is fine from the interpreter. If you wanted to be sure that it printed in for example a python script you would call print recursive(2678)