creating a list using a function from an undefined list - python

I'm asked to create a list of numbers that stops when the number 7 appears.
I've tried the following, but get a runtime error:
def sublist(x):
s = []
while x != 7:
s.append(x)
return s
Any ideas?

If you're getting a runtime error, you probably cannot compare the type of x to 7. Try
def sublist(x):
s = []
for elem in x:
if elem != 7:
s.append(elem)
else:
break
return s
This will only work if x is iterable and has elements that can be compared to 7.

Try this,
def sublist(x):
s = []
x1=0 #initialized x1
while x[x1] != 7:
s.append(x[x1])
if x1==len(x)-1:
break
x1+=1 #increment x1
return s
x=[1,4,8,9,2,7,4,2,3,4]
print(sublist(x))
output:
[1, 4, 8, 9, 2, 4, 2, 3, 4]
Hope this helps you!

Related

Return the only element in the hash table in Python

I am working on a problem as:
In a non-empty array of integers, every number appears twice except for one, find that single number.
I tried to work it out by the hash table:
class Solution:
def singleNumber(self, array):
hash = {}
for i in array:
if i not in hash:
hash[i] = 0
hash[i] += 1
if hash[i] == 2:
del hash[i]
return hash.keys()
def main():
print(Solution().singleNumber([1, 4, 2, 1, 3, 2, 3]))
print(Solution().singleNumber([7, 9, 7]))
main()
returning the result as:
dict_keys([4])
dict_keys([9])
Process finished with exit code 0
I am not sure if there is any way that I can return only the number, e.g. 4 and 9. Thanks for your help.
Instead of return hash.keys() do return hash.popitem()[0] or return list(hash.keys())[0].
Of course this assumes that there is at least one pair in the hashmap. You can check for this using len(hash) > 0 before accessing the first element:
class Solution:
def singleNumber(self, array):
hash = {}
for i in array:
if i not in hash:
hash[i] = 0
hash[i] += 1
if hash[i] == 2:
del hash[i]
return hash.popitem()[0] if len(hash) > 0 else -1 # or throw an error
One solution that might be simpler is to use the .count method.
myList = [1, 4, 2, 1, 3, 2, 3]
non_repeating_numbers = []
for n in myList:
if myList.count(n) < 2:
non_repeating_numbers.append(n)
Applied to your code it could look something like this:
class Solution:
def singleNumber(self, array):
for n in array:
if array.count(n) < 2:
return n
def main():
print(Solution().singleNumber([1, 4, 2, 1, 3, 2, 3]))
print(Solution().singleNumber([7, 9, 7]))

Loop inside the function can't run as well as an outside loop

I tried to find all the duplicates in list by the loop like the following
num = [1, 2, 2, 1]
for i in range(1, len(num)):
if num[i] == num[i - 1]:
print(num[i])
and it return all the duplicates inside the list but when i pass that inside the the function it only pick the first like the following
def FindDuplicates(nums):
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
return nums[i]
and this function remove the duplicates but can't work well as i expected
means when list looks like this print(RemoveDuplicate([1, 2, 3, 4, 4, 5, 6]))
it work well but this print(RemoveDuplicate([1, 2, 3, 4, 4, 4, 5, 6, 6, 6]))
the function crush
def RemoveDuplicate(array):
no_double = []
its_index = 0
founded = 0
for arr in array:
if array.count(arr) > 1:
founded = arr
its_index = array.index(arr)
elif array.count(arr) <= 1:
no_double.append(arr)
no_double.insert(its_index, founded)
return no_double
when there is a lot of duplicates this function can't pick them all out
any one who can help me to fix this bug
Try this :)
from collections import Counter
lst = [4,3,2,4,5,6,4,7,6,8]
d = Counter(lst) # -> Counter({4: 3, 6: 2, 3: 1, 2: 1, 5: 1, 7: 1, 8: 1})
res = [k for k, v in d.items() if v > 1]
print(res)
Can anyone help me to fix this bug?
Doing it your way, maybe this:
def FindDuplicates(nums):
d = []
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
d.append(nums[i])
return d
The reason yours don't work is because when the program reaches a return statement in a function, it will jump out of the function right then and there. So if you want to returns multiple values in a single function, make sure they're returned all at once.

Trying to use sort method on a list but doesn't work. I have included code that works with the sorted method but can't understand why it doesn't work

#Trying to find largest even number
def highest_even(li):
even = []
for num in li:
if num % 2 == 0:
even.append(num)
print(sorted(even)[-1])
highest_even([3, 2, 1, 3, 4, 8, 22, 11])
Use max:
print(max(i for i in li if i % 2 == 0))

Python loop to calculate sum of elements in a list except 13

I am trying to write a function that iterates through a list to return the sum of the integer elements in the list. However if there is a 13 in the list, it needs to exclude the 13 and whatever comes right after it from the sum. So far I have come up with the following code. This works for almost all cases except when there are two 13's back to back. It only excludes the two 13's instead of the two 13's plus whatever is after the second 13. For example, when I call the function with print(sum13([13, 13, 2, 13, 1, 5, 6, 13])), instead of giving the output of 11 it gives 13. Any help is appreciated.
def sum13(nums):
while 13 in nums:
index13 = nums.index(13)
nums = nums[0:index13]+nums[index13+2:]
return sum(nums)
The idiomatic way of doing something like this is to keep track of the previous variable, for example:
def sum13(nums):
prev = None
my_sum = 0
for ele in nums:
if ele != 13 and prev != 13:
my_sum += ele
prev = ele
return my_sum
if __name__ == "__main__":
print(sum13([1,2,13,3,4]))
print(sum13([13, 13, 2, 13, 1, 5, 6, 13]))
Result:
7
11
You can do it functionally:
def sum13(nums):
return sum(current
for current, following
in zip(nums, [None] + nums[:-1])
if current != 13 and following != 13)
"Gimme a sum of all numbers that are not 13, and whose next number is not 13".
You could use a slice to determine whether a 13 precedes a number:
def sum13(nums):
sum_ = 0
for index, elem in enumerate(nums):
if 13 not in nums[max(index-1, 0):index+1]:
sum_ += elem
return sum_
The max is needed only for the first element, being that i-1 would be 0-1, so the slice would be [-1:1], which is empty. You can even cut it down to one line, if you really wanted to:
sum(e for i, e in enumerate(nums) if 13 not in nums[max(i-1, 0):i+1])
Because generators need love too:
l = [13, 13, 2, 13, 1, 5, 6, 13]
def sanitize(list):
il = iter(list)
for e in il:
while e == 13:
e = next(il)
if e != 13:
e = next(il)
yield e
print(sum(sanitize(l)))
The idea being that you clean up your list first and then sum it up.
Try the below. Note that this is using nexted function to remove 13s, or a series of 13s and the number right after
def refine(nums, index_i):
while 13 in nums:
print(nums)
index = len(nums) - nums[::-1].index(13) - 1
if index == index_i -1:
nums = refine(nums[0:index] + nums[index+1:], index)
else:
nums = refine(nums[0:index] + nums[index+2:], index)
return nums
print( sum(refine([0, 13, 1, 2, 3, 4, 13, 13, 7, 13, 13, 5, 6, 13], 0)) )
This will sum only [0, 2, 3, 4, 6]
However, this is assuming you have a small list to manage With large list, you might want to think of the performance of such manipulation

duplicates function, adding

Hello I am trying to develop a function to find duplicates in a list. Below is the code that I have obtained thus far. I am cannot seem to figure out how to get the code to correctly add the number of duplicated numbers.
import collections
myList = [5, 9, 14, 5, 2, 5, 1]
def find_duplicates(aList, target):
if target not in aList:
print (target, "occurred 0 times")
else:
n=0
print (target, "occurred",n+1,"times")
the output of the code shows:
find_duplicates(myList, 5)
5 occurred 1 times
Obviously I am missing something for the program to properly track how many times the value occurs? Can someone please help?
I am not allowed to use the count() or sort() built in functions.
To only count the number of duplicates, just iterate over the list, comparing each value. If you find a match, increment a counter, than report the counter. To make this better, I would return the count then print to console outside of the def.
import collections
def find_duplicates(aList, target):
n = 0
for obj in aList:
if obj is target:
n += 1
return n
myList = [5, 9, 14, 5, 2, 5, 1]
target = 5
num_dup = find_duplicates(myList, target)
print (target, "occurred", num_dup, "times")
This should echo out:
5 occurred 3 times
Or do this (with list.count(x)):
myList = [5, 9, 14, 5, 2, 5, 1]
target = 5
num_dup = myList.count(target)
print (target, "occurred", num_dup, "times")
This should echo out:
5 occurred 3 times
You forgot to increment n in your code, so it always print 1. I think your code should look like:
import collections
myList = [5, 9, 14, 5, 2, 5, 1]
def find_duplicates(aList, target):
if target not in aList:
print (target, "occurred 0 times")
else:
n= aList.count(5)
print (target, "occurred",n,"times")
without using count and reading the target from shell:
import collections
myList = [5, 9, 14, 5, 2, 5, 2]
def find_duplicates(aList, target):
result = 0
for item in aList:
if item == target:
result += 1
return result
try:
target = int(raw_input("Choose a number to find duplicates: ")) # for python 3.X use input instead of raw_input
res = find_duplicates(myList, target)
print (target, " occurred ", res, " times")
except:
print("Write a number, not anything else")
This works for integers, if you want to use floats, just change int(...) for float(...)
it's a simple case of using a dictionary. Check the following code:
def frequency(l):
counter = {}
for x in l:
counter[x] = counter.get(x, 0) + 1
return counter
It will iterate over the list, saving each element as a key to the counter dictionary. Note the special form counter.get(x, 0), it will return the value of counter[x] if x is already on the dict, else it will return zero.
Checking the results is a matter of using:
print(frequency(myList))
>>> {9: 1, 2: 1, 5: 3, 14: 1, 1: 1}
You can get the number of appearances of any member by inspecting the dictionary:
frq = frequency(myList)
print(frq[14])
>>> 1
print(frq[1])
>>> 1
Of course it's possible to write a wrapper:
def target_frequencty(target, my_list):
frq = frequencty(my_list)
return frq.get(target, 0)
Enjoy.

Categories