ZeroDivisionError Python - python

def do_timelapse(self, cmd):
self.final_fps = input("What will your final edit be at(FPS)?\n")
self.frame_interval = input("What is your Camera's Frame interval(Sec)")
self.original_frame_fps = 1/self.frame_interval
self.small_original = self.original_frame_fps/100
self.percentage = self.final_fps/self.small_original
print self.percentage
How do i resolve this error:
self.percentage = self.final_fps/self.small_original
ZeroDivisionError: integer division or modulo by zero ?

self.frame_interval = input("What is your Camera's Frame interval(Sec)")
it returns an integer, means that you're using python 2. So the next line
self.original_frame_fps = 1/self.frame_interval
probably issues 0 if self.frame_interval > 1
self.small_original = self.original_frame_fps/100
so self.small_original is zero
self.percentage = self.final_fps/self.small_original
so it crashes.
Fix: work with floats:
self.original_frame_fps = 1.0/self.frame_interval
and
self.small_original = self.original_frame_fps/100.0
(of course check that self.frame_interval isn't 0 either)
Alternatives:
use python 3, with just a small fix (and still the check for zero):
self.final_fps = int(input("What will your final edit be at(FPS)?\n"))
self.frame_interval = int(input("What is your Camera's Frame interval(Sec)"))
since input returns strings now (like raw_input does in python 3)
use python 3 division in python 2: add this at the start of your file:
from __future__ import division

My best guess is you are using Python 2.7 which returns an integer value on division of two int. For example:
>>> 5 / 100
0
That is the reason the value of self.small_original is getting set as 0. In order to fix it, you need to type-cast any of the numerator or denominator to float as:
>>> float(5) / 100
0.05 # returns float value
Hence, you need to update the line in your code with:
self.original_frame_fps = 1.0/self.frame_interval
# float here ^
and
self.small_original = self.original_frame_fps/100.0
# float value ^

Related

Display the middle elements of a string

Recently i tried learning to program and after finishing my first tutorial I am trying tackling some problems from codewars.com.
"You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters."
Here is my solution:
def get_middle(n):
if len(n) % 2 == 0:
return n[(len(n)/2) - 1] and n[(len(n)/2)]
else:
return n[(len(n)/2) + 0.5]
Unfortunately when executing the function with for example "abc" I always get:
Traceback (most recent call last) <ipython-input-24-46429b2608e5> in <module>
----> 1 print(get_middle("abc"))
<ipython-input-23-56ccbf5e17f7> in get_middle(n)
3 return n[(len(n)/2) - 1] and n[(len(n)/2)]
4 else:
----> 5 return n[(len(n)/2) + 1]
TypeError: string indices must be integers
I don't understand why I always get the this kind of error. Aren't all my string indices integers?
I know there are are a lot of different solutions out there, but I really would like to know why mine isn't working the way I intended it to.
Thanks in advance!
In Python, there are two kinds of division: integer division and float division.
print(4 / 2)
---> 2.0
print(4 // 2)
---> 2
in Python 2, dividing one integer to an another integer,it comes an integer.
Since Python doesn't declare data types in advance, The interpreter automatically detects the type so you never know when you want to use integers and when you want to use a float.
Since floats lose precision, it's not advised to use them in integral calculations
To solve this problem, future Python modules included a new type of division called integer division given by the operator //
Now, / performs - float division, and
// performs - integer division.
def get_middle(n):
if len(n) % 2 == 0:
return n[(len(n)//2) - 1] and n[(int(len(n)/2))]
else:
return n[int(len(n)/2+ 0.5)]
The issue with our code is that division casts integer to float type automatically and Python starts complaining about it. Simple solution would be to add second / symbol to division or in else case cast it to integer:
def get_middle(n):
if len(n) % 2 == 0:
return n[(len(n)//2) - 1] and n[(len(n)//2)]
else:
return n[int((len(n)/2) + 0.5)]
Try math.floor:
import math
def get_middle(value):
length = len(value)
if length % 2 == 0:
# even length, pick the middle 2 characters
start = length // 2 - 1
end = length // 2 + 1
else:
# odd length, pick the middle character
start = math.floor(length // 2)
end = start + 1
return value[start:end]
A suggestion if you are learning programming, try to break down your steps rather than doing it all in one line, it helps a lot when trying to understand the error messages.
If you divide an odd integer by 2 with the /operator, you get a float. This float should be explicitly converted to an integer when it is used as an indice.

Python function for sums of integers

Wrote a python program that added up numbers from 1 to a given number using the Gauss equation. It worked for 100 and 10 but when I do 3 it says the sum is 4 instead of 6. The equation works out in my head, did I mess up the code?
def numberSum(num):
nim = int(num)
num = (nim/2)*(nim+1)
return num
print numberSum(raw_input())
from __future__ import division
def number_sum(num):
"""
Return sum of 1 .. num
"""
return num * (num + 1) // 2
num = int(raw_input(": "))
print(number_sum(num))
Things I changed:
number_sum should not be responsible for type-casting input; if it expects a number, you should give it some kind of number, not a string.
if num is an int, then either num or num + 1 is even, ie dividing num * (num + 1) by 2 will result in an int. This is not necessarily true of num; therefore you should divide the product by 2, not num, if you want an integer result.
in Python 2.6+, from __future__ import division makes / always return a float result and // always return an int result, consistent with Python 3.x
I suppose you are working with python2, cause by default it applies integer division like other languages. Besides, you can notice this feature in this post Integer division in python 2 and python 3.
To solve your problem you can follow the next approach:
def numberSum(num):
nim = int(num)
return ((nim * 1.0) / 2) * (nim + 1)
print numberSum(raw_input())

How to perform addition and division in python

I want to get the sum of all numbers within a list. My code is shown below; however, I am getting an error when I try to run it:
c = [795557,757894,711411,556286,477322,426243,361643,350722]
for c1 in c:
x = x + c1
I am also trying to divide one number by another. However, the result is always zero:
y=(273591/21247633)*100
In the first case, you need to define x before you use it and use c1 instead of c:
x = 0
c=[795557,757894,711411,556286,477322,426243,361643,350722]
for c1 in c:
x=x+c1
print x
You can try this code online here.
In the second case, you need to use floating point numbers instead of integers:
y=(273591/21247633.0)*100
print y
This is because the result of an integer-integer division in Python 2.x is also an integer. In this case, 273591 รท 21247633 = 0.0128763048571 so the result is rounded down to 0.
This has changed in Python 3.x, and you can enable the same behavior in Python 2.x as follows:
from __future__ import division
y=(273591/21247633)*100
print y
You forgot to initialize x to 0 and this statement should be x = x + c1 and not x = x + c
Probably those numbers are used as integers. Using their float value should help.
y = (float(273591)/21247633)*100
If you want to get a sum of numbers in a list, then use sum:
c = [795557,757894,711411,556286,477322,426243,361643,350722]
x = sum(c)
For the second one, int/int returns an int rounded down, so 273591/21247633 returns 0. Convert one (or all) of the numbers to float and it will work as awaited:
y = (273591. / 21247633.) * 100.

Generate and Enter Value for OEIS Sequence in Python?

This is a rather difficult challenge for me as I am new to Python. How would I write a program in python based off this sequence function:
http://oeis.org/A063655
and does the following:
It asks for the value of the sequence and returns the corresponding number. For example, the number corresponding to the 10th value of the sequence is 7. I'd like to be able to do this for values over 300,000,000.
So, the final product would look like this:
Enter a value: 4
[7]
Any ideas where to start? I have a framework to generate sequences where (x) would be to put a mathematical equation or numbers, but I'm not exactly sure how to go from here or how to implement the "Enter a value" portion:
import math
def my_deltas():
while True:
yield (x)
yield (x)
def numbers(start, deltas, max):
i=start
while i<=max:
yield i
i+=next(deltas)
print(','.join(str(i) for i in numbers((x), my_deltas(),(x))))
If you're looking to have your computer keep track of over 300,000,000 elements of a sequence, if each is a 4 byte integer, you'll need at least 300,000,000 * 4bytes, or over 1.1GB of space to store all the values. I assume generating the sequence would also take a really long time, so generating the whole sequence again each time the user wants a value is not quite optimal either. I am a little confused about how you are trying to approach this exactly.
To get a value from the user is simple: you can use val = input("What is your value? ") where val is the variable you store it in.
EDIT:
It seems like a quick and simple approach would be this way, with a reasonable number of steps for each value (unless the value is prime...but lets keep the concept simple for now): You'd need the integer less than or equal to the square root of n (start_int = n ** .5), and from there you test each integer below to see if it divides n, first converting start_int to an integer with start_int = int(start_int) (which gives you the floor of start_int), like so: while (n % start_int) != 0: start_int = start_int - 1, decrement by one, and then set b = start_int. Something similar to find d, but you'll have to figure that part out. Note that % is the modulus operator (if you don't know what that is, you can read up on it, google: 'modulus python'), and ** is exponentiation. You can then return a value with the return statement. Your function would look something like this (lines starting with # are comments and python skips over them):
def find_number(value):
#using value instead of n
start_int = value ** .5
start_int = int(start_int)
while (n % start_int) != 0:
#same thing as start_int = start_int - 1
start_int -= 1
b = start_int
#...more code here
semiperimeter = b + d
return semiperimeter
#Let's use this function now!
#store
my_val = input("Enter a value: ")
my_number = find_number(my_val)
print my_number
There are many introductory guides to Python, and I would suggest you go through one first before tackling implementing a problem like this. If you already know how to program in another language you can just skim a guide to Python's syntax.
Don't forget to choose this answer if it helped!
from math import sqrt, floor
def A063655(n):
for i in range(floor(sqrt(n)), 0, -1):
j = floor(n / i)
if i * j == n:
return i + j
if __name__ == '__main__':
my_value = int(input("Enter a value: "))
my_number = A063655(my_value)
print(my_number)
USAGE
> python3 test.py
Enter a value: 10
7
> python3 test.py
Enter a value: 350000
1185
>

Reading values with raw_input in Python

I am trying to do integration in Python but whenever I key in a value my outputs always results in 0. What the reason?
E.g.:
def main():
eq_of_form()
value_of_a()
value_of_b()
value_of_c()
value_of_m()
value_of_n()
value_of_x()
area_under_graph()
def eq_of_form():
print "Eq of the form y = ax^m + bx^n + c " + ":"
def value_of_a():
return raw_input("Enter value for a \n")
def value_of_b():
return raw_input("Enter value for b \n")
def value_of_c():
return raw_input("Enter value for c \n")
def value_of_m():
return raw_input("Enter value for m \n")
def value_of_n():
return raw_input("Enter value for n \n")
def value_of_x():
return raw_input("Enter a value for x to find " +
"value of y and the gradient at that point \n " + "x = ")
def area_under_graph():
y = (int(value_of_a())*int(value_of_x())**(int(value_of_m())+1))/((int(value_of_m())+1))
// * 2nd part.This works for me(:
// + (int(value_of_b())) * (int(value_of_x())**
// (int(value_of_n())+1))/(int(value_of_n())+1) + ((int(value_of_c())*int(value_of_x())))
print y
main()
(* Note: the eq under the area_under_graph() function is only half of it because the other half kind of work so I did not post it:))
For the top code, I tried inputting the values here: (maybe you can try using the same(: )
a = 1
b = 2
c = 1
m = 2
n = 1
x = 1
I am supposed to get 7/3 which is 2.333, but I end up getting 2. The problem appears to lie in the first part of the eq.
Sorry for the newbie question.
Your code at the start is wrong. You need to assign your variables after you read the user input:
value_of_a()
should be:
a = value_of_a()
It is also unnecessary to write a separate function for inputting each variable. You could instead have a function that takes a parameter:
def get_user_value(name):
return raw_input("Enter value for %s\n" % name)
a = get_user_value("a")
b = get_user_value("b")
# etc..
But then you ignore all these values and read them again inside the area_under_curve() method. This is probably not what you intend to do. Furthermore inside this method you assume that all parameters are integers. If you are using Python 2.5 the division here is integer division:
m1/m2
This could return 0 when the result was actually supposed to be a non-integer like 0.125. You need to use floats instead of integers to do the calculation. You can do this in Python 2.5 using float(m). In Python 3.0 the division operator does what you want by default.
/ does Integer division in Python2, this means a/b is the biggest integer c with c*b <=a, so 7/3 is indeed 2. You want floats, so you need to use them .. replace all the int with float in your code.
You should probably take another look at functions too ... you code can be much much shorter :-)
In Python 2.x, dividing an integer by another integer results in an integer. Either use from __future__ import division, or turn one of the integers into a float by passing it to float().
The issue is that you're using integer arithmetic - see all those int calls you've got everywhere. Integer arithmetic (in Python 2.x) will only ever return integers, so you'll never get 2.33, only 2.
Use float() instead of int() and things should work.

Categories