I have a question which is asking to compare 2 numbers in a list, specifically if the adjacent numbers are positive or negatives
However I am stuck on the first part of the question. My idea is to compare the first number using its index with the second number so i+1, but inevitably is goes out of range.
I am missing something here, help is appreciated.
my_list=[-1,2,-3,-4,-5,1,2]
for i in range(len(my_list)):
print (my_list[i])
print (my_list[i+1])
I have been working on it and this is the full questions
Given a sequence of numbers, find and print the first pair of adjacent elements which have the same sign. If there is no such pair, print NONE.
I'm not allowed to use zip in this case.
However I cannot do the last bit where it ask pro print none if no pairs are there
s = input()
my_list_str = s.split()
my_list = []
for beta in my_list_str:
my_list.append(int(beta))
for i in range(len(my_list)-1):
if my_list[i]>0 and my_list[i+1] >0:
print (my_list[i], end =' ')
print (my_list[i+1])
break
elif my_list[i]<0 and my_list[i+1] <0:
print (my_list[i], end =' ')
print (my_list[i+1])
break
Two points:
Most of the time it is considered "unpythonic" to use indices to iterate over a list
The for-loop has the option to close with an else-condition: The code in the else condition is only executed if the for-loop isn't left via a break
So, you could try the following:
for first, second in zip(my_list[:-1], my_list[1:]):
if (first < 0 and second < 0) or (first > 0 and second > 0):
print(first, second)
break
else:
print("NONE")
EDIT: If you need to use indices, then you could do:
for i in range(len(my_list) - 1):
first, second = my_list[i], my_list[i+1]
if (first < 0 and second < 0) or (first > 0 and second > 0):
print(first, second)
break
else:
print("NONE")
If you are not allowed to use the else-option of the for-loop, then you could try:
found = False
for i in range(len(my_list) - 1):
first, second = my_list[i], my_list[i+1]
if (first < 0 and second < 0) or (first > 0 and second > 0):
print(first, second)
found = True
break
if not found:
print("NONE")
Because you want to print (my_list[i+1])
Your list size is 7 -> when i = 6 -> [i+1] = 7
=> my_list[7] <- out of range
You can do it like below:
my_list=[-1,2,-3,-4,-5,1,2]
list_len = len(my_list)
for i in range(list_len-1):
print(f'comparison {i+1}')
print (my_list[i])
print (my_list[i+1])
my_list=[-1,2,-3,-4,-5,1,2]
list_len = len(my_list)
x = 7 # any positive number
for i in range(x):
if i < list_len:
print (my_list[i])
if i+1 < list_len:
print (my_list[i+1])
Related
I have the following exercise.
Neighbours of same sign
Given a sequence of numbers, find and print the first adjacent elements which have the same sign. If there is no such pair, print NONE.
Please note that the output must be the same as indicated in the example.
Example
Input:
-1 2 -3 -4 -5 1 2
Output:
-3 -4
this is my code, but it does not work when I try to catch the case when the pairs are not the same sign, can someone help?
The code works fine, but when i add the ELSE things break down.
s = input()
my_list_str = s.split()
my_list = []
for beta in my_list_str:
my_list.append(int(beta))
for i in range(len(my_list)-1):
if my_list[i]>0 and my_list[i+1] >0:
print (my_list[i], end =' ')
print (my_list[i+1])
break
elif my_list[i]<0 and my_list[i+1] <0:
print (my_list[i], end =' ')
print (my_list[i+1])
break
else:
print ('NONE')
just add a found flag
s = input()
my_list_str = s.split()
my_list = []
for beta in my_list_str:
my_list.append(int(beta))
found=False
for i in range(len(my_list)-1):
if my_list[i]>0 and my_list[i+1] >0:
print (my_list[i], end =' ')
print (my_list[i+1])
found=True
break
elif my_list[i]<0 and my_list[i+1] <0:
print (my_list[i], end =' ')
print (my_list[i+1])
found=True
break
if not found:
print ('NONE')
you should check the else part once
I would suggest keeping track of the sign of the previous and current numbers and a found flag. For example like this:
list = [-1, 2, -3, 4, -5, 1]
prev_sign = -1
found = 0
for i in range(len(list)):
this_sign = list[i] < 0
if this_sign == prev_sign:
print("{} {}".format(list[i - 1], list[i]))
found = 1
break
prev_sign = this_sign
if not found:
print("NONE")
Or even more concise, the for loop could look like this:
for i in range(1, len(list)):
if (list[i] < 0) == (list[i - 1] < 0):
print("{} {}".format(list[i - 1], list[i]))
found = 1
break
One error I see with the code is the placement of the else statement inside the for-loop. In the existing code, if the first two elements have mismatched sign, then it will immediately print 'NONE' because it reaches that else statement, and will continue printing 'NONE' until it does find matching neighbors. I would rewrite your for-loop as follows:
found_pair = False
for i in range(len(my_list)-1):
if my_list[i] * my_list[i+1] > 0: # matching sign
found_pair = (my_list[i], my_list[i+1])
break
if found_pair:
print(found_pair[0], found_pair[1])
else:
print('NONE')
In the above code, the result must necessarily only print once after it's already finished the for-loop. If a pair is found, it is stored and we break, otherwise we exhaust the loop without ever assigning found_pair, leading 'NONE' to be printed only once at the end. Let me know if this doesn't work or if you have any questions!
David
Lots of suggestions for a found flag, but you don't need one. This is where the else on a for loop comes in:
lst = [-1, 2, -3, 4, -5, 1]
# zip lst with a slice of itself to get corresponding
# elements offset by 1 position
for a, b in zip(lst, lst[1:]):
if a * b > 0:
print(f"Found pair {a} {b}")
break
else:
print("NONE")
The else will only trigger if the for loop completes (isn't ended early by break)
This question already has answers here:
Find max with negative numbers
(3 answers)
Closed 12 months ago.
def second_largest(numbers):
first = 0
second = 0
for n in numbers:
if n > first:
first, second = n, first
elif first > n > second:
second = n
return second or None
print(second_largest([2,2,2,-2]))
When i run this code, output is None, but i need it to be -2 and also i cant use functions as .sorted and others for array. I think that problem is in second = 0 ,but i dont know how to fix it.
Here's a few issues I see.
You are instantiating first and second incorrectly (what if the largest number is negative)?
The only time you'd want to return None is if your list size is smaller than 2.
Change your return condition to return second.
def second_largest(numbers):
if len(numbers) < 2:
return None
first, second = numbers[0], numbers[1]
if first < second:
first, second = second, first
for n in numbers[2:]:
if n > first:
first, second = n, first
elif n > second:
second = n
return second
Not sure if this is what you're looking for, but you can basically take the largest element out of the list (or make a note of it) and then search for the second-largest element in what's left. Here, I do this by first using max() (a built-in function of python that works on any iterable object) to get the largest element of the list, then using a list comprehension to create a second list of elements that do not equal that largest element, and finally using max() again to get the second-largest element from the original list.
def second_largest(numbers):
first = max(numbers)
second = max([i for i in numbers if i != first])
return second
You could use a for loop for this if you didn't want to use max() for some reason.
The code you provided does not handle cases where n == first. Changing elif first > n > second to elif n > second should be sufficient (you do not need to test if first >= n since if control can reach that line n > first must be false).
Not use sorted?
values = [2,2,2,-2]
values.sort(reverse=True) # technically correct
second_largest = values[1]
or, less facetious
values = set([2,2,2,-2])
values.remove(max(values))
second_largest = max(values)
Or even
import heapq
heapq.nlargest(2, [2,2,2,-2])
def second_largest(numbers):
if len(numbers) < 2:
return "less than 2 numbers"
temp1,temp2 = numbers[0], numbers[1]
if temp1 < temp2:
temp1, temp2 = temp2, temp1
for i in range(len(numbers)):
if numbers[i] > temp2:
if numbers[i] > temp1:
temp2 = temp1
temp1 = numbers[i]
else:
temp2 = numbers[i]
else:
if(temp1==temp2):
temp2 = numbers[i]
return temp2
I am learning python, one the the question I have is how can check if variable x is equal to array[i]. I am trying to use divide and conquer to find element in array
x = 12
arr = [12,31,33]
middle = len(arr)//2
print ("Find",x)
print ("Middle ", arr[middle])
print ("Middle Left",arr[middle] +1)
print ("Middle Right", arr[middle] -1)
if x == arr[middle]:
print ("found it")
elif x == arr[middle] - 1 :
print ("found on left")
elif x == arr[middle] + 1:
print ("found on right")
else:
print("Not found")
if you want to find element at left/right based on index, you need to minus/add on index.
x = 12
arr = [12,31,33]
middle = len(arr)//2
print ("Find",x)
print ("Middle ", arr[middle])
print ("Middle Left",arr[middle + 1] )
print ("Middle Right", arr[middle -1])
if x == arr[middle]:
print ("found it")
elif x == arr[middle - 1] :
print ("found on left")
elif x == arr[middle + 1]:
print ("found on right")
else:
Unless your problem specifically says that you must use divide and conquer to do this, you could just use .index(x) to get its index - i.
So for your example:
x = 12
arr = [12,31,33]
then:
arr.index(x)
gives 0 for i (the index). This is much neater and unless you have a massive list, will be perfectly fast enough.
If it turns out you must write your own divide and conquer for this, then the place you are going wrong is when indexing from arr with arr[middle] and then adding and subtracting from that value. What you want to do instead, is index one further or one before with arr[middle - 1] or arr[middle + 1].
Hopefully you can implement these changes to your code yourself if you don't want to use the much easier .index().
How about creating a function like this?
arr = [12,31,33,31]
def position(array,key):
# find all entries
positions = [ind for ind,i in enumerate(array) if i==key]
# return No match if nothing is found
if not positions:
return "No match!"
# set mid to middle of array
mid = len(arr) / 2
# loop through all found elements and print
for i in positions:
if i < mid:
where = "left"
elif i > mid:
where = "right"
else:
where = "mid"
print("found {} on {}".format(key,where))
print(position(arr,31)) # 'found 31 on left \n found 31 on right'
print(position(arr,19)) # 'No match!'
I have a long list of numbers and I want to compare them all to 0 at the same time and if they are greater, to print out along with another long list. my problem is, I don't know how to do that and I don't want to spend all night typing the same couple lines of code 90 times. This is what I have:
if nums[n]>0:
print(nums[n]'='templist[n])
else:
print('')
and this is what I want it to say:
if nums[1-90]>0:
print(nums[1-90]'='templist[1-90])
else:
print('')
you can use a for loop with a range to go through index 1 - 90 (this will miss index 0):
for i in range(1, 91):
if nums[i] > 0:
print(str(nums[i]) + '=' + str(templist[i]))
else:
print('')
if you want to go through every item in the list, you can use enumerate which give you each item and its index:
for (i, v) in enumerate(nums):
if v > 0:
print(str(v) + '=' + str(templist[i]))
else:
print('')
add = lambda x,y : x+y
list1 = [1,2,3,4,5]
count = 0
for num1 in list1:
if count > len(list1):
break
else:
print(add(num1,list1[count+1]))
count += 1
In the code above, why is the for loop not breaking as it exceeds the condition?
In fact you do not need the break statement (nor lambda expression). You may write you code as:
list1 = [1,2,3,4,5]
for i in range(len(list1)-1):
print list1[i] + list1[i+1]
Even better to use zip here:
for a, b in zip(list1, list[1:]):
print a+b
The for loop executes once per element in list1, so count will never be bigger than the length of that list.
I've you want to stay with tihs code, change the if statement:
if count >= len(list1) - 1:
and it will break before running out of the bounds of the list in
print(add(num1,list1[count+1]))
The error is on this line:
print(add(num1,list1[count+1]))
When you use count + 1 you're falling into an index out of range.
To keep your logic, you should use count + 1 >= len(list1)
for num1 in list1:
if count + 1 >= len(list1):
break
else:
print(add(num1,list1[count + 1]))
count += 1