Fermat's little Theorem python - python

i am trying to implement Ferment's little Theorem via python. The value that returns does not give me a prime however. Any help is appreciated.
Apologies, the theorem states that in which for a random number of of times if a number is prime then any number generated less then it would give pow(a,value,x) == 1. The code below is an implementation of it.
The purpose of the code would be for function generate bit to create a 16 bit integer and run it via the theorem to prove if its a prime or not, if its a prime,return the value, if not call the function generatebit() again. Thank you for your time taken
import random
def generatebit():
x = random.getrandbits(16)
x = int(x)
if little(x):
return x
def little(x):
value = x -1
for i in xrange(50000):
# check for a total of 50000 times to reduce chances
a = random.getrandbits(15)
if pow(a,value,x) != 1:
generatebit()
break
return True
a=generatebit()
print a

Not knowing what the theorem is (see my comment), I can still tell you that there are some issues in your code.
you first call generatebits, which generates a random number. then if little(x), you return that value. Since however little(x) is always true, what this code does is create a random value and return it
Whatever happens within you for loop is totally without effect. all you do is assign a value to a variable a that never gets read, and call a function that returns a value you don't read

Related

i was watching Reducible's video about recursion and saw this code and i cant understand how it works could someone please explain?

# function counts number of ways you can
# partition n objects
# using parts up to m (assume m>=0)
n=int(input('enter n '))
m=int(input('enter m '))
def count(n, m):
if n==0:
return 1
elif m==0 or n<0:
return 0
else:
return count(n-m , m)+count(n , m-1)
print(count(n,m))
I don't understand the inputs and outputs of every function, I want to learn this and I am getting discouraged I hope someone could help I especially don't understand how it returns one value from this function, not two.
(this is my first post I don't know if it's the correct format).
I don't understand the inputs and outputs of every function
The inputs are the total number of objects n, and the maximum size of the partitions that it can be split into m.
The output is the count of the number of possible partitions fitting that criteria.
For instance, if n == 3 and m == 2, the possible partitions are 3 partitions with 1 item each, or 2 partitions with 2 and 1 items. So the output is 2.
I especially don't understand how it returns one value from this function, not two
The base cases clearly each return just a single value. One of them returns 1, the other returns 0.
If it doesn't return immediately from one of the base cases, it calls itself recursively twice, with smaller values of one of the parameters. So each recursive call gets closer to one of the base cases. When these return, it adds the results together, so it's only returning one value, not both values.

how can I verify that this hash function is not gonna give me same result for two diiferent strings?

Consider two different strings to be of same length.
I am implementing robin-karp algorithm and using the hash function below:
def hs(pat):
l = len(pat)
pathash = 0
for x in range(l):
pathash += ord(pat[x])*prime**x # prime is global variable equal to 101
return pathash
It's a hash. There's, by definition, no guarantee there will be no collisions - otherwise, the hash would have to be as long as the hashed value, at least.
The idea behind what you're doing is based in number theory: powers of a number that is coprime to the size of your finite group (which probably the original author meant to be something like 2^N) can give you any number in that finite group, and it's hard to tell which one these were.
Sadly, the interesting part of this hash function, namely the size limiting/modulo operation of the hash, has been left out of this code – which makes one wonder where your code comes from. As far as I can immediately see, has little to do with Rabin-Karb.

Exponentially distributed random generator (log function) in python?

I really need help as I am stuck at the begining of the code.
I am asked to create a function to investigate the exponential distribution on histogram. The function is x = −log(1−y)/λ. λ is a constant and I referred to that as lamdr in the code and simply gave it 10. I gave N (the number of random numbers) 10 and ran the code yet the results and the generated random numbers gave me totally different results; below you can find the code, I don't know what went wrong, hope you guys can help me!! (I use python 2)
import random
import math
N = raw_input('How many random numbers you request?: ')
N = int(N)
lamdr = raw_input('Enter a value:')
lamdr = int(lamdr)
def exprand(lamdr):
y = []
for i in range(N):
y.append(random.uniform(0,1))
return y
y = exprand(lamdr)
print 'Randomly generated numbers:', (y)
x = []
for w in y:
x.append((math.log((1 - w) / lamdr)) * -1)
print 'Results:', x
After viewing the code you provided, it looks like you have the pieces you need but you're not putting them together.
You were asked to write function exprand(lambdr) using the specified formula. Python already provides a function called random.expovariate(lambd) for generating exponentials, but what the heck, we can still make our own. Your formula requires a "random" value for y which has a uniform distribution between zero and one. The documentation for the random module tells us that random.random() will give us a uniform(0,1) distribution. So all we have to do is replace y in the formula with that function call, and we're in business:
def exprand(lambdr):
return -math.log(1.0 - random.random()) / lambdr
An historical note: Mathematically, if y has a uniform(0,1) distribution, then so does 1-y. Implementations of the algorithm dating back to the 1950's would often leverage this fact to simplify the calculation to -math.log(random.random()) / lambdr. Mathematically this gives distributionally correct results since P{X = c} = 0 for any continuous random variable X and constant c, but computationally it will blow up in Python for the 1 in 264 occurrence where you get a zero from random.random(). One historical basis for doing this was that when computers were many orders of magnitude slower than now, ditching the one additional arithmetic operation was considered worth the minuscule risk. Another was that Prime Modulus Multiplicative PRNGs, which were popular at the time, never yield a zero. These days it's primarily of historical interest, and an interesting example of where math and computing sometimes diverge.
Back to the problem at hand. Now you just have to call that function N times and store the results somewhere. Likely candidates to do so are loops or list comprehensions. Here's an example of the latter:
abuncha_exponentials = [exprand(0.2) for _ in range(5)]
That will create a list of 5 exponentials with λ=0.2. Replace 0.2 and 5 with suitable values provided by the user, and you're in business. Print the list, make a histogram, use it as input to something else...
Replacing exporand with expovariate in the list comprehension should produce equivalent results using Python's built-in exponential generator. That's the beauty of functions as an abstraction, once somebody writes them you can just use them to your heart's content.
Note that because of the use of randomness, this will give different results every time you run it unless you "seed" the random generator to the same value each time.
WHat #pjs wrote is true to a point. While statement mathematically, if y has a uniform(0,1) distribution, so does 1-y appears to be correct, proposal to replace code with -math.log(random.random()) / lambdr is just wrong. Why? Because Python random module provide U(0,1) in the range [0,1) (as mentioned here), thus making such replacement non-equivalent.
In more layman term, if your U(0,1) is actually generating numbers in the [0,1) range, then code
import random
def exprand(lambda):
return -math.log(1.0 - random.random()) / lambda
is correct, but code
import random
def exprand(lambda):
return -math.log(random.random()) / lambda
is wrong, it will sometimes generate NaN/exception, as log(0) will be called

How to multiply without the * sign using recursion?

so as homework for a programming class on python we're supposed to multiply to integers (n,m) with each other WITHOUT using the * sign (or another multiplication form). We're supposed to use recursion to solve this problem, so i tried just adding n with itself, m number of times. I think my problem is with using recursion itself. I have searched on the internet for recursion usage, no results. Here is my code. Could someone point me in the right direction?
def mult(n,m):
""" mult outputs the product of two integers n and m
input: any numbers
"""
if m > 0:
return n + n
return m - 1
else:
return 1
I don't want to give you the answer to your homework here so instead hopefully I can provide an example of recursion that may help you along :-).
# Here we define a normal function in python
def count_down(val):
# Next we do some logic, in this case print the value
print(val)
# Now we check for some kind of "exit" condition. In our
# case we want the value to be greater than 1. If our value
# is less than one we do nothing, otherwise we call ourself
# with a new, different value.
if val > 1:
count_down(val-1)
count_down(5)
How can you apply this to what you're currently working on? Maybe, instead of printing something you could have it return something instead...
Thanks guys, i figured it out!!!
i had to return 0 instead of 1, otherwise the answer would always be one higher than what we wanted.
and i understand how you have to call upon the function, which is the main thing i missed.
Here's what i did:
def mult(n,m):
""" mult outputs the product of two integers n and m
input: any numbers
"""
if m == 0:
return 0
else:
return n + mult(n, m - 1)
You have the right mechanics, but you haven't internalized the basics you found in your searches. A recursive function usually breaks down to two cases:
Base Case --
How do you know when you're done? What do you want to do at that point?
Here, you've figured out that your base case is when the multiplier is 0. What do you want to return at this point? Remember, you're doing this as an additive process: I believe you want the additive identity element 0, not the multiplicative 1.
Recursion Case --
Do something trivial to simplify the problem, then recur with this simplified version.
Here, you've figured out that you want to enhance the running sum and reduce the multiplier by 1. However, you haven't called your function again. You haven't properly enhanced any sort of accumulative sum; you've doubled the multiplicand. Also, you're getting confused about recursion: return is to go back to whatever called this function. For recursion, you'll want something like
mult(n, m-1)
Now remember that this is a function: it returns a value. Now, what do you need to do with this value? For instance, if you're trying to compute 4*3, the statement above will give you the value of 4*2, What do you do with that, so that you can return the correct value of 4*3 to whatever called this instance? You'll want something like
result = mult(n, m-1)
return [...] result
... where you have to fill in that [...] spot. If you want, you can combine these into a single line of code; I'm just trying to make it easier for you.

Need help fixing/refining a while loop sum calculator in python [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Keep in mind that I am still very new to python coding as I am only just into chapter 5 of my python coding class. Keeping that in mind, I am attempting to create a sum calculator using a "while loop" to continue until the user enters a negative number instead of a positive number.
In case I am not entirely clear in my description of my question I will post the exact homework problem here:
Chapter 5, page 200, #8
Sum of Numbers
Write a program with a while loop that asks the user to enter a series of positive numbers. The user should enter a negative number to signal the end of the series. After all the positive numbers have been entered, the program should display their sum.
Now for the code that I have written so far:
def main():
number = float(input('Please enter in a positive number: '))
while number > 0:
positiveNumber()
while number < 0:
calculateTotal()
printTotal()
def positiveNumber():
number = float(input('If you are finished please enter a negative number.' + \ 'Otherwise, enter another positive number: '))
while number > 0:
positiveNumber()
while number < 0:
calculateTotal()
printTotal()
def calculateTotal():
total = 0 + number
def printTotal():
print('The sum of your numbers is: ', total)
main()
In line 11, I have the "+ \" sign there because I wanted to make an enter space there in order to have a cleaner looking text, but that does not seem to work.
I apologize if this question seems "nooby" but I need help making a cleaner/working sum calculator. I would greatly appreciate it if someone can take a look at this code and hopefully help me improve it. Thank you!
Final Edit:
Thank you all for the informative answers! I learned alot (for a "newbie" =]). I used Talon876's answer for my calculator. Thanks again everyone!
If you want a single string to be printed on multiple lines, put a \n in the string.
For example,
print "This is on the first line\nThis is on the second line"
would output
This is on the first line
This is on the second line
It looks like you're mixing a while loop with recursion (calling a method from within itself). I would suggest using a single while loop and an input variable to check for the breaking condition (the input is < 0)
It would look something like this:
sum = 0
number = float(input('Please enter in a positive number: '))
while number > 0:
sum = sum + number
number = float(input('If you are finished please enter a negative number.' + \ 'Otherwise, enter another positive number: ')) #fix this line using the information from the first part of the answer
This will loop until the user inputs a negative number, or 0. If you want to accept 0 as a positive number, change the while condition to number > -1
You can't update a global variable in a python function without explicitly declaring it as a global. Observe:
a = 1
def foo():
a = a + 6 #creates a new variable (a) that is confined to the "foo" namespace.
#Note that it still uses a from the global namespace on the Right hand side
#This is because python looks for a in the "foo" namespace first. When
#it isn't found there, it looks in the global namespace. However, python
#WON'T ASSIGN to something in the global namespace without being told
#to explicitly
print (a)
foo() # 7
print (a) # 1
def foo():
global a #Tell python that it is OK to assign to variable "a" in the global namespace.
a = a + 6
print (a)
foo() # 7
print (a) # 7
However, with this great power comes great responsibility. Many people will tell you to never use global variables. In a lot of ways, they're correct because just about anything you can accomplish with global variables can be accomplished more cleanly using some other method. My hope in writing this is not to convince you to use globals, but to help you understand one of the errors in your code.
One thing that you may want to try is to have your function accept the input number as an argument along with the total to this point and then return the new total.
Good luck!
the problem is 1.you have not declared the variables you are using in function as global,to note the changes being made to them
2.you dont need while loops if you are implementing it by calling a function recursively!you need checking condition lik "if & else"
here is an easy implementation of problem with while loop:
def main():
total=0
number = float(input('Please enter in a positive number: '))
while(number>0):
total=total+number
number = float(input('Please enter in a positive number to continue or a negative no. to stop: '))
print('The sum of your numbers is: %d'% total)
main()
I think you're looking for something like this? But I don't know what style constraints you are required to use.
number = float(input('Please enter in a positive number: '))
to_sum = []
while number > 0:
to_sum.append(number)
number = float(input('If you are finished please enter a negative number.\n' +
'Otherwise, enter another positive number: '))
print('The sume of your numbers is: ', sum(to_sum))
Please note that because the statement you are trying to break onto multiple lines is already within ()'s, you don't need the . You can just break the line.
Did the assignment require you to use so many crazy functions? Also, which version of Python are you using?
One thing you need to learn is how to break up a program into functions. Some problems are better handled by a single block of code than by being split up, and I think this is one of them.
You need to calculate a single sum. You can handle that with a single variable, to which you add more numbers as the user enters them. Your code should be designed around this variable. If you try to split the code up into functions, you either need to use a global variable (not recommended!), or you need to pass the variable around among the functions, or perhaps you could put the variable into an object and then make the functions be "method" functions on the object. But simplest is just to write some code that uses the variable, and make all that code be a single block of code (either one function, or even just the code in your Python program).
Here is a solution:
sum = 0.0 # initial value; we will add values to this
print('Welcome to this program')
while True:
s = input('User: enter data value or a negative number to stop')
x = float(s)
if x < 0:
break
sum += x # add this value to update the sum
print('Here is your sum: {}'.format(sum))
So, here is what is good about the above code. All the places that need to work with the variable sum are all close together, and we can see them. We don't need to declare sum global, because we don't have multiple functions trying to all use it.
Look at that code, and ask yourself: would it be simpler or cleaner if we carved it up into multiple functions? If not, then don't do it.
The only tricky thing here is that we used while True: for the loop. This is because we want to do something (get input), then based on the result, decide whether to break out of the loop or continue, and then finally do something else based on the decision (update the sum).
It's possible to rewrite this to use a "flag" variable, and make the loop while flag: but I don't think it is cleaner:
sum = 0.0 # initial value; we will add values to this
print('Welcome to this program')
continue_loop = True
while continue_loop:
s = input('User: enter data value or a negative number to stop')
x = float(s)
if x < 0:
continue_loop = False
else:
sum += x # add this value to update the sum
print('Here is your sum: {}'.format(sum))
Do you think it is clearer to have the continue_loop flag variable? Some textbooks say you should write your code this way, because they think it is a sin to use break to exit a loop in the middle; they think loops should only exit from the usual place (which, for a while loop, is the top).
What if you really wanted to use functions? Well, you could, but you still shouldn't use a global variable. In fact, if you are writing a "functional" solution, you don't need a sum variable at all!
Here is a functional solution.
def ask_and_sum():
s = input('Hey dude enter a value or a negative to stop')
x = float(s)
if x < 0:
return 0
else:
return x + ask_and_sum()
print('Welcome to this program')
print('Your sum is: {}'.format(ask_and_sum()))
Instead of an explicit loop, this uses "tail recursion", where a function ends with another call to itself. In this case, I personally prefer the explicit loop. What do you think?
P.S. This problem is so simple that it was hard to discuss it without giving you the full answer. I apologize for that. But even if you just copy the code, please look at it, and think about it, and make sure you understand it.

Categories

Resources