Sequence function error? - function

I'm getting an error on line 3 "TypeError: 'int' object is not iterable," and its been bothering me. Any advice/fixes appreciated.
Example test: collatz_counts(4) → 3 # 4 -> 2 -> 1 (3 steps)
Code I have:
def collatz_counts(x):
num = 0
for i in (x):
if i == 1:
num += 1
return num
elif i % 2 == 0:
num(i) / 2
num += 1
num.append(i)
else:
num = (i*2) + 3
num += 1
num.append(i)
return num

This can be solved recursively:
def collatz_length(n):
if n == 1:
return 1
return 1 + collatz_length(3*n+1 if n%2 else n//2)
Which lends itself to be memoized if you are going to be calling for a range of numbers, e.g. in Py3
import functools as ft
#ft.lru_cache(maxsize=None)
def collatz_length(n):
if n == 1:
return 1
return 1 + collatz_length(3*n+1 if n%2 else n//2)
Which will run through the first million collatz sequences in about 2.31s vs about 28.6s for the iterative solution.

Use a while loop. Just modify x in place until you get to 1 and keep track of the number of steps each time you run a cycle.
def collatz_counts(x):
steps = 0
while x != 1:
if x % 2:
x = x * 3 + 1
else:
x = x // 2
steps += 1
return steps

Related

How to Convert base 10 to base 2 and find the base 10 integer that denotes most consecutive 1s?

I have been trying to convert base 10 to base 2 and finding the base 10 integer that denotes most consecutive 1s
if __name__ == '__main__':
n = int(input().strip())``
outcomes = 0
biggest = 0
while n > 0:
if n % 2 == 1:
outcomes += 1
if outcomes > biggest:
biggest = outcomes
else:
result = 0
print(biggest)
those are my codes please correct where i'm wrong

Applying my function to every position in a Numpy array

I am attempting to apply my CasinoTime function to each position in my array per sweep. The function currently does this but chooses a position at random and can only do one position per sweep. The output looks something like this:
Starting Configuration: [[ 1 -1 1 1 -1 -1 1 1 1 -1]]
0: [[ 1 -1 1 1 -1 -1 1 1 1 -1]] Energy: [-2] Spin: 0.2
1: [[ 1 -1 1 1 1 -1 1 1 1 -1]] Energy: [[-10]] Spin: 0.4
2: [[ 1 -1 1 1 1 -1 1 1 1 -1]] Energy: [[-10]] Spin: 0.4
3: [[-1 -1 1 1 1 -1 1 1 1 -1]] Energy: [[-2]] Spin: 0.2
As you can see, it only alters one position at a time. Ideally my function will run through every position in my array (per sweep) and change the values which meet the criteria. This is a simulation of A Monte Carlo/Metropolis Algorithm. I have attempted to use a map function to apply my function to my array however this does not seem to work. Any help is greatly appreciated and I have attached my code below!
import numpy as np
N = 10
J = 1
H = 2
def calcEnergy(config, J, H):
energy = 0
for i in range(config.size):
spin = config[i]
neighbour = config[(i + 1) % N]
energy = energy - J * (spin * neighbour) - H * neighbour
return energy
def ChangeInEnergy(J, H, spin, spinleft, spinright):
dE = 2 * H * spin + 2 * J * spin * (spinleft + spinright)
return dE
def CasinoTime(sweeps, beta, J, H, debug=False):
config = np.random.choice([-1, 1], (N, 1))
averagespins = []
if debug is True:
print("Starting Configuration:", (np.transpose(config)))
runningenergy = calcEnergy(config, J, H)
for i in range(sweeps):
spinlocation = np.random.randint(N)
spin = config[spinlocation]
spinright = config[(spin + 1) % N]
spinleft = config[(spin - 1) % N]
dE = ChangeInEnergy(J, H, spin, spinleft, spinright)
r = np.random.random()
if r < min(1, np.exp(-beta * dE)):
config[spinlocation] *= -1
runningenergy = runningenergy + dE
else:
pass
averagespin = config.mean()
if debug and i % 1 == 0:
print("%i: " % i, np.transpose(config), "Energy:", runningenergy, "Spin:", averagespin)
return averagespins
averagespins = CasinoTime(sweeps=20, beta=0.1, J=1, H=2, debug=True)

Julia (Julia-lang) conditional in function chaining

I'm trying to sum all numbers from 1 to 1000 that are either divisible by 3 or 5.
The first attempt is straight forward:
ans1 = 0
for x in 3:999
ans1 += x % 3 == 0 || x % 5 == 0 ? x : 0
end
When I try the same approach using function chaining, it fails to return the answer I expect, it instead returns 0.
ans2 = [3:999] |> x -> x % 3 == 0 || x % 5 == 0 ? x : 0 |> sum
I believe the problem is the center function, since the code below prints all values within the range of 3 to 999. So i know there is no problem with iteration.
[3:999] |> x -> println(x)
Could anyone please help me.
I discovered the reason was because I did not understand the type being parsed. Here is an example:
[3:999] |> println(typeof(x)) # Array{Int64,1}
Meaning the value being parsed is an array of integer64. So evaluating the following:
[1:999] % 3 == 0 # false
So my answer was to instead use the filter function, here is an example:
ans3 = sum(filter(x -> x % 3 == 0 || x % 5 == 0,[1:999]))
The final answer using function chaining is:
ans4 = [1:999] |> x -> filter(y -> y % 3 == 0 || y % 5 == 0,x) |> sum
Which evaluates to the expected answer.

Tweaking a Function in Python

I am trying to get the following code to do a few more tricks:
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.answerLabel = Label(self, text="Output List:")
self.answerLabel.grid(row=2, column=1, sticky=W)
def psiFunction(self):
j = int(self.indexEntry.get())
valueList = list(self.listEntry.get())
x = map(int, valueList)
if x[0] != 0:
x.insert(0, 0)
rtn = []
for n2 in range(0, len(x) * j - 2):
n = n2 / j
r = n2 - n * j
rtn.append(j * x[n] + r * (x[n + 1] - x[n]))
self.answer = Label(self, text=rtn)
self.answer.grid(row=2, column=2, sticky=W)
if __name__ == "__main__":
root = Tk()
In particular, I am trying to get it to calculate len(x) * j - 1 terms, and to work for a variety of parameter values. If you try running it you should find that you get errors for larger parameter values. For example with a list 0,1,2,3,4 and a parameter j=3 we should run through the program and get 0123456789101112. However, I get an error that the last value is 'out of range' if I try to compute it.
I believe it's an issue with my function as defined. It seems the issue with parameters has something to do with the way it ties the parameter to the n value. Consider 0123. It works great if I use 2 as my parameter (called index in the function) but fails if I use 3.
EDIT:
def psi_j(x, j):
rtn = []
for n2 in range(0, len(x) * j - 2):
n = n2 / j
r = n2 - n * j
if r == 0:
rtn.append(j * x[n])
else:
rtn.append(j * x[n] + r * (x[n + 1] - x[n]))
print 'n2 =', n2, ': n =', n, ' r =' , r, ' rtn =', rtn
return rtn
For example if we have psi_j(x,2) with x = [0,1,2,3,4] we will be able to get [0,1,2,3,4,5,6,7,8,9,10,11] with an error on 12.
The idea though is that we should be able to calculate that last term. It is the 12th term of our output sequence, and 12 = 3*4+0 => 3*x[4] + 0*(x[n+1]-x[n]). Now, there is no 5th term to calculate so that's definitely an issue but we do not need that term since the second part of the equation is zero. Is there a way to write this into the equation?
If we think about the example data [0, 1, 2, 3] and a j of 3, the problem is that we're trying to get x[4]` in the last iteration.
len(x) * j - 2 for this data is 10
range(0, 10) is 0 through 9.
Manually processing our last iteration, allows us to resolve the code to this.
n = 3 # or 9 / 3
r = 0 # or 9 - 3 * 3
rtn.append(3 * x[3] + 0 * (x[3 + 1] - x[3]))
We have code trying to reach x[3 + 1], which doesn't exist when we only have indices 0 through 3.
To fix this, we could rewrite the code like this.
n = n2 / j
r = n2 - n * j
if r == 0:
rtn.append(j * x[n])
else:
rtn.append(j * x[n] + r * (x[n + 1] - x[n]))
If r is 0, then (x[n + 1] - x[n]) is irrelevant.
Please correct me if my math is wrong on that. I can't see a case where n >= len(x) and r != 0, but if that's possible, then my solution is invalid.
Without understanding that the purpose of the function is (is it a kind of filter? or smoothing function?), I prickled it out of the GUI suff and tested it alone:
def psiFunction(j, valueList):
x = map(int, valueList)
if x[0] != 0:
x.insert(0, 0)
rtn = []
for n2 in range(0, len(x) * j - 2):
n = n2 / j
r = n2 - n * j
print "n =", n, "max_n2 =", len(x) * j - 2, "n2 =", n2, "lx =", len(x), "r =", r
val = j * x[n] + r * (x[n + 1] - x[n])
rtn.append(val)
print j * x[n], r * (x[n + 1] - x[n]), val
return rtn
if __name__ == '__main__':
print psiFunction(3, [0, 1, 2, 3, 4])
Calling this module leads to some debugging output and, at the end, the mentionned error message.
Obviously, your x[n + 1] access fails, as n is 4 there, so n + 1 is 5, one too much for accessing the x array, which has length 5 and thus indexes from 0 to 4.
EDIT: Your psi_j() gives me the same behaviour.
Let me continue guessing: Whatever we want to do, we have to ensure that n + 1 stays below len(x). So maybe a
for n2 in range(0, (len(x) - 1) * j):
would be helpful. It only produces the numbers 0..11, but I think this is the only thing which can be expected out of it: the last items only can be
3*3 + 0*(4-3)
3*3 + 1*(4-3)
3*3 + 2*(4-3)
and stop. And this is achieved with the limit I mention here.

Miller–Rabin SPOJ WA

I am trying to implement Miller-Rabin for the first time. My code is giving correct answer for all the testcases, i tried but still on SPOJ it is giving wrong answer.
Problem Statement: I am supposed to print "YES" if entered number is prime otherwise "NO"
Please help:
Problem Link: http://www.spoj.com/problems/PON/
CODE:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define LL long long
LL expo(LL a,LL b,LL c)
{
LL x=1,y=a;
if(b==0)
return 1;
while(b)
{
if(b%2==1)
x=(x*y)%c;
y=(y*y)%c;
b=b/2;
}
return x;
}
int main()
{
LL t,s,x,a,n,prime,temp;
scanf("%lld",&t);
srand(time(NULL));
while(t--)
{
scanf("%lld",&n);
if(n<2)
puts("NO");
else if(n==2)
puts("YES");
else if(n%2==0)
puts("NO");
else
{
s=n-1;
prime=1;
while(s%2==0)
s=s/2;
for(int i=0;i<20;i++)
{
a=rand()%(n-1)+1;
x=expo(a,s,n);
temp=s;
while((temp!=n-1)&&(x!=1)&&(x!=n-1))
{
x=(x*x)%n;
temp*=2;
}
if((x!=n-1)&&(temp%2==0))
{
prime=0;
break;
}
}
if(prime==0)
puts("NO");
else
puts("YES");
}
}
return 0;
}
Keep in mind that puts appends a newline character '\n' to the string that you're giving. You can try with printf instead.
I think your calculation of s and d is incorrect:
function isStrongPseudoprime(n, a)
d := n - 1; s := 0
while d % 2 == 0
d := d / 2; s := s + 1
t := powerMod(a, d, n)
if t == 1 return ProbablyPrime
while s > 0
if t == n - 1 return ProbablyPrime
t := (t * t) % n
s := s - 1
return Composite
I discuss the Miller-Rabin method in an essay at my blog.
You are getting wrong answer because of integer overflow as you are multiplying 2 long number which can't be holded in a single long long type.
Here is a solution in python to overcome the issue
import random
_mrpt_num_trials = 25 # number of bases to test
def is_probable_prime(n):
assert n >= 2
# special case 2
if n == 2:
return True
# ensure n is odd
if n % 2 == 0:
return False
# write n-1 as 2**s * d
# repeatedly try to divide n-1 by 2
s = 0
d = n - 1
while True:
quotient, remainder = divmod(d, 2)
if remainder == 1:
break
s += 1
d = quotient
assert(2 ** s * d == n - 1)
def try_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2 ** i * d, n) == n - 1:
return False
return True
for _ in range(_mrpt_num_trials):
a = random.randrange(2, n)
if try_composite(a):
return False
return True
for i in range(int(input())):
a = int(input())
if is_probable_prime(a):
print("YES")
else:
print("NO")