I have a list of numbers, say list= [0,1,0,1,0]. I have to check for each element i in list whether its equal to its previous and the element after it and if it is, change its value to the previous one. I presented this task as:
i-1=x
i+1=y
for i in list:
if x=y and i!=x
i=x
elif x!=y
i=i
But I need to connect the first and the last element in list, so that if i=list[0]: x=list[4] (and y=list[2]). My idea was to define another loop like this:
if i=list[0]
x=list[4]
But when i execute the program it writes that x=list[0] is "syntax error: invalid syntax". First, I am not quite sure why is this: I was thinking that I didn't define x (but I did!), or I maybe didn't define it in the right place (I am not sure where I should define it then). On the other hand, is this the way to connect last and first value of list?
Here is a code that does exactly what you asked.
test=[0,1,0,1,0] # don't use 'list' as variable name
for j in range(len(test)): # j=index of current
i = (j-1) % len(test) # i=index of previous
k = (j+1) % len(test) # k = index of next
if test[i] == test[k]: # equal to previous and next
test[j] = test[i] # change to previous
print(test)
Try this:
i-1=x
i+1=y
for i in list:
if x==y and i!=x :
i=x
elif x!=y
i=i
= means assignment whereas == means equality test. And the colon : in python defines the beginning of a scope (indented) so you need :' after anif` to define its scope block.
Related
I have a question about the below code, particularly the 6th line; is it right to say that it is returning the index of target-nums[I]? If so, why is there another I after it?
Also, what is comp[nums[I]] = I doing? Is it assigning values of nums into comp if it is not in comp already?
Finally, what is the final return [ ] doing in the last line of code?
def TwoSum(nums, target):
comp = {}
for i in range(len(nums)):
if (target - nums[i]) in comp:
return [comp[target - nums[i]],i]
comp[nums[i]] = i
return []
print(TwoSum(nums,target))
is it right to say that it is returning the index of target-nums[I]?
If so, why is there another 'I' after it?
It is returning a list of two items, the first item being comp[target - nums[i]], and the second item being i. It's the same idea as:
def addAndSubtract(x, y):
return [x+y, x-y]
Above, we return a list, the first item in the list is the value of evaluating x+y and the second value is the result of evaluating x-y.
Also, what is comp[nums[I]] = I doing? Is it assigning values of nums into comp > if it is not in comp already?
This will assign the value of nums[i] as a key in your comp dictionary and assign it the value of i. It essentially stores the current value in nums and along with its index. This does two things:
Allows you to easily and quickly check if you have seen a given number yet by checking if it is a key in your comp dictionary
Allows you to check where that number was last seen in your list.
The comp[nums[i]] = i occurs each time your for loop runs, so it will do it for all numbers, in your list, unless it returns in your if-statement. If you happen to encounter the same number again (which is already in your list), then this assignment will simply overwrite the value with the current index of the current number (ie: i).
Finally, what is the final return [ ] doing in the last line of code?
The purpose of this is to return an empty list. It is just a way to signify that no result was found. You will only reach that return when you have iterated through all the numbers in your list and not returned from within your for loop, thus indicating no sum can be made to reach the target.
I explain how this algorithm works in detail here, so you might want to check that out if you need more of an explanation. Although the question is a JavaScript question, the logic explained is the exact same as this.
Make a function that receives a string containing only digits and may also be an empty string, which returns an integer value which is the maximum of all the digits that are in the EVEN POSITIONS of the original string.
If the empty string, the function should return -1.
For example:
max_even_pos("123454321") returns 5, because 5 is the maximum of 1,3,5,3,1, which are the digits in the original string in even positions.
# My code
def max_even_pos(st):
if not st:
return -1 ### This line satisfies the empty list condition
for i in range(len(st)): ### Problem I have. Trying to find
## the max integer from even positions
num_list = [i] # assigns elements to the list
if i%2 == 0: # checks if elements are even
return max(num_list) # result
My only problem is trying to get the code to find the greatest integer in the even position of the original string. I think "num_list = [i]" causes the error, but I am unsure how to change this so it executes properly.
As of right now, it outputs 0 for all cases
Your current code ensures that num_list has no more than a single element. When you hit the first even index, 0, you stop and return that index, without regard to the input value. You have several errors to correct:
Put the return after the loop. You have to get through all of the input before you can return the required value.
Accumulate the values with append. Your current code keeps only the last one.
Accumulate the input values; i is the position, not the value. I believe that you want st[i]
Also look into better ways to iterate through a list. Look at for loops or list slicing with a step of 2. If you are ready for another level of learning, look up list comprehension; you can reduce this function to a one-line return.
#Prune is correct. Maybe comparing the lines below to your original will help you for next time....
test_string = "123454321"
def max_even_pos(st):
num_list = []
if not st:
return -1
for i in range(len(st)):
if i%2 == 0:
num_list.append(st[i])
return max(num_list)
print(max_even_pos(test_string))
I want to use this function to find duplicate items in my list, but this code is not working:
p = "enter a list\n"
t = raw_input(p)
def has_duplicate(t):
o = sorted(t)
i = 0
while i < len(o):
if o[i] == o[i + 1]:
print "the list has duplicates"
elif o[i] != o[i+1]:
i += 1
if i >= len(o):
print "the list has no duplicate"
It gives me an error saying has_duplicates not defined.
As #mgilson commented, your issue is you are calling the function incorrectly (has_duplicates vs has_duplicate) however...
The most straight forward way to do this is using a set and comparing len.
def has_duplicates(t):
return len(set(t)) != len(t)
If you take an iterable and wrap it in a set you will end up with only unique items. If the length of the set is the same as your original iterable then you have no duplicates. If the length is different (will always be equal to or smaller) then you have duplicates which were removed when converting to a set type.
First thing is you do list_name.sort().
Other easy way to find duplicates is
len(your_list)!=len(set(your_list))
you might be calling function has_duplicates but you have defined has_duplicate function.
try to call has_duplicate
For some reason the same method is working for one function and not the other. The function that works already is defined as the following:
def is_unique1(lst):
for item in lst:
current_index = lst.index(item)
if lst[current_index] in lst[current_index + 1:-1]:
return False
return True
You pass in a list and checks the uniqueness of it, if it is unique then return TRUE if not return FALSE. However I am then asked to create another function, except this time copy the list and sort it. Then iterate over every index for values in the list to check whether the value at that index is equal to the value at the next higher index. But it keeps returning TRUE no matter what input. The function looks like this:
def is_unique2 ( myList ):
list_copy = list(myList)
list_copy.sort()
print(list_copy)
for item in list_copy:
index = list_copy.index(item)
if list_copy[index] in list_copy[index + 1: -1]:
return False
return True
Why is this happening. Am I using the slice incorrectly. I am checking if the current value at list_copy[index] is in the index + 1. I am testing it like so:
print('\nTesting is_unique2')
print (is_unique2(['raisin', 'apricot', 'celery', 'carrot']) )
print (is_unique2(['raisin', 'apricot', 'raisin', 'carrot']) )
Your bug is that by checking if list_copy[index] in list_copy[index + 1: -1] you're not checking the very last item in the list.
Remember, in Python, it's always "upper bound excluded": so somelist[a:b] will span somelist[a] included to somelist[b] excluded... for any a and b.
Easy fix: use in list_copy[index + 1:]. IOW, give no upper bound for the slice, so the slice will run all the way to the end of the list.
Incidentally, your approach is very dubious if the list's items are hashable -- in which case,
def is_unique3(myList):
return len(myList) == len(set(myList))
will be much faster and much less bug-prone too:-)
Try this line instead of your -1 indexed list for unique1:
lst[current_index] in lst[current_index + 1:None:-1]:
The input (list) would be a list similar to [[1,2],[5,6],[4,6]]. I am trying to add the whole row together to test if it is even or odd.
def evenrow(list):
for row in list:
for item in row:
newNums+=item
n=sum(newNums)
print(n)
First of all do not use 'list' as variable name. Second you calling sum for int value not for a list and that's why you getting error. Check your code please.
Not sure but your code can looks like:
def evenrow(list):
for row in list:
value = sum(row)
if values is even: # put your condition here
# do something
else:
print "Value is odd"
Just an alternate method:
def evenrow(lst):
return sum(map(sum,lst))%2 == 0 #True if even, False otherwise.
This works this way:
The outer sum adds up all items of the map, which applies sum to each item in lst. In python2, map returns a list object, while in python3, it returns a map object. This is passed to the outer sum function, which adds up all items in your map.
def evenrow(lst):
return sum(itertools.chain(*a)) % 2 == 0
This expands all the items in a (each of the sublists), and chains them together, as a chain object. It then adds together all the items and determines if the sum is even.
You don't need the following line of code: n=sum(newNums). You already summed up all the items of row in the newNums += item line. Second, you have to declare newNums before using it in your code. So, the fixed version of code will look like this:
def evenrow(list):
for row in list:
newNums = 0
for item in row:
newNums += item
print(newNums)
BTW: You should consider accepting answers to some of your previous questions, otherwise nobody will spend their time to answer your new questions.