Without using module, how can I determine the width of an integer? - python

In other words, if I am presented with the number 54352, I want an expression that will tell me the width of that number is 5. I could use a for each loop to do this I know, but that seems rather cumbersome. Any other ideas?

you can use len(str(54352)) which will return 5 by converting it into a string, and returning the length of the string representation of the number.
Another way, a bit longer, would be:
def ilen(n):
i=0
while n != 0:
n /= 10
i += 1
return i
ilen(54352)

Actually is more like len(str(abs(n))) because -1 should probably have length 1.

Try
n = 54352
print (len(str(abs(n))))
Amended as user2722968 is correct.

Related

I don't see my error here - Trying to learn Python

I'm trying to become comfortable with python. I've been trying some simple activities that I've given in my beginning c++ classes when I was teaching. I did one involving functions and writing a file which worked flawlessly. I thought this one would be easier. It acts like it is in a silent endless loop, but it won't even let me trace it. Can someone see where I am going awry?
# Find Adam Numbers
def isAdamNumber(candidate):
isAdam = False
rev = reverse(candidate)
square = candidate * candidate
revsq = rev*rev
if revsq == reverse(square):
isAdam = True
return isAdam
def reverse(num):
rev=0
while num > 0:
rev = rev * 10 + num%10
num/=10
return rev
for x in range (11,25):
if isAdamNumber(x):
print(x, " is an adam number\n")
The quick fix is to change /= with the integer division version, //=
Inside the reverse function, you are going into an infinite loop. num value always will be greater than 0, therefore the while loop will continuously run. In python, you can get the reverse of the function without much effort. Convert the integer to string and reverse the string and now change the string back to integer.
def reverse(num):
num_str = str(num)[::-1]
return int(num_str)
I think this function definition can solve your problem.
To visualize the python to learn and teach, use this link
The problem has already been addressed by the other answers, so here's the expanded and simplified version of the slicing that's going on [this doesn't actually use slicing]:
def reverse(num):
rev = ''
num = str(num)
for i in range(len(num) - 1, -1, -1):
rev += num[i]
return int(rev)
This counts backward from the last element in the string version of num, and adds all the elements of num (in reverse order) to rev.
num > 0 is never False. Dividing a positive number by 10 repeatedly makes it smaller, but it never becomes zero, so the while loop keeps repeating.
Use //= instead. It rounds to the nearest integer, so it will reach 0.
This also wouldn't reverse numbers (unless I'm missing something). Alternatively, you can use
int(str(num)[::-1])
which converts the number to a string, reverses it using slicing, and turns it back into an integer.

can't quite figure out what's not working (checkio excersise "Even the Last")

You are given an array of integers. You should find the sum of the integers with even indexes (0th, 2nd, 4th...). Then multiply this summed number and the final element of the array together. Don't forget that the first element has an index of 0.
For an empty array, the result will always be 0 (zero).
Input: A list of integers.
Output: The number as an integer.
Precondition: 0 ≤ len(array) ≤ 20
all(isinstance(x, int) for x in array)
all(-100 < x < 100 for x in array
result = 0
if array:
for element in array:
i = array.index(element)
if i%2 == 0:
result += element
else:
pass
else:
return 0
return result
Last_digit = array[-1]
final_result = result*Last_digit
return final_result
print(final_result)```
I've figured out the problem, that you've shared the array you're having problem with. Since you have this array :
[-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]
If you notice here, 84 appears twice, first at index 9 and then 16. The method you're using to get index of elements, .index returns the index of the first instance the element is found in the list.Therefore for the value of 84, the index is taken as 9 and not 16 which is an odd value, this does not add 84 to your sum. You should rather use enumerate for your code:
for idx, element in enumerate(array):
if idx %2 == 0:
result += element
First, I recommend reading the stackexchange guides on posting a well-formed question. You need to state what your goal is, what you've tried, what errors get thrown, and what the output should look like -- along with code examples and a minimal reproducible example as needed.
However, I'll help you out anyway.
You have a dangling return at line 11:
else:
return 0
return result
This makes no sense, as you've already returned 0. This is also apparently a snippet from a function, no? Post the whole function. But based on the instructions, you could try this:
import random
array = random.sample(range(-100, 100), 20)
def etl_func(arr):
arrsum = 0
for i, val in enumerate(arr):
if i%2 == 0: arrsum += val
return (arrsum * arr[-1])
answer = etl_func(array)
print(answer)
Note that importing random and using array = random.sample(range(-100, 100), 20) are not necessary if you're already GIVEN an array to work with. They're included here just as an example.
Also note that it's unnecessary to use an else: pass. If the condition evaluates to true (i.e. i%2 == 0), the if block will be executed. If i%2 != 0, the loop will short circuit automatically and move to the next iteration. Adding else: pass is like telling someone sitting in your chair to sit in your chair. You're telling the program to do what it's already going to do anyway. There's nothing necessarily wrong with including the else: pass, if it really want to... but it's just adding lines of meaningless code, which nobody wants to deal with.
EDIT: I don't know whether you were supposed to write a function or just some code (back to the "ask a well-formed question" issue...), so I went with a function. It should be trivial to turn the function into just plain code -- but you want to get into the habit of writing good functions for reusability and modularity. Makes everything run more smoothly and elegantly, and makes troubleshooting much easier.
This function also works for the array mentioned in the comments to your original post.
In addition, if you need a direct replacement for your code (rather than a function... I'm not familiar with checkio or how your answers are supposed to be formatted), and you already have the array of integers stored in the variable array, try this:
arrsum = 0
for i, val in enumerate(array):
if i%2 == 0: arrsum += val
print(arrsum * array[-1])
Since your question didn't say anything about using or defining functions, return statements shouldn't appear anywhere. There's nothing to return unless you're writing a function.

Counting zeroes using Recursion and if-else in python

def countz(n):
if n<10:
if n==0:
return 1
else:
return 0
small=countz(n//10)
if n%10==0:
return small+1
else:
return small
from sys import setrecursionlimit
setrecursionlimit(11000)
n = int(input())
print(countz(n))
Someone helped me write this code, I did not understand why he used the condition n<10 in the base case of the recursion. I though the code would work without that condition but it didn't. Can anyone help me understand why the code is not working without that condition/ what is the real purpose or reason for that condition?
The base case that we want here is indeed n<10, or in words, n is a single digit number.
You might be tempted to choose n==0 as the base case and simply return 1 because it has one zero:
def countz(n):
if n==0:
return 1
small=countz(n//10)
if n%10==0:
return small+1
else:
return small
But that wouldn't work! Why? Consider the input 9, which has no zeroes. This isn't the base case, so we enter the recursive call: small=countz(n//10). n//10 gives 0, so we call countz(0) which returns 1. This is then returned as the answer, even though it should be 0.
The underlying problem is that, by convention, we denote the number zero with one more digit than is actually needed. Ideally it would consist of no digits at all, but that would be a bit impractical in daily life!

Converting binary number to decimal useing string

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)

How do I check if each digit of a number is less than 2? (python) [duplicate]

This question already has answers here:
How to check if a input is in binary format(1 and 0)?
(8 answers)
Closed 7 years ago.
I'm trying to create a program that checks if each digit of a given number is less than 2, possibly using
range(len(a)):
def is_bin(number):
try:
int(str(number), 2)
except ValueError:
return False
return True
You can convert number to string and check like this:
all(int(c) < 2 for c in str(n))
For example:
>>> all(int(c) < 2 for c in str(1011))
True
>>> all(int(c) < 2 for c in str(1211))
False
You can try this
num = 123457
>>>all(int(i)<2 for i in str(num))
False
num = 11011
>>>all(int(i)<2 for i in str(num))
True
Python is dynamically typed, so this is relatively easy to do. I would suggest converting your integer into a string, then iterating through the string and checking each digit.
Using that method, the code would probably look something like:
your_number_string = str(your_number)
for d in range(0, len(your_number_string)):
i = your_number_string[d]
if (int(i) > 2):
raise new Exception("Digit " + str(i) + "is not less than 2")
Couple things to note with this: It's bad practice to throw bare Exceptions. If you like the exception route, then extend the exception class and make your own. This also assumes that your number is a valid integer. Finally, this also will only alert you for the first digit larger than two, it won't tell you about any subsequent ones that also are larger than 2. This will require some adjustments for negative numbers and floats.
Could use the good ol' fashioned method :) just take your number and extract each digit and then update your number.
while yournumber != 0 :
digit = yournumber % 10
yournumber = younumber / 10
if digit < 2
do stuff
but I'm sure there are easier (maybe not as fast) ways.
At the moment, all solutions depend on converting the number to a string. While that works, you could do it completely numerically:
def check_digits(nbr, max=1):
nbr = abs(nbr) # only look at a positive numbers
while nbr != 0:
nbr, rem = divmod(nbr, 10)
if rem > max: return False
return True
The trick here is that each time the digit furthest to the right gets inspected. Once that's done, the number gets divided by 10, ignoring the remainder. So 1201 becomes 120, which becomes 12 and the cycle stops there, because divmod(12, 10) is (1, 2), and the remainder, 2, is bigger than your maximum digit.
Note that TigerhawkT3's answer and #John La Rooy's comment probably nailed it (upvoted) as it is by far the most Pythonic solution. All others, including mine, work for various programming languages, TigerhawkT3's solution uses Python exceptions to good effect.

Categories

Resources