I am trying to produce code that will first find me all the perfect squares under modulos p, in a function perfectsq(p).
With that list of perfect squares. I want to find all solutions of the equation y^2=x^3+Ax+B. I am doing this by using the list in perfectsq(p) to check that m=x^3+Ax+B is in that list. Can someone tell me why this code isn't compiling?
def perfectsq(p):
x=[]
for i in range(1,p):
m=(i**2)%p
x.extend(m)
i+=1
def ellipticpt(a, b, p):
x=perfectsq(p)
if 4*(a**3)+27*(b**2) != 0:
for i in range(0,p):
m=(i**3+a*i+b)%p
if m in x:
i=x.index(m)+1
print (m,i)
i+=1
else:
i+=1
else:
print "Error"
perfectsq x.extend(m) TypeError: 'int' object is not iterable
You can't .extend() a list with a single number argument, it's for extending a list with another list. Use .append() to add to the end of a list instead.
Also perfectsq() doesn't return anything
Try:
def perfectsq(p):
x=[]
for i in range(1,p):
m=(i**2)%p
x.append(m)
i+=1
return x
def ellipticpt(a, b, p):
x=perfectsq(p)
if 4*(a**3)+27*(b**2) != 0:
for i in range(0,p):
m=(i**3+a*i+b)%p
if m in x:
i=x.index(m)+1
print (m,i)
i+=1
else:
i+=1
else:
print "Error"
Related
def list_num_checker(num_list):
for x in num_list:
if x%2==0:
return x
else:
continue
I just began learning Python and this is the code I have written to create a function to return all the even values in a list. However, It breaks down after checking the first even number.E.g.
list_num_checker([1,2,3,4,5,6])
2
Any and all help is appreciated.
return will cause a function to exit... if you use yield you can make it a generator
def list_num_checker(num_list):
for x in num_list:
if x%2==0:
yield x # yield makes this a generator instead
# else: # you don need the else
# continue
for evennum in list_num_checker([1,2,3,4,5,6,7,8]):
print(evennum)
you could also make a list comprehension
print([x for x in num_list if x%2 == 0])
or you could use the builtin filter function
def is_even(num):
return num % 2 == 0
list(filter(is_even,num_list)) # its a generator so you need to call list on it
I think you can use yield instead of return since return will break the for loop and immediately returns the give value
def list_num_checker(num_list):
for x in num_list:
if x%2==0:
yield x
else:
continue
divisible2 = list(list_num_checker([1,2,3,4,5,6]))
Some possible alternative approaches would be to use list comprehension or filter
def list_num_checker(num_list):
return [x for x in num_list if x % 2 == 0]
def list_num_checker(num_list):
return filter(lambda x: x % 2 == 0, num_list)
return will immediately terminate the function. To produce multiple values in one function, use yield instead.
def list_num_checker(num_list):
for x in num_list:
if x%2==0:
yield x
else:
continue
I need to write a function that will print biggest odd number from three input arguments.
Here is my code.
def oddn(x,y,z):
odd_number_keeper = []
for item in x,y,z:
global odd_number_keeper
if item % 2==1:
odd_number_keeper = [item]
return max(odd_number_keeper)
else:
print 'No odd number is found'
My codes seem is not working. Any ideas how i can modify this code?
A few changes would be needed:
def oddn(x,y,z):
odd_number_keeper = []
for item in [x,y,z]:
if item % 2==1:
odd_number_keeper.append(item)
if not odd_number_keeper:
print 'No odd number is found'
return
return max(odd_number_keeper)
Iterate over the values x, y and z and add the odd numbers to odd_number_keeper. If there are any numbers then you return the max() of the elements in this list of odd numbers. If there are no odd numbers then you print the message and return (without a result, as there is no number to return).
You have to first filter all odd-numbers and then call max:
def oddn(x,y,z):
odd_numbers = [item for item in (x,y,z) if item%2==1]
return max(odd_numbers)
or in short:
def oddn(*numbers):
return max(x for x in numbers if x % 2 == 1)
also it is not good practice, if you want to print some message on error:
def oddn(*numbers):
try:
return max(x for x in numbers if x % 2 == 1)
except ValueError:
print 'No odd number is found'
return None
You are not finding the biggest odd number from the list, instead, you are finding the first odd number and returning that. The issue is in the lines -
odd_number_keeper = [item]
return max(odd_number_keeper)
you first need to be appending item to the list, insteading of making odd_number_keeper the list with only that item.
Secondly, the return statement should be at the end of the function, not inside the for loop.
You need a code something like -
def oddn(x,y,z):
odd_number_keeper = []
for item in x,y,z:
if item % 2==1:
odd_number_keeper.append(item)
return max(odd_number_keeper)
You are resetting odd_number_keeper each time. You probably meant
odd_number_keeper += [item]
Also the return and print should be at the end of (outside) the for loop.
(please fix indentation to be clearer on your intent).
Solving it using filter. Doing it in pythonic way.
def oddn(a, b, c):
final = []
final.append(a)
final.append(b)
final.append(c)
result = filter(lambda x: x % 2 != 0, final)
return max(result)
im new..
my script is pretty long so I'll write down the specific parts.
str= ''
#str is a long DNA sequence
def FIND_UPPER(str):
global x
x=str.upper()
y=0
while y>(-1):
y=x.find('CTTTGATTCCT')
z=x[y+11:y+22]
x=x[y+23:]
variability(z)
#variability is another function
FIND_UPPER(str)
and then I get this message:
list indices must be integers, not str
about those lines:
variability(z)
FIND UPPER(str)
How can I fix this?
thanks
edit:
this is variability:
A=[0]*10
C=[0]*10
T=[0]*10
G=[0]*10
def variability(z):
for i in z:
if i=='A':
A[i]=A[i]+1
i=i+1
elif i=='T':
T[i]=T[i]+1
i=i+1
elif i=='C':
C[i]=C[i]+1
i=i+1
elif i=='G':
G[i]=G[i]+1
i=i+1
return G
return C
return T
return A
I fixed it, can u tell me if I got u right?
:
def variability(z):
for i in range(len(z)):
if i=='A':
A[i]=z[i]
A[i]+=1
i+=1
elif i=='T':
T[i]=z[i]
T[i]+=1
i+=1
elif i=='C':
C[i]=z[i]
C[i]+=1
i+=1
elif i=='G':
G[i]=z[i]
G[i]+=1
i+=1
return G,C,T,A
def variability(z):
for i in z:
if i=='A':
A[i]=A[i]+1
i=i+1
Assume i == 'A', then A[i] is actually translated to A['A'] which returns:
list indices must be integers, not str
Which means you can't access a list by a string index, list indices are integers.
Moreover, Python doesn't support multiple return statements:
return G
return C
return T
return A
This will always return G
If you want to return all of these values, then replace it with:
return G,C,T,A
The above return statements returns a tuple consists G,C,T,A
If you want to return just one, place each return statement inside your elif clauses.
In the loop you have to do something like:
for i in range(len(z)):
letter = A[i]
If you iterate over range function result, "i" will take numeric values. If you iterate over the string i will take each character of the string
An then compare variable "letter"
if letter == 'A':
...
Be careful in the variability function, only the value in the first return statement will be returned.
I'm wondering how to do the following in Python.
If I have a function with a for loop, it is possible to with an if statement to skip certain numbers.
This is an implementation of fisher-yates d got from activestate.com.
import random
def shuffle(ary):
a=len(ary)
b=a-1
for d in range(b,0,-1):
e=random.randint(0,d)
if e == d:
continue
ary[d],ary[e]=ary[e],ary[d]
return ary
Now continue simply goes to the next value for d. How can I, instead of doing continue, rerun the function with the original parameter ary?
Note that the function is just some example code, I'm curious on how to do this in general.
Also, maintaining a copy of the array might not be possible if the list is big, so thats not really a solution imo.
This is a common recursive pattern. However, your case is a little different than usual because here you need to make a copy of your input list to use when you recurse if the shuffling fails.:
import random
def shuffle(ary):
initial = ary[:]
a=len(ary)
b=a-1
for d in range(b,0,-1):
e=random.randint(0,d)
if e == d:
return shuffle(initial)
ary[d],ary[e]=ary[e],ary[d]
return ary
ary = [1,2,3,4,5,6]
print shuffle(ary)
Also note that Wikipedia gives a (non-recursive) python implementation of the very similar Sattolo's algorithm.
from random import randrange
def sattoloCycle(items):
i = len(items)
while i > 1:
i = i - 1
j = randrange(i) # 0 <= j <= i-1
items[j], items[i] = items[i], items[j]
return
If I read the article correctly, to re-acquire Fisher-Yates, you'd just do one simple change:
from random import randrange
def FisherYates(items):
i = len(items)
while i > 1:
i = i - 1
j = randrange(i+1) # 0 <= j <= i
items[j], items[i] = items[i], items[j]
return
def function(list):
len(list)-1
for i in range(len(list)-1,0,-1):
e= randint(0,i)
while e > i:
e= randint(0,i)
"do something to the list"
return array
?
def function(list):
for i in (a for a in range(len(list)-1,0,-1) if randint(0,a) > a):
#do something with list
#do something else with remainder.
Not exactly what you asked for. Just wanted to remind you of this possibility.
you can copy the parameter to a temp variable. then call the function with the temp variable and use return;
def function(list):
listCopy = list;
len(list)-1
for i in range(len(list)-1,0,-1):
e= randint(0,i)
if e > i:
return function(listCopy)
else
"do something with the list"
return array
I know there are easier ways to create a function which gives you the largest number in a list of numbers but I wanted to use recursion. When I call the function greatest, i get none. For example greatest([1,3,2]) gives me none. If there are only two elements in the list, I get the right answer so I know the problem must be with the function calling itself. Not sure why though.
def compare(a,b):
if a==b:
return a
if a > b:
return a
if a < b:
return b
def greatest(x):
if len(x)==0:
return 0
i=0
new_list=[]
while i< len(x):
if len(x)-i>1:
c=compare(x[i],x[i+1])
else:
c=x[i]
new_list.append(c)
i=i+2
if len(new_list)>1:
greatest(new_list)
else:
return new_list[0]
print greatest([1,3,2])
This line:
if len(new_list)>1:
greatest(new_list) # <- this one here
calls greatest but doesn't do anything with the value it returns. You want
return greatest(new_list)
After fixing that, your function seems to behave (although I didn't look too closely):
>>> import itertools
>>> for i in range(1, 6):
... print i, all(max(g) == greatest(g) for g in itertools.product(range(-5, 5), repeat=i))
...
1 True
2 True
3 True
4 True
5 True
A simple recursion can be like this :
from random import *
def greatest(x,maxx=float("-inf")):
if len(x)>0:
if x[0] > maxx:
maxx=x[0]
return greatest(x[1:],maxx)
else:
return maxx
lis=range(10,50)
shuffle(lis)
print greatest(lis) #prints 49