There aren't a set of instructions, but I basically have to write a code for def hasNoDuplicate and it returns True exactly when list has no duplicates. This is what I've written, I'm new to programming so all of this is very overwhelming. I don't know exactly what to put in the if statement. Any advice would help a lot!
def hasNoDuplicates(values):
foundCounterExampleYet = False
for value in values:
if():
foundCounterExampleYet = True
return not(foundCounterExampleYet)
def hasNoDuplicates(values):
foundCounterExampleYet = False
value = None
while values:
value = values.pop()
if value in values:
foundCounterExampleYet = True
break
return not(foundCounterExampleYet)
Now you get:
>>> hasNoDuplicates([1,2,3])
True
>>> hasNoDuplicates([1,2,3,4,6,7,8,9,4])
False
>>>
What this code does is, it takes the input list, and one by one takes out the last element from the list and checks if the item exists in the list. If it exists, then a duplication is detected, and it changes the value of foundCounterExampleYet and consequently jumps out of the loop. This checking happens until the list becomes empty. while values means do this while the list is not empty
The pop method takes out the last element from the list. But it has side effect, meaning it changes the value of the initial input:
>>> [1,2,3].pop()
3
>>> a = [1,2,3]
>>> a.pop()
3
>>> a
[1, 2]
You're on the right track. You can store the values in a set as you're looping through the inputs, and use the in operator to check for membership in that set. See my comments alongside the following code.
def hasNoDuplicates(values):
currentValues = set() # initialize an empty set
for value in values: # iterate over your inputs
if value in currentValues: # if the current value is in your set, there is a duplicate
return False
else:
currentValues.add(value) # no duplicate exists, add it to the set
return True # If it made it through all the values, there were no duplicates
For fun, there is an easier way to do this. If the items in the values sequence are hashable, you can make a set from the whole sequence. Since by definition a set may not have any duplicates, if the length of the original sequence is the same length as the set, then all items are unique. If the set is shorter, there was at least one duplicate.
def hasNoDuplicates(values):
return len(values) == len(set(values))
Related
Here's part of the code I'm working on in Python:
def ee(mid_circ = False):
initial_layout = [[1,0] if mid_circ == True else [1,2,3,0]]
return initial_layout
However, the output is either [[1,0]] or [[1,2,3,0]]. Is there a way I can directly obtain [1,0] or [1,2,3,0] from the code?
That's not a list comprehension. You are simply constructing a list consisting of a single item (which also happens to be a list).
You should simply remove the outer brackets, i.e.
initial_layout = [1,0] if mid_circ else [1,2,3,0]
Note that I've also dropped the redundant == True check.
Beginner question.
I have a dictionary as such:
tadas = {'tadas':{'one':True,'two':2}, 'john':{'one':True,'two':True}}
I would like to count the True values where key is 'one'. How should I modify my code?
sum(x == True for y in tadas.values() for x in y.values() )
Access only the one attribute:
sum(item['one'] for item in tadas.values())
This makes use of the fact, that True is equal to 1 and False is equal to 0.
If not every item contains the key 'one' you should use the .get method:
sum(item.get('one', 0) for item in tadas.values())
.get returns the second argument, if the dict does not contain the first argument.
If 'one' can also point to numbers, you should explictly test for is True:
sum(item.get('one', 0) is True for item in tadas.values())
If you dont want to hide the summation in the boolean, you can do it more explicitly with:
sum(1 if item.get('one', False) is True else 0 for item in tadas.values())
List can count occurrences of values, so making use of that is probably most idiomatic:
[x.get('one') for x in tadas.values()].count(True)
You can use filter to filter the list of any values where 'one' doesn't map to True. Then, just return the length of the list.
len(filter(lambda x: tadas[x]['one'], tadas))
try this:
print(sum(1 for x in tadas.values() if x['one']))
NOTE: please do not use this answer as it's definitely not as good as other answers.
What's the most pythonic way to take the single item of a 1-sized list in python?
I usually go for
item = singlet_list[0]
This would fail for an empty list, but I would like a way to make it fail even if the list is longer, something like:
assert(len(singlet_list) == 1)
item = singlet_list[0]
but I find this ugly. Is there anything better?
This blog post suggests an elegant solution I fell in love with:
(item,) = singlet_list
I find it much more readable, and plus it works with any iterable, even if it is not indexable.
EDIT: Let me dig a little more
This construct is called sequence unpacking or multiple assignment throughout the python documentation, but here I'm using a 1-sized tuple on the left of the assignment.
This has actually a behaviour that is similar to the 2-lines in the initial question: if the list/iterable singlet_list is of length 1, it will assign its only element to item. Otherways, it will fail with an appropriate ValueError (rather than an AssertionError as in the question's 2-liner):
>>> (item,) = [1]
>>> item
1
>>> (item,) = [1, 2]
ValueError: too many values to unpack
>>> (item,) = []
ValueError: need more than 0 values to unpack
As pointed out in the blog post, this has some advantages:
This will not to fail silently, as required by the original question.
It is much more readable than the [0] indexing, and it doesn't pass unobserved even in complex statements.
It works for any iterable object.
(Of course) it uses only one line, with respect to explicitly using assert
You could use an inline if...else and define a default value like this:
If singlet_list contains one or more values:
singlet_list = [2]
item = singlet_list[0] if singlet_list else False
print item
output:
2
If singlet_list is empty:
singlet_list = []
item = singlet_list[0] if singlet_list else False
print item
output:
False
This uses the fact that an empty list evaluates to False.
Similarly, if you would like a default value to be assigned if the list doesn't contain exactly one element, you could check the length:
item = singlet_list[0] if len(singlet_list) == 1 else False
I want every element in l(which is a list) to be added to a.
When I run the function, it gives me '[]' every time. How can I fix this?
def sim(l):
a = []
if len(l)>0:
a = a.append(l.pop())
l.pop()
return sim(l)
return a
Several things are wrong:
You shouldn't use lowercase L for a variable name - it looks like one
At the top of the function you assign an empty list to a - ultimately sim will be called with an empty list, then a will be assigned an empty list, the conditional statement will fail and sim will return an empty list.
Inside the conditional statement you assign the return value of list.append() to a. The return value is None so whatever a was before, it gets wiped out.
Inside the conditional statement you pop() two items out of your control list
An empty list has a boolean value of false so there is no need to explicitly check its length,
def sim(el, a = None):
if el:
a.append(el.pop())
return sim(el, a)
return a
I was taught to write the base case of a recursive function as the first statement:
def sim(el, a = None):
if not el:
return a
a.append(el.pop())
return sim(el, a)
append() doesn't return anything but does update the existing list. In other words, by trying to assign the result of the append() method, you're setting a to nothing after you have already appended the item.
Your Code :def sim(l):
a = []
when you call Function recursively return sim(l) every time it is call sim(l) and a=[] is empty.
Try This :
def sim(l,a):
if len(l)>0:
a.append(l.pop())
print a
return sim(l,a)
return a
Is this a homework assignment where you're required to do it in a certain (overly complicated) way? Because if not, you can add one list to another in Python like so:
>>> l = [1, 2, 3]
>>> a = []
>>> a.extend(l)
>>> a
[1, 2, 3]
Write a recursive function search(l,key) that returns a boolean: True if key is in the list l; False if it isn’t. Describe the base case(s) and how the smaller problem relates to the bigger one. You may not use the in operator or the index() list method.
Can anyone explain what i need to do here for the description? I dont know anything about recurrsion to know where to start. Its for a exam review lab assignment.
Here is the code i have been provided.
def search(l,key):
"""
locates key in list l. if present, returns True; else returns False.
PRE: l is a list.
POST: l is unchanged; returns True if key in l; False otherwise.
"""
Sample Main:
l1 = [1, '2', 'x', 5, -2]
print search(l1, 'x') # should output: "True"
print search(l1, 2) # should output: "False"
All recursion tends to follow the same rules:
Have one or more terminating cases.
Every other case is a slightly simpler form of the current case.
So, for example, a (very inefficient) way to add two positive numbers a and b:
if b is zero, return a.
otherwise add the two numbers a+1 and b-1.
Something like:
def addtwo (a, b):
if b == 0:
return a
return addtwo (a+1, b-1)
Now let's think about the cases for your assignment:
if the list is empty, you didn't find it: return false.
if the first element of the list is equal to your key, you found it: return true.
otherwise look in the list made by removing the first element.
In pseudo-code (which is very similar to Python but different enough that you'll have to do some work):
def search (list, key):
if list is empty:
return false
if key == first item in list:
return true
return search (list with first element removed, key)
Every question regarding recursion should be dealt with the same way (usually)...Ask yourself what is the base case and then build on that for higher cases...
So in this question, ask yourself, when can i be certain there is no key in the list...
It's obviously when the list is empty, you're certain it's not present.
For a bigger list, you compare the first element, if it's the same as the key, you return True right away, but incase it's not, you perform all the checks for the rest of the list....
So studying all these aspects,
Here's your Algorithm.
function locate(lst,key)
if lst == emptylist then return False
if lst[0] == key then return True
else return locate(lst[1..],key) //i use the notation lst[1...] to indicate list starting from 1 index.