Python 3 : List of odd numbers [duplicate] - python-3.x

This question already has answers here:
Python "for i in" + variable
(3 answers)
Closed 2 years ago.
I'm trying to return a list of odd numbers below 15 by using a python user-defined function
def oddnos(n):
mylist = []
for num in n:
if num % 2 != 0:
mylist.append(num)
return mylist
print(oddnos(15))
But I'm getting this error :
TypeError: 'int' object is not iterable
I didn't understand what exactly this means, please help me find my mistake

Because 15 is an integer, not a list you need to send the list as an input something like range(0,15) which will give all numbers between 0 and 15.
def oddnos(n):
mylist = []
for num in n:
if num % 2 != 0:
mylist.append(num)
return mylist
print(oddnos(range(0,15)))

When you're passing values to the function oddnos, you're not passing a list of values till 15, rather only number 15. So the error tells you, you're passing an int and not a list, hence not iterable.
Try to use range() function directly in the for loop, pass your number limit to the oddnos function.

Related

what is wrong with my Sum of Digits recursive function? [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 5 months ago.
def digital_root(n):
if n > 0:
a.append(n%10)
if n/10 > 0:
digital_root(n/10)
else:
if len(a) > 1:
b = a
a.clear()
z = 0
for i in range(len(b)):
z += b[i]
digital_root(z)
else:
return a[0]
why it returns None?
task is: Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.
You got None because you seem to miss return statements when you call digital_root(). Should be:
return digital_root(n/10)
and
return digital_root(z)

for loop doesn't itterate through all the data? [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
data = [1, 2, 3, 4, 5]
for x in data:
print(x)
if data.count(x) < 2:
data.remove(x)
Hello Guys,
so I am currently working through py.checkio.org and am at a point where I have to remove all the numbers that are unique in a list.
When I run my code without the if statement I get an output counting from 1 to 5. But once I run the for loop with the if statement the for loop only runs through the data for every second number and my output is 1 3 5. Can anyone please tell me what is happening here?
While the from #Stef and #0x5453 are both relevant to your problem. The comment from #ConnorTJ is patently wrong. The remove function does not remove the item at the index but the first occurrence of the item.
To answer your question, about what's going on here, let[s examine your code:
The first pass through the value of x is 1
You print the value of x
You then test to see if the number of occurrences of x is less than 2
Since the answer is yes, you proceed to remove the item from the list.
The second pass through the list the For loop picks up the next value in the list (at index 1) which is now the value 3
You print the value 3
You check to see if the count of 3 is less than 2
Since the count is less you remove that item from the list.
This process than continues
Simple solution, use filter()
Construct an iterator from those elements of iterable for which function returns true
it returns a list of the list items that the function returned true for.
example:
x = [1,1,2,2,3,4]
x = filter(lambda f: (x.count(f)<2), x)
x = list(x)
print(x)
or in short: print(list(filter(lambda f: (x.count(f)>=2),x)))
output is [1,1,2,2]

Binary Search function returning None value in python [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 2 years ago.
Below is the code which I used for binary search in python using recursion. I have not used num == l[mid] since this is being handled by function calling this binarySearch. I just have to return the last item of list being left while splitting it.
def binarySearch(l,num):
length = len(l)
if length==1:
print(l)
return l
if length % 2 == 0:
mid = (length//2) - 1
else:
mid = length//2
if num < l[mid]:
binarySearch(l[mid+1:],num)
else:
binarySearch(l[0:mid+1],num)
print(l) prints the correct value which I want to return but return l gives me None instead of l
if num < l[mid]: binarySearch(l[mid+1:],num) doesn't return anything: it calls binarySearch and discards its return value. Thus, None is returned implicitly. You should actually return the values you want to be returned:
if num < l[mid]:
return binarySearch(l[mid+1:],num)
else:
return binarySearch(l[0:mid+1],num)
Here, return binarySearch(...) means "return whatever the call to binarySearch returned".

This code is not giving the value of the new sorted list . Can someone tell me the error in this code? [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 3 years ago.
I am making a class for sorting algorithms . But there seems to be some error which is giving the value of my sorted linked list as None. I cannot identify the missing piece of the code. Please help.
#Bubble sort algorithm
class Sort:
def Bubble(self,llister):
for i in range(len(llister)-1,0,-1):
for j in range(i):
if llister[j]>llister[j+1]:
llister[j],llister[j+1]= llister[j+1],llister[j]
if __name__=='__main__':
obj = Sort()
llist = [2,5,3,15,10,13,1]
print("The list before bubble sort : " ,llist)
ans = obj.Bubble(llist)
print("The list after bubble sort :" ,ans)
Unfortunately Python doesn't do any type checking. Your bubble function doesn't contain a return statement; it therefore returns None by default. ans is therefore None and None is what is printed.
In order to avoid returning None, return a result explicitly instead e.g. return 'Some'.

Accept iterable sequence and return them in reverse order [duplicate]

This question already has an answer here:
iterating an interable sequence in reverse order [duplicate]
(1 answer)
Closed 4 years ago.
Write a generator function reverse_iter that accepts an iterable sequence and yields the items in reverse order without using built-in functions or methods. After using the function however, the original list should be unchanged. An example output is below:
it = reverse_iter(nums)
next(it) == 4
True
next(it)
3
next(it)
2
next(it)
1
Note that the above should work even if the list is changed to a tuple. I have no idea how to do this without using something like reverse() or reversed(). Maybe utilize a -1 slice? Any Ideas?
def reverse_iter(nums): # A generator function
idx = len(nums) - 1
while idx > -1:
yield nums[idx]
idx -=1
nums = [1,2,3,4]
print('before: ',*nums)
get = reverse_iter(nums) # get is a generator object
print('manually')
# Iterating over the generator object using next
print(get.__next__()) # In Python 3+ , print(get.__next__())
print(get.__next__())
print(get.__next__())
print(get.__next__())
#print(get.next()) #now you will get StopIteration
#print(next(get,'traversing complete')) #to avoid the StopIteration exception
# printing all items in list in reverse
print('\nusing for loop')
get = reverse_iter(nums) # get is a generator object
for i in range(len(nums)):
print(get.__next__())
print('after: ',*nums)

Resources