Why is there a None in output? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Help, I'm trying to create a function that uses modulus to print numbers that are divisible by an integer, in this case, multiples of 17:
def nextDivisible(n):
if n % 17 == 0:
print n
else:
nextDivisible(n+1)
But the output is for example:
n: 93 next divisible: 102
None
n: 59 next divisible: 68
None
Why is there a None?! and how do I remove it, thanks!

I think your problem is that you are printing out the result instead of returning it from the function.
If you change your code to be like this it should fix it:
def nextDivisible(n):
if n % 17 == 0:
return n
return nextDivisible(n + 1)
How this works with recursion is that your function nextDivisible is going to be repeatedly called until it reaches its base case of n being divisible by 17. When that case occurs it will return n all the way back up the recursive stack to where the original first call to the function was done.
You also don't need an else statement because return statements break out of the function code. But sometimes else's are good for readability.

You don't need to:
print(nextDivisible(n))
I think you get None printed because your function doesn't return anything. It is also redundant to print the return of the function because you print the numbers inside the loop.
All you need is:
nextDivisible(n)
And it will print the divisible numbers.
If you are use nextDivisible() in other functions, it may be worth nothing that a return statement may be required depending on the nature of how you are using it.
For all intents and purposes this should work just fine.
And python 3.x:
x = [x for x in range(1000)]
def nextDivisible(x, mod=17):
c = 0
for n in x:
if n % mod == 0:
print(n)
c += 1
else:
#nextDivisible(n+1)
pass
print('{} numbers divisible by {} in {}'.format(c, mod, len(x)))
nextDivisible(x)
Expected output:
59 total numbers divisible by 17 in 1000

Related

Please help me solve this algorithm im in problem this code python (TypeError: 'NoneType' object is not iterable)? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 months ago.
Improve this question
it is my first post in StackOverflow I'm having trouble understanding and applying this exercise on my own with python please could help me!
getting this TypeError: 'NoneType' object is not iterable
This is the exercise Algorithm:
Definition: An integer is said to be perfect if it is equal to the sum of all its divisors. Examples: 6 and 28 are perfect since
6 = 1+2+3 (knowing that 1, 2 and 3 are the divisors of 6 less than 6)
28= 1+2+4+7+14 (knowing that 1, 2, 4, 7 and 14 are the divisors of 28 less than 28)
1) Create a function liste_divisors(), which accepts an integer N as a parameter and returns the list of its divisors less than N (1 included).
2) Make a function is perfect(), which accepts a (positive) integer N as a parameter and returns “True” if it is perfect and “False” otherwise (use the function from the 1st question)
3) Create a Perfect List() function, which accepts a Limit parameter, then returns a list containing the perfect numbers less than Limit
This is my attempt so far,
but there are errors, please help me to correct these errors and make it better
def liste_diviseur(N):
for i in range(1,N):
if(N%i == 0):
print(i)
def est_parfait(M):
s = 0
for i in liste_diviseur(M):
s += i
if(s == M):
return True
else:
return False
def liste_parfait(Limite):
if(Limite<est_parfait(Limite)):
return Limite
m = int(input('Giving an number :'))
print(liste_parfait(m))
As you iterate over the result of liste_diviseur() this latter function must return an iterable (something we can iterate).
It can be a sequence : a list or a tuple.
def liste_diviseur(N):
diviseurs: list[int] = []
for i in range(1,N):
if(N%i == 0):
print(i)
diviseurs.append(i)
return diviseurs
Or simpler you can use a Generator.
def liste_diviseur(N):
for i in range(1,N):
if(N%i == 0):
print(i)
yield i
Consider adding N itself to the divisors list.
N divided by N equals 1.
You can add N at the end of the loop.
Or you can have a higher range with range(1, N+1) as the upper bound is not comprised.
"1) Create a function liste_divisors()....and returns the list of its divisors.."
Your function just prints the divisors, You need to collect them in a list and return it.
Then you can iterate over the list in est_parfait(M).

How can I solve the functions of large number problem in Python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm trying to find the factors of 600851475143. my code isn't working.
def factor(a):
factor = []
for i in range (1, a+1):
if(a%i==0):
factor.append(i)
print(factor)
factor.clear()
factor(600851475143)
You can use return keyword to return a list of factors.
def factor(a):
factor = []
for i in range (1, a + 1):
if a % i == 0:
factor.append(i)
return factor
print(factor(int(input())))
Your code have some problems, first, the if statement in python don't use (), it should be only if a%i == 0:. Your code is not correctly indented, the code bellow the function is not part of it. You made a global variable with the same name as the function name, they overwrite each other.If you want the function to complete:
factorlist = []
def factor(a):
for i in range(1, a + 1):
if a % i == 0:
factorlist.append(i)
factor(input("Fators of: "))
print(factorlist)
factorlist.clear()
If you want to return the end list, use the #Ratery 's code.
First of all the indentation is not correct. You've to indent the inner code of the function correctly. It should come inside the defining statement. The next thing is, you're printing the factor list outside the function which is a local variable and not global variable. If you want to print it, add a print statement inside the function and then call the function. Your corrected code:
def factor(a):
factor_1= []
for i in range (1, a+1):
if(a%i==0):
factor_1.append(i)
print(factor_1)
factor(600851475143)
Also, don't keep your function name and the list name same. It might give error
Your function should return the list of factors (not print it). Because you are going through all potential divisors from 1 to a, it will take along time to produce a result with a very large number such as 600851475143.
To make this run faster, you can extract the factors in pairs so that you only have to look at divisors up to the square root of your number. Every time you find a factor (f) of the number (N), you know there is a corresponding factor which is the result of dividing N by f (N/f). This means that every factor <= √N has a corresponding one that is >= √N so you can get them in pairs and only check the divisors <= √N
def factors(N):
return [f for d in range(1,int(N**0.5)+1) if N%d==0 for f in {d,N//d}]
Output:
print(factor(600851475143))
[1, 600851475143, 8462696833, 71, 716151937, 839, 408464633, 1471,
6857, 87625999, 59569, 10086647, 104441, 5753023, 1234169, 486847]

How does this for loop on consecutive integers work? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
This seems like an embarrassingly easy concept but I can't understand why this for loop is working the way it is. The question is simply asking "Given a binary array, find the maximum number of consecutive 1s in this array."
def main(nums):
count = 0
for num in nums:
if num == 1:
count+=1
else:
count = 0
main([1,1,0,1,1,1,0,0,1,1,1,1,1])
My question is, why does this for loop work? I expected the loop to print out the total count of 1's.
It just doesn't work.
You can't expect to have the sum of all the 1s because when the loop find a zero it reset the counter (the "else" part).
However, your code doesn't do what it was expected to do, add a zero at the end of the list and you will easily see that the code fails.
To do what you asked, without changing your code too much, try this
def main(nums):
count = maxcount = 0
for num in nums:
if num == 1:
count+=1
else:
maxcount=max(maxcount, count)
count = 0
return maxcount
print(main([1,1,0,1,1,1,1,1,1,0,0,1,1,1,1,0,1]))
Dave
The difference is that once it sees a zero, it sets the value of count back down to zero, saying that it's seen 0 consecutive ones. This code actually doesn't work—it only gets lucky on this input because the longest sequence is at the very end of the list.
A better practice would be to store both the lengths of the current_group of ones and the highest_total count.
It's probably hard to believe, but could it be that the reason you are wondering why this loop works at all is that you are not familiar with Python ability to iterate over all elements of a list, not needing any counter variable increasing its value?
[1,1,0,1,1,1,0,0,1,1,1,1,1]
is in Python a kind of array storing multiple number of values.
Here some "pseudo-code" for explanatory purpose only demonstrating that "for num in nums" means in Python (in terms of programming in other
languages which don't support iteration over elements of a list/array):
noOfValuesIn_nums = lengthOf/sizeOf(nums)
for i = 0 to noOfValuesIn_nums do:
# get i=th value from 'nums' and put it to a variable named 'num':
num = nums[i]
...
By the way: the loop provided in the question gives the desired result for the provided example:
main([1,1,0,1,1,1,0,0,1,1,1,1,1])
but won't work on another one as demonstrated here:
def main(nums):
count = 0
for num in nums:
if num == 1:
count+=1
else:
count = 0
return count
print( main([1,1,1,1,1,1,0,0,1,1,1,0,1]) )
# it prints 1 instead of 6
The task of finding the longest consecutive sequence of ones
solves following code:
def main1(nums):
count = 0
maxOnes = 0
for num in nums:
if num == 1:
count+=1
else:
if count > maxOnes:
maxOnes = count
count = 0
return maxOnes
print( main1([1,1,1,1,1,1,0,0,1,1,1,0,1]) )
# gives 6

Python: How do I write a program that reads 10 different integers and prints the one that has the largest value? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
What is a method, in python, that can be used to read the largest number in a list? My attempt is below:
list = [a, b, c, d, e, f, g, h, i, j]
print max(list)
EDIT (Solution): Use a for loop.
userInput = []
for i in range(10):
userInput.append(int(input("Enter a number")))
print(max(userInput))
You can use a loop if you want to do something repeatedly. You want to have an empty list, and then get a number from the user 10 times, so you put all of the requests for a number from the user in a loop. input gives you a string, so you need to convert it to an int.
user_inputs = []
for i in range(10):
user_inputs.append(int(input("Enter a number")))
print(max(user_inputs))
If you don't understand loops, you should look into learning about them.
I think along with JHobern, you could probably do something like
print(max([int(raw_input("Enter a number: ")) for x in range(10)]))
That should do it!
To explain, you know what print and max should do.
raw_input asks the user for an input and stores it.
max() returns the maximum value in a list of things.
[ ______ for x in range(10)] is a list comprehension where it does something 10 times. Doesn't necessarily use the variable x in this case though.
So basically, I'm using list comprehension to create a list of 10 integers that is provided y the user and then prints out the maximum all in one line :)
You can use a while loop to achieve this:
This code will prompt the user 10 times to input numbers. Each time the number will be appended to the list nums. Also, each time the highest number in nums will be printed.
nums = []
while len(nums) < 10:
nums.append(int(input('Enter a number: ')))
print (max(nums))
If you only want to print the highest number at the end, one time, after the 10th input, then you can do this:
nums = []
while len(nums) < 10:
nums.append(int(input('Enter a value: ')))
print (max(nums))
You shouldn't use list as a variable because list is a built in function

Looking for revisions of previously written code [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I've noticed that lately my assignment grades have been getting lower as the class has advanced in Python, and I was wondering if anyone could help me see what I did wrong with these code snippets and why they were supposedly wrong. This may be a long post, but any help that'll stop me from making these mistakes in the future is appreciated.
def geometric(l):
'list(int) ==> bool, returns True if the integers form a geometric sequence'
res = False
if (l[1] / l[0]) == (l[2] / l[1]):
res = True
return res
This is a code that was considered wrong. As the code says, it takes a list of ints and returns whether or not they're in a geometric sequence. My book says a sequence is geometric if a1/a0 equals a2/a1, which worked just fine for 2, 4, 8, 16, etc. I just realized that the issue with this one is that it only checks the first two indices and ignores the rest of the numbers. What could I write that would fix this?
def letter2number(grade):
'''string ==> int, returns the numeric equivalent to the letter grade, adding 0.3 if the grade contains a +
and subtracts 0.3 if the grade contains a -'''
res = 0
if 'F' in grade:
res = 0
elif 'D' in grade:
res = 1
elif 'C' in grade:
res = 2
elif 'B' in grade:
res = 3
elif 'A' in grade:
res = 4
if '+' in grade:
res += 0.3
elif '-' in grade:
res -= 0.3
return res
This wasn't considered wrong, exactly, but it was much longer than he intended I guess. A comment he wrote on the file was "# set res to index of grade in grades," but since it was an independent lab I couldn't ask for help. I attempted to give each grade its value in a list but I couldn't index it correctly.
def leap(n):
'int ==> bool, returns True if the year is a leap year, False otherwise'
res = False
if n % 4 == 0 and n % 400 == 0 or not n % 100 == 0:
res = True
return res
Figuring out an if statement that translated into "A year is a leap year if it is divisible by 4 but not by 100, unless it is divisible by 400" was confusing for me. Apparently what I wrote works for all odd numbers, but I can't really figure out why.
It seems like at least half your problems aren't programming problems, but problems understanding the assignment. For example:
This is a code that was considered wrong. As the code says, it takes a list of ints and returns whether or not they're in a geometric sequence. My book says a sequence is geometric if a1/a0 equals a2/a1, which worked just fine for 2, 4, 8, 16, etc. I just realized that the issue with this one is that it only checks the first two indices and ignores the rest of the numbers.
Your code correctly implements what you thought the assignment was. It just doesn't implement what the assignment actually was, by checking all pairs of indices. Once you know that's what you need to do, presumably you can figure out how to write a loop that compares pairs of indices:
def geometric(l):
'list(int) ==> bool, returns True if the integers form a geometric sequence'
res = True
for i in range(len(l) - 2):
if (l[i+1] / l[i]) != (l[i+2] / l[i+1]):
res = False
return res
And then you might notice that you can short-circuit things at the first failure, or compare all the ratios to the first instead of comparing them as pairs (meaning you have to calculate most of them twice), or write a simple helper function that just checks one pair and use all to run it on all of them, etc., but those are all just refinements.
Then:
Figuring out an if statement that translated into "A year is a leap year if it is divisible by 4 but not by 100, unless it is divisible by 400" was confusing for me. Apparently what I wrote works for all odd numbers, but I can't really figure out why.
You first need to translate that into a sequence of and and or and not steps in English. What you did, "divisible by 4 and divisible by 400 or not divisible by 100", is not even close to the same thing. You then coded that incorrect algorithm correctly, but that's no help.
All you need to do is translate "but not" to "and not", and "unless" to "or": "visible by 4, and either not divisible by 100 or divisible by 400". The only tricky part about translating that to code is using parentheses instead of the command and "either":
if n % 4 == 0 and (not n % 100 == 0 or n % 400 == 0):
For your letter2number I would have used a dictionary instead to handle the mapping, something like this:
def letter2number(grade):
G = {'F': 0, 'D': 1, 'C': 2, 'B': 3, 'A': 4}
D = {'+': 0.3, '-': -0.3}
if len(grade) == 2:
return G[grade[0]] + D[grade[1]]
else:
return G[grade[0]]

Categories