I was working on this particular task given by CodeSignal which had the purpose of creating a program that would go through a given list with numbers and check if the numbers were increasing and/or "almost increasing". What this means is that, for example, if the list was (1, 3, 2, 1) then the program should return false due to the fact that, while it does appear to increase, it also takes a dip back to 1, returning false. Getting true on the output would require the list incrementing up normally, or almost incrementing up like (1, 3, 2, 4).
I created a code for this through research and Youtube videos, and I actually understood how the code worked and tried it out on Python, however only getting 12/19 correct. I did think this code would go through and ace all the 19 tests but it turns out it had an issue within it and would like to know how I could fix this. The code:
def almostIncreasingSequence(sequence):
count = 0
for i in range(0, len(sequence)-1):
if sequence[i] <= sequence[i-1]:
count +=1
if sequence[i] <= sequence[i-2] and sequence[i+1] <= sequence[i-1]:
return False
return count <= 1
The outputs:
I have tried to give the best solution possible with me but unfortunately ended up with time limit exceeded for last 4 test cases.
Explanation
each time I tried with excepting one element from an array and checked if it is in sorted order or not and thus i continued it until last if i did not found any such possible arrays i returned false
def solution(sequence):
if sorted(set(sequence)) == sequence :
return True
for i in range(len(sequence)):
temp = sequence[:i]+sequence[i+1:]
if sorted(set(temp)) == temp :
return True
return False
def isIncreasing(sequence):
return sorted(set(sequence)) == sequence
def isAlmostIncreasing(sequence):
#(optional)
#if isIncreasing(sequence) :
# return True
for i in range(len(sequence) - 1):
if sequence[i] >= sequence[i+1]:
temp, temp2 = sequence[:], sequence[:]
del temp[i]
del temp2[i+1]
return isIncreasing(temp) or isIncreasing(temp2)
return True
First, if sequence is already IncreasingSequence then no need to check individual data.(optional)
but if it's not:
find first wrong pair at index i & i+1. (if no wrong pair found, then sequence has no issue.)
if we remove one of them, check will we get proper result in remaining sequence?
Related
I am writing a function to take a list of integers and an integer called target and return the indices of the two numbers in the list such that they add up to target. But my code doesn't work the way it should. The function ends up not printing anything at all. How can I fix this? I am a beginner and I can't figure out what's wrong :(
def solution(list, target):
firstindex = 0
secondindex = -1
while(firstindex <= len(list)-1):
if list[firstindex] + list[secondindex] == target:
print(f"The sum was found at index {firstindex} and {secondindex}")
break
else:
firstindex = firstindex + 1
secondindex = secondindex - 1
#I am calling the function here
solution([1,2,3,4,5, 6], 5)
You can use this way to solve the problem.
def solution(list, target):
n = len(list)
for firstindex in range(n - 1):
for secondindex in range(firstindex + 1, n):
if list[firstindex] + list[secondindex] == target:
print(f"The sum was found at index {firstindex} and {secondindex}")
solution([1,2,3,4,5, 6], 5)
Not so sure about the approach in general to the task you are trying to solve, depending on the algorithm you implement and the starting parameters you may receive multiple results and not one single value.
Looking at your example list and target value, the pairs (1,4) (2,3) would both solve for the target value.
In principle, in case you're not using any IDE that keeps track of the variable values or don't want to use any library to keep things very lightweight, I'd recommend to use pen and paper and walk through the variable values of your loop or have printouts in the code itself as a simple means to debug, like this:
def solution(list, target):
firstindex = 0
secondindex = -1
while(firstindex <= len(list)-1):
print(firstindex)
print(secondindex)
if list[firstindex] + list[secondindex] == target:
print(f"The sum was found at index {firstindex} and {secondindex}")
break
else:
firstindex = firstindex + 1
secondindex = secondindex - 1
#I am calling the function here
solution([1,2,3,4,5, 6], 5)
What you will find is that your second index starting at -1 will decrement simultaneously to the first index, while it does not stay fixed while iterating through the first index. Hope that helps a bit in the debugging.
Really, try to solve this question algorithmically on paper first.
Cheers,
Let me know how it goes
Edit: I utterly messed up my thinking, as Python does indeed use negative indices for starting with the last item of the list and walking back. Need to stop thinking C...
Don't use list as the variable name for the first list the function is taking, it is a keyword in python.
edit:
you are refering to the keyword list in your function which represents a type object in python. You are basically referring to the classification of the object. Instead assign your variable to another name such as def solution(original, target):
You are given an array of integers. You should find the sum of the integers with even indexes (0th, 2nd, 4th...). Then multiply this summed number and the final element of the array together. Don't forget that the first element has an index of 0.
For an empty array, the result will always be 0 (zero).
Input: A list of integers.
Output: The number as an integer.
Precondition: 0 ≤ len(array) ≤ 20
all(isinstance(x, int) for x in array)
all(-100 < x < 100 for x in array
result = 0
if array:
for element in array:
i = array.index(element)
if i%2 == 0:
result += element
else:
pass
else:
return 0
return result
Last_digit = array[-1]
final_result = result*Last_digit
return final_result
print(final_result)```
I've figured out the problem, that you've shared the array you're having problem with. Since you have this array :
[-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]
If you notice here, 84 appears twice, first at index 9 and then 16. The method you're using to get index of elements, .index returns the index of the first instance the element is found in the list.Therefore for the value of 84, the index is taken as 9 and not 16 which is an odd value, this does not add 84 to your sum. You should rather use enumerate for your code:
for idx, element in enumerate(array):
if idx %2 == 0:
result += element
First, I recommend reading the stackexchange guides on posting a well-formed question. You need to state what your goal is, what you've tried, what errors get thrown, and what the output should look like -- along with code examples and a minimal reproducible example as needed.
However, I'll help you out anyway.
You have a dangling return at line 11:
else:
return 0
return result
This makes no sense, as you've already returned 0. This is also apparently a snippet from a function, no? Post the whole function. But based on the instructions, you could try this:
import random
array = random.sample(range(-100, 100), 20)
def etl_func(arr):
arrsum = 0
for i, val in enumerate(arr):
if i%2 == 0: arrsum += val
return (arrsum * arr[-1])
answer = etl_func(array)
print(answer)
Note that importing random and using array = random.sample(range(-100, 100), 20) are not necessary if you're already GIVEN an array to work with. They're included here just as an example.
Also note that it's unnecessary to use an else: pass. If the condition evaluates to true (i.e. i%2 == 0), the if block will be executed. If i%2 != 0, the loop will short circuit automatically and move to the next iteration. Adding else: pass is like telling someone sitting in your chair to sit in your chair. You're telling the program to do what it's already going to do anyway. There's nothing necessarily wrong with including the else: pass, if it really want to... but it's just adding lines of meaningless code, which nobody wants to deal with.
EDIT: I don't know whether you were supposed to write a function or just some code (back to the "ask a well-formed question" issue...), so I went with a function. It should be trivial to turn the function into just plain code -- but you want to get into the habit of writing good functions for reusability and modularity. Makes everything run more smoothly and elegantly, and makes troubleshooting much easier.
This function also works for the array mentioned in the comments to your original post.
In addition, if you need a direct replacement for your code (rather than a function... I'm not familiar with checkio or how your answers are supposed to be formatted), and you already have the array of integers stored in the variable array, try this:
arrsum = 0
for i, val in enumerate(array):
if i%2 == 0: arrsum += val
print(arrsum * array[-1])
Since your question didn't say anything about using or defining functions, return statements shouldn't appear anywhere. There's nothing to return unless you're writing a function.
My function gives the error ("IndexError: list index out of range"), and I'm not to sure why, even first putting i = 0. My code is to print the index of the first element that is equal to the target value and if it doesn't equal anything in the list then index = -1. (Using While loop)
Function
def yareyare(list_g, list_size, target):
found = False
i = 0
while i < list_size or not found:
if target == list_g[i]:
found = True
result = i
else:
i += 1
if not found:
result = -1
print("The index is {}".format(result))
Main
# Imports
from index import yareyare
# Inputs
list_g = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list_size = len(list_g)
target = str(input("What is the target value(1-10): "))
#
yareyare(list_g, list_size, target)
There are two simple errors in the code.
First, the boolean logic of the while loop should be and not or because it allows it to loop forever since found doesn't become True until the target is found.
Second, you need to convert target to an int not an str
It should work after that.
while i < list_size or not found: is the culprit. As long as found is false, the loop continues even if it ran out of list entries. That said, the entire code seems very clumsy; a Python approach would normally use list.index, or for more verbosity, a for loop with enumerate and an else clause.
There are several problems with this code. I am going to try and fix your errors while changing as little of your original code as possible. There are some things that you are doing that will work that I would advise against, like passing the list length as a parameter rather than using len and using a while loop for this at all.
Your first issue is that target is a string while the goals you compare it to are ints. That means this:
target == list_g[i]
Will never be true. It must be changed to:
int(target) == list_g[i]
Your second problem is that you are looping while i < list_size OR found is false. When you find a match, you set found to false but you never increment i. This means that i will always stay at the same value and therefore it will always equal list_g[i] so you will never increment it. Since i is always less than the list length i < list_size or not found will always be true and you will be trapped in an infinite loop. You should change the or to an and.
Here is your function with the fixes:
def yareyare(list_g, list_size, target):
found = False
i = 0
while i < list_size and not found:
if int(target) == list_g[i]:
found = True
result = i
else:
i += 1
if not found:
result = -1
print("The index is {}".format(result))
I was making a poker simulator and tried to define a function which would identify a straight and give it a handstrength value of 5.
def straightCheck(playerHand):
playerHand.sort()
print(playerHand)
for playerHand in range(len(playerHand)):
for i in playerHand:
if playerHand[i] == playerHand [i+1] -1:
straight = True
else:
straight = False
if straight == True:
handstrength = 5
x = [1,3,5,4,2]
straightCheck(x)
i can't figure out what is wrong with is but it keeps returning this error message:
for i in playerHand:
TypeError: 'int' object is not iterable
First of all you are trying to iterate of an integer, which cannot (and shouldn't) be done. It seems like your two nested for loops should just be one for, like for i in range(len(playerHand) - 1), when the -1 is used so that you don't try to accessplayerHand[len(playerHand)].
In addition, since you set straight to True or False in every iteration, only your last iteration will count, so you'll get false positives.
Finally, I'm not sure whether you want your function to return a value, but currently your function returns no data (unless handstrength is a global variable). Also, please note that currently, by using .sort() you are actually sorting playerHand, thus changing it from within the function - this might not be what you want.
A possible function to check whether a hand is straight, similar to your code, is this:
def is_straight(playerHand):
playerHand.sort()
for i in range(len(playerHand) - 1):
if playerHand[i] != playerHand [i+1] - 1:
return False
return True
This function returns True if playerHand is straight, and False otherwise.
What about this. You sort the list, then convert it to a set and back to a list, which makes it unique. Then the length must be 5 and if so, the difference between max and min for 5 consecutive numbers must be 4. I can't mathematically prove this here, but it should be. ;)
>>> x=[2,1,5,3,4]
>>> y=sorted(x)
>>> y=list(set(y))
>>> if len(y) == 5 and y[4]-y[0] == 4:
... print "straight"
...
straight
Also see this here: Check for consecutive numbers
My task is to create a recursive function in Python that takes a list and a value of 0 as its inputs and then adds up all of the odd numbers on the list and returns that value. Below is the code that I have and it keeps returning that the list index is out of range. No matter what I do I can not get it to work.
def addodds2(x,y):
total=0
a=x[y]
while y<len(x):
if a%2!=0:
total+=a
return(addodds2(x,y+1))
else:
return(addodds2(x,y+1))
return(total)
print(addodds2([3,2,4,7,2,4,1,3,2],0))
Since you are trying to solve this recursively, I don't think you want that while loop.
When you are trying to solve a problem recursively, you need two parts: you need a part that does some of the work, and you need a part that handles reaching the end of the work. This is the "basis case".
Often when solving problems like this, if you have a zero-length list you hit the basis case immediately. What should be the result for a zero-length list? I'd say 0.
So, here's the basic outline of a function to add together all the numbers in a list:
Check the length, and if you are already at the end or after the end, return 0. Otherwise, return the current item added to a recursive call (with the index value incremented).
Get that working, and then modify it so it only adds the odd values.
P.S. This seems like homework, so I didn't want to just give you the code. It's easier to remember this stuff if you actually figure it out yourself. Good luck!
Your code should be (the comments explain my corrections):
def addodds2(x,y):
total=0
if y<len(x): #you don't need a while there
a=x[y] #you have to do this operation if y<len(x), otherwise you would get the index error you are getting
if a%2!=0:
total+=a
return total+addodds2(x,y+1) #you have to sum the current total to the result returned by the addodds2() function (otherwise you would got 0 as the final result)
return total
print(addodds2([3,2,4,7,2,4,1,3,2],0))
while y<len(x)
So the last y which is smaller than len(x) is y = len(x) - 1, so it’s the very last item of the list.
addodds2(x,y+1)
Then you try to access the element after that item, which does not exist, so you get the IndexError.
This code can be very short and elegant:
def add_odds(lst, i=0):
try:
return (lst[i] if lst[i] % 2 == 0 else 0) + add_odds(lst, i+1)
except IndexError:
return 0
Note that, in a truly functional style, you wouldn't keep track of an index either. In Python, it would be rather inefficient, though, but recursion isn't recommended in Python anyway.
def add_odds2(lst):
try:
return (lst[-1] if lst[-1] % 2 == 0 else 0) + add_odds2(lst[:-1])
except IndexError:
return 0
To make it work with any kind of sequence, you can do the following:
def add_odds3(it):
it = iter(it)
try:
value = next(it)
return (value if value % 2 == 0 else 0) + add_odds3(it)
except StopIteration:
return 0
It's much more efficient, though there's not much sense in using an iterator recursively...
I realize that little of this is relevant for your (educational) purposes, but I just wanted to show (all of) you some nice Python. :)