My teacher solved this question "Write a function which takes a n digits number as an input and return True if the biggest digit in this number is divisible by 3" like this:
def is_divisable(n):
a = str(n)
b = 0
for i in a:
if int(i)>b:
b = int(i)
if b % 3 == 0:
return "True"
print is_divisable(67479)
I have thought of it in another way but my code is not working and
I am getting an error says:
"TypeError: 'int' object is not iterable"
def is_dvo(n):
if max(n) % 3 == 0:
return True
print is_dvo(67479)
You don't quite say what your question is, but if you want another way to solve the problem,
def is_divisable(n):
return int(max(str(n))) % 3 == 0
This code converts the number to its decimal string representation, finds the largest digit (as a character), changes that digit to an integer, checks if that is divisible by 3, then returns that answer.
If your question is why you are getting that error, your parameter n is an integer, and you try to apply the max() function to that integer. However, max() is supposed to be used on iterable objects such as strings, lists, tuples, generators, and so on. My code changes the integer to a string before using max() so it does not have that problem, and it iterates over the digits in the string.
You can condense the code to a single line:
def is_divisable(n):
return max(map(int, str(n)))%3 == 0
Try:
max(str(n), key=int) in {'3', '6', '9'}
Related
I've tried to write a simple function, which input is binary number in string format and converts binary to decimal. But in the output I always get the wrong thing: the 'res' value in line 3, no matter what the input is ('1010', '10010111010', etc.). Also, I've tried to debug the code and the function doesn't even start the loop, as if it wasn't there... So, I just don't see my mistake
def bin_to_dec(bin):
bin = bin[::-1]
res = 0
for i in range(len(bin)):
if bin[i] == 0:
res += 2**i
return res
You are comparing the string "0" to the number 0 and they are, trivially, unequal.
So, contrary to what you say, the loop is actually looping; but the if statement will never be true.
Of course, also, you should probably add when the number is 1, not when it's 0.
def bin_to_dec(bin):
bin = bin[::-1]
res = 0
for i in range(len(bin)):
if int(bin[i]) == 1:
res += 2**i
return res
Notice the addition of int().
if bin[i] == '1'
This will correct the problem. bin[i] is a character and you are comparing it to a number which always results in false.
You can just use the built in int function:
def binaryToDecimal(n):
return int(n,2)
This question already has answers here:
Python Recursion: Range
(5 answers)
Closed 7 years ago.
So what I'm trying to do is basically make a recursive function that returns a tuple of numbers from 0 to a given number n that does not use range(), loops or lists. The problem reads as this:
"Define a recursive function called rec_range() that takes a natural number n and returns a tuple of numbers starting with 0 and ending before n. So rec_range(5) returns (0,1,2,3,4) and rec_range(1) returns (0,)."
The problem is that I have no idea how to make a function that returns a tuple. I know how to get a factorial of a number n using recursion, but we never went over how to return multiple numbers in a tuple.
The only thing I have right now is this:
def rec_range(n):
"""Takes a natural number n and returns a tuple of numbers starting with 0 and ending before n.
Natural Number -> tuple"""
if n == 0
return (,)
elif n == 1:
return (0,)
else:
???
Sorry if the answer to this is actually really obvious I'm very new to programming
You want to append tuples together, so use + and recurse over your function lowering the value by 1 . In addition, just return (or return None) for n == 0. Really the n == 0 call is unnecessary and your code could be more idiomatic, but I'll leave that to you.
def rec_range(n):
"""Takes a natural number n and returns a tuple of numbers starting with 0 and ending before n.
Natural Number -> tuple"""
if n == 0:
return
elif n == 1:
return (0,)
else:
return rec_range(n-1) + (n-1,)
Outputs:
>>>rec_range(4)
(0, 1, 2, 3)
need help with this, i tried something but it didn't work for some reason. I need some help to figure it out.
def F(n):
if n == 0: return 0
elif n == 1: return 1
else: return F(n-1)+F(n-2)
F('3')
and here is the original problem- Write a function called fib which takes as a parameter an integer, n, and returns the nth number in the Fibonocci sequence (see definition below). If n is zero or a negative number, your function should return an error message in the form of a string "Error: Invalid input.".
The Fibonocci sequence is 1, 1, 2, 3, 5, 8, 13, 21, ... where the first two numbers are 1, and each number beyond that is calculated as the sum of the previous two numbers (2 = 1+1, 3 = 2+1, 5 = 3+2, 8=5+3, etc).
i guess the problem is that you use string instead of integer.
try F(3) instead of F('3')
or give more information about the error you get
First, for the invalid numbers error you are supposed to print out, I would suggest adding another if statement in. Below shows an example of how you could set any negative number to return an error message.
if n < 0: return "Error: Invalid Input"
For the F function, it goes back to data types. When you put in quotes around something, that specifies an actual string. When you just have a number, it will be an integer data type. For this, we want an integer data type since we want to do math operations on our number. This is why you should remove the quotes.
I have a list like this, named x (which I have already split):
['16','bob','2440', '34']
I want to write a code that checks to see if any of the numbers are negative. The code I tried does not work. This is what I have tried:
for num in x:
if num < 0:
print ("Negative number")
Your list contains only strings. So you should cast them to floats (or integers, whatever you need) first:
a = ['"16','bob','2440', '-2', '34"']
for x in a:
try:
if float (x) < 0: print ('negative')
except: continue
EDIT: I changes int to float as OP is asking for numbers and not exclusively integers.
You need to turn your numbers into integers first; use a predicate function to try to do this:
def negative(string):
try:
return int(string.strip('"')) < 0
except ValueError:
return False
The predicate function here also removes quotes; your input list looks like it was not cleaned up properly and you may want to do so first before testing for negative values.
Then use that to test for negative values:
negative_values = [v for v in a if negative(v)]
or test if there are any negative values:
if any(negative(v) for v in a):
print "No negative values please!"
How about checking for - sign in the beginning of an item and for the rest of an item to consist of digits? One-liner:
>>> a = ["-1", "aa", "3"]
>>> any(s.startswith('-') and s[1:].isdigit() for s in a)
True
Using any, because you've said that you want to write a code that checks to see if any of the numbers are negative.
Note: if there can be negative floats, then just replace s[1:] with s[1:].replace(".", "").
Hope that helps.
First, you need to understand that neither '"16' nor '2440' are numbers - they are strings.
Secondly, you need to figure out what you want to do with '"16' - it doesn't represent a number, but I assume you want it to. You could alter these strings, but you should probably just use an appropriate method of splitting in the first place.
That said, you can do this:
x = ['"16','bob','2440', '34"']
def int_is_negative(s)
try:
return int(s) < 0
except ValueError:
return False
is_negative_num = [int_is_negative(s) for s in x]
I am new to python, and was going through some pre written code to get a better grip at it.
This code tries to get the number of digits each non-termination cycle has when a number is at the denominator to 1. For eg. 1/3 = 0.(3) it has a cycle of 1.
similary 7 has a cycle of 6 as 1/7 = 0.(142856)
def get_decimals(num, div, current=([], [])):
"""Return a tuple (integer_part, decimal_part, cycle_length) for num/div"""
headtail = lambda lst: (lst[0], lst[1:])
memory, values = current
if values and num == 0:
integer, decimals = headtail(values)
return integer, decimals, 0
elif num in memory:
integer, decimals = headtail(values)
print integer, decimals
lencycle = len(memory) - memory.index(num)
return integer, decimals, lencycle
a, b = divmod(num, div)
return get_decimals(10*b, div, (memory+[num], values+[a]))
print max((get_decimals(1, num)[2], num) for num in xrange(2, 10))[1]
could anyone please explain me in context of the code pasted above. I could not understand the following:
the subscripts [2] and [1] in the last print statement.
memory.index(num) this one inside the get_decimals function at the line 4th to last.
get_decimals(1, num)[2]
get_decimals returns a tuple containing 3 items, named integer, decimals and lencycle. So the subscript [2] picks out lencycle.
max((get_decimals(1, num)[2], num) for num in xrange(2, 10))[1]
The subscript [1] picks out num from a tuple of the form (get_decimals(1, num)[2], num). Note that the max function is applied before the [1] subscript. In this case max is operating on a iterable of tuple pairs and uses lexicographic ordering to compare items.
memory.index(num) calls the method index on the object memory passing num as the parameter. Since memory is a list then this is simply finding the index of the first occurrence of the value num in that list.
Unless you are very new, the above explanation would have made sense. If not, i try explaining in a simpler manner:
for a list a = [1, 2, 3] you would access first element as: a[0]
similarly a subscript of 2 after get_decimals(1, num)[2] means if the function is returning a tuple/dictionary access the third element, in your case the length of the cycle of the non-terminating series. For the input number 7, the output would be 6 as it has a non terminating cycle of 142856.
similarly for line: max((get_decimals(1, num)[2], num) for num in xrange(2, 10))[1]
if you go without the subscript [1] you will see two values printing, but the coder was concerned only with the second value being returned. Apparently the code says:
call the function get_decimals for the values 2 to 10.
Find the max of the tuple being returned and print the second item of the tuple which has been filtered as the max.
Index has been explained pretty clearly and needs no further explanation. Just another simplification:
[1, 2, 3] the index of 2 in list is 1. This will clarify the stuff.
Please refer to the official python documentation, before reading codes. IMHO.