This question already has answers here:
range() for floats
(23 answers)
Closed 2 years ago.
I'm trying to print the numbers between 0.00001 and 0.1, where i tried:
for i in range(0.00001,0.1):
print(i)
But python throws an error saying it cannot be interpreted as integers. Is it possible to do something like this in python?
range only supports integers. Lets define our own
def frange(start, stop, step):
while start < stop:
yield start
start += step
for i in frange(0.5, 1.0, 0.1):
print(i)
From the range() method documentation we can read the following:
The arguments to the range constructor must be integers (either built-in int or any object that implements the __index__ special method).
You also didn't specify the step you want to have. Because there are infinitely many real numbers between any 2 unique real numbers, you can't really get all of them.
What you can do is multiply both sides of the range by the same number until they are both integers and then when doing stuff with them divide them by that number again. I'm going to assume you wanted to have a step of 0.00001
mult = 100000
for i in range(1, 10000):
print(i/mult)
If you want any different step, simply supply a third argument to the range() method.
Related
This question already has answers here:
How to implement conditional string formatting? [duplicate]
(3 answers)
Closed 1 year ago.
I currently am trying to work with a number that has variable decimal place lengths. It can either be an integer, or have up to 10 decimals i.e. 33.3333333. I wanted to restrict the number to only have 2 decimals when it exceeds the length, or maintain the original if it's less.
I've tried using "{:0:.2f}".format, but the problem is that for integers, it also adds .00 to the end of the string.
When I tried using round(3) it'll return 3.0.
Is there a method, preferably a single line, that can convert 3.333333 to 3.33 but still allow for 3 to stay as an int?
Try choosing the format as a function of the values wholeness:
"{d}" if int(a) == a else "{:0:.2f}"
Can you finish from there?
You can use a conditional expression to choose the format based on the type of the variable:
for x in (33.3333333, 3):
print(("{:0}" if isinstance(x, int) else "{:.2f}").format(x))
You could also implement it using a dictionary to map types to format strings:
formats = {int: "{:0}", float: "{:.2f}"}
for x in (33.3333333, 3):
print(formats.get(type(x)).format(x))
I have some kind of AP in Computer Science and I've started on coding/programming with Python. I briefly used C++ for few years and now I switched to Python. I don't really remember where I stopped with C++ but that's irrelevant now. Anyways, I have this task that says: "Write program that loads number N, then N numbers and prints number that has the highest value between them. Number N has input in one line and line underneath loads N numbers with same space between them. None of the numbers will be greater than 100. Number N will be greater than 2."
I wrote this code;
`n = int (input())
max = 2
for i in range (1, n+1, 1):
x=map(int,input().split())
if x>max: x=max
print (max)
`
which returned this error:
5
2 87 12 90 55
File "C:\Users\Mariee.Marija-PC\Documents\Python\19-4.py", line 5, in
if x>max: x=max
TypeError: unorderable types: map() > int()
that was totally expected because I know I can't compare those two as they are clearly not comparable (which again, I am very aware of).
So my question is, is there any other way that N number could be put in one line and then N numbers could be put in the same line but you can compare them (if that makes any sense).
[P.S. Also I'm ultimately sorry if my english was bad.]
The variable x is a map (similar to a list) of integers, but you are comparing it with a single integer.
In order to loop over the values of x you should use a for loop:
for x in map(int, input().split()):
if x > max:
max = x
There's already a max method in Python, and no need to re-create a max function like you have to do in C/C++. Just apply the max method
n = int (input())
print (max(map(int,input().split())))
This question already has answers here:
Python: range function for decimal numbers [duplicate]
(4 answers)
How do I use a decimal step value for range()?
(34 answers)
Closed 8 years ago.
Using Python 3.4 and I have a list which has numbers in it which have 8 decimal places or more (eg. -72.2373909452 and 175.33903215), and I need a way to separate them according to their number.
Original code looks like this:
for number in list:
range_list=[]
if number in range(x, y):
range_list.append(number)
but for obvious reasons it doesn't work and doesn't add any numbers to the new list.
I also thought about multiplying the number first and then just having the range numbers between factors of ten, but as the number of decimal places is different between each number that isn't practical.
If I understand well, you want to check if number is between x and y.
Just use comparisons then. The following has the same behavior the "number in range(x, y)" solution has with integers:
if x <= number < y:
range_list.append(number)
Even if number is an integer, this sort of comparison is clearer and most likely faster than the solution involving range.
On a side note, you should define range_list outside of the for loop, otherwise you'll end up emptying the list with each loop:
range_list=[]
for number in my_list:
if x <= number < y:
range_list.append(number)
This question already has answers here:
How do you round UP a number?
(28 answers)
Closed 8 years ago.
I have some integer count suppose '51' and I want represent that much of integers in binary number. Here I need to do log(51) so i get some float value as 3.93182563272. But I want it in some integer format as 4 which could be used to represent 51 integers.
Log value can be calculated as
import math
math.log(51)
If you want the number of binary digits, that would be base 2, whereas math.log by default returns the natural logarithm (base e). A second argument can be used to specify an alternative base. Then you can use math.ceil to round up the number.
math.ceil(math.log(51, 2))
6.0
You haven't specified a python version but if you have python 3, (thanks #delnan), you can use math.log2 instead, which should be more accurate:
math.ceil(math.log2(51))
6.0
numpy also has a log2 method (but is probably overkill for this application).
math.ceil actually returns a float, so if you want an integer you can wrap the expression in int:
int(math.ceil(math.log(51, 2)))
6
By the way, there is also the function bin which you might want to look at. It returns a string containing the binary representation of an integer:
bin(51)
'0b110011'
...but if you don't want to mess around with any of that (thanks again #delnan), you can just use bit_length instead:
(51).bit_length()
6
You could use the ceiling "round up" function before you cast it to an int:
math.ceil(math.log(51)) # round up
You should also have a look at:
math.floor() # round down
math.round()
If you need to save it as a integer type you can cast it to that type:
int()
This question already has answers here:
How do I get the number of elements in a list (length of a list) in Python?
(11 answers)
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 5 months ago.
Hey this is a demo to show some of my classmates an intro to python and coding. The code below should be able to take a list like [0,1] and if run using the average function would return 0.5. When run using a list the function below returns the error 'list' object has no attribute 'len'. How would I get this function to work without removing the len() function
def average(lst):
total = 0
for item in lst:
total += item
averageGrade= total / lst.len()
return averageGrade
How would I also get it to return a float rather than an integer
Change the line
averageGrade= total / lst.len()
to
averageGrade= total / len(lst)
Refer the python docs for the built-in len. The built-in len calculates the number of items in a sequence. As list is a sequence, the built-in can work on it.
The reason it fails with the error 'list' object has no attribute 'len', because, list data type does not have any method named len. Refer the python docs for list
Another important aspect is you are doing an integer division. In Python 2.7 (which I assume from your comments), unlike Python 3, returns an integer if both operands are integer.
Change the line
total = 0.0
to convert one of your operand of the divisor to float.
or by changing
averageGrade= total / lst.len()
to:
averageGrade= total / lst.__len__()
Just change lst.len() to len(list)
Also can refer Progamiz Python - len for more information