Math programming with python - python

So I'm pretty new to programming and I don't understand how to do this problem.
Egg cartons each hold exactly 12 eggs. Write a program which reads an integer number of eggs from input(), then prints out two numbers: how many cartons can be filled by these eggs, and how many eggs will be left over. I would really appreciate the help!

At first, what you are looking for is the modulo operator and the function math.floor()
Modulo
from wikipedia:
In computing, the modulo operation finds the remainder after division of one number by another (sometimes called modulus).
for example:
12%12=0
24%12=0
25%12=1
this does fit your needs for the eggs that are leftover.
Math.floor()
returns the largest following integer.
eg.:
Math.floor(13/2)
would be the same as
Math.floor(6.5)
and result in 6.
This function should solve your problem with the fully filled egg cartons.
Hint
remember to import floor() properly.
from math import floor
First, try to figure the rest out on your own.
You shouldn't look at this until your code is done.
Either way I'm not your mom, if you wanna die dumb I tried to prevent it.
https://github.com/AiyionPrime/EggCartons
One last thing.
It does not matter wether your attempts to solve a problem were stupid or failed hard.
But if you ever expect an answer to one of your problems you should explain what you tried.
We're not here to solve your problems, but to help you understand to do it.

I remember that text. It comes from a site for exercising with Python coding.
Its name is Computer Science Circles, if I remember correctly.
Anyway, the correct answer at that specific exercise is:
eggs = input() #Reads imput, assigning it to the "eggs" variable
eggs = int(eggs) #Converts the "eggs" variable into an int
print(eggs // 12) #Performs a division, showing the result and ignoring the remainder, giving you the exact number of cartons that can be filled by the "eggs" variable
print(eggs % 12) #Performs a second division, this time showing only the remainder, giving you the exact number of eggs that will be left over

Related

how to get real valule in R [duplicate]

I'm just learning R, so please forgive what I'm sure is a very elementary question. How do I take the real part of a complex number?
If you read the help file for complex (?complex), you will see a number of functions for performing complex arithmetic. The details clearly state
The functions Re, Im, Mod, Arg and Conj have their usual interpretation as returning the real part, imaginary part, modulus, argument and complex conjugate for complex values.
Therefore
Use Re:
Re(1+2i)
# 1
For the imaginary part:
Im(1+2i)
# 2
?complex will list other useful functions.
Re(z)
and
Im(z)
would be the functions you're looking for.
See also http://www.johnmyleswhite.com/notebook/2009/12/18/using-complex-numbers-in-r/

Setting number of decimals for print via user input

I'm dabbling around in Python and wrote a short program which returns the square root of a number provided by the user. The output, respectively the print line, looks like this:
print 'The square root of %d is %.2f' % (x, math.sqrt(x))
with x as the user input.
My question: how could i adjust the results number of decimals via user input?
Thanks a lot!
First get input for how many decimal places you want it by:
y = int(raw_input("How many decimal places? "))
Then you'll probably want to use str.format to make your print statement easier:
print 'The square root of {} is {:.{dec}f}'.format(x, math.sqrt(x), dec=y)
I might be (I probably am) wrong here, but I'm not sure if you can do what you're trying to achieve with the % operator. % tends to be looked at as a deprecated operator anyway, especially with the majority of people transitioning to Python 3. But, since you're using Python 2, thankfully str.format is in Python 2.7.

How do I fix this OverflowError?

I keep getting a "OverflowError: math range error". No matter what I input, the result is the same. I'm running Python 3.3, and it's finding the problem at the last line. How do I fix this? (Also, I don't want to hear anything about my overuse of parentheses. It is my preference for there to be this many.):
import math
a=float(input('a=?'))
b=float(input('b=?'))
c=float(input('c=?'))
d=float(input('d=?'))
critical_point_n=((-2*b)-math.sqrt(abs((4*(math.pow(b, 2)))-(12*a*c))))/(6*a)
first_root=critical_point_n-1
if first_root==0 and c==0:
first_root+=(-0.01)
for x in range(10):
first_root=first_root-((a*(math.pow(first_root, 3)))+(b*(math.pow(first_root, 2))+(c*first_root)+d)/(3*(a*(math.pow(first_root, 2))))+(2*(b*first_root))+c)
I know you don't want to hear about your excessive use of parenthesis, but the problem is that you have the parenthesis in the wrong places. With the sheer number of parenthesis you used, it took a while to find the problem.
I think the following code is much cleaner, easier to debug, and vastly easier to maintain in the future. I also included what I think is the corrected version of your one-liner.
import math
a=float(input('a=?'))
b=float(input('b=?'))
c=float(input('c=?'))
d=float(input('d=?'))
critical_point_n=((-2*b)-math.sqrt(abs((4*(math.pow(b, 2)))-(12*a*c))))/(6*a)
first_root=critical_point_n-1
if first_root==0 and c==0:
first_root+=(-0.01)
for x in range(10):
f = a*first_root**3 + b*first_root**2 + c*first_root + d
fp = 3*a*first_root**2 + 2*b*first_root + c
first_root = first_root - (f/fp)
#first_root=first_root-(((a*(math.pow(first_root, 3)))+(b*(math.pow(first_root, 2))+(c*first_root)+d)))/((3*(a*(math.pow(first_root, 2))))+(2*(b*first_root))+c)
print(first_root)
You are overflowing the internal representation of floats. Use sys.float_info to check your system's limits for floating point numbers. http://docs.python.org/3.3/library/sys.html#sys.float_info
I recommend trying out your operations by "hand" on wolframalpha to see the magnitude of the actual values. http://www.wolframalpha.com/
The math range of functions work on doubles... so you're out of range for that - re-write as normal Python floats which will scale as needs be, or look at using decimal.Decimal which also has sqrt, power etc.. functions: http://docs.python.org/2/library/decimal.html

Implement hashing function with collision

For a demo project, I want to create a hashing function with a very high probability of collision. Something simple is fine since the aim of the project is NOT security - but to demonstrate hash collisions.
Can anyone help me get started with an algorithm, or a sample implementation, or just point me in the right direction?
I am doing this in Python, though maybe that should not matter.
You could use the sum of the characters in a string. It's the first hash function I was taught back when I was first learning BASIC in high school, and I ran into the collision problem right away and had to figure out how to deal with it.
sum(ord(c) for c in text)
Transpositions are easily achieved by swapping strings or even words. For more fun you could also make it case-insensitive:
sum(ord(c) for c in text.lower())
I'll even give you a sample collision for that last one: Jerry Kindall -> Dillan Kyrjer :-)
One algorithm that comes to mind is hashing using the first letter of the string.
Something like
hash[ord(text[0]) - ord('a')] = text
So anything starting with the same letter will be hashed together. As you can see, that's a lot of collisions.
Another idea is to hash according to the length of the string.
hash[len(text)] = text
You can use what hayden suggests in a comment above, and cause further collisions by taking the length modulo some number. Eg.
hash[len(text) % 5] = text

Is Python reevaluating arithmetic operations with bignums each time the resut is used?

Okay, I was trying to throw in some really large number evaluation on python - of the order of 10^(10^120)- which i then realized was quite huge. Anyways, I then receded to 10**10**5 and 10**10**6. Checking the time difference of the two brought me to this somewhat strange finding which I could see as an inefficiency.
The finding was that when I tried cProfile.run("x=10**10**6") it took 0.3s and cProfile.run("print 10**10**6") took 40s.
Then I tried x= 10**10**6 which took almost no time but thereafter every time that I interpreted x (x followed by enter) it would take a really long time (40s I suppose). So, I am assuming that every time that I interpret x it calculates the entire value over again.
So my question is: isn't that extremely inefficient? Say I had declared some variable in a module, x= 10**10, and every time I would reference x the python interpreter would compute the value of 10**10 over and over again ?
Gory details would be much appreciated.
Python can calculate extremely large numbers using binary, but to turn that back into digits that can be displayed is a lot of work.
For example: (and what quite a few Euler projects ask) -
What is the sum of all the digits of, say, 2 ** 32768
Python can use BigNum's to calculate that result as a number pretty much straight anyway, but as soon as you do:
sum(int(c) for c in str(my_big_number)) # ouch - that's a lot of digits to produce and store
So that's what's happening when you type (then press enter) the variable name/print the variable name, it's performing a conversion.
The value is not being recalculated each time you print it, the long delay you see is the cost of converting the large number into a string for displaying.

Categories