Python 2.7. Iterating list not working - list

Just starting with Python and doing some challenges, this one on Collatz numbers.
I am stuck at the start however, where the range that I am passing to the collatz method is not iterating over the given range.
What am I missing here?
def collatz(number):
for i in number:
if i % 2:
return i // 2
else:
return 3 * (i + 1)
try:
print(collatz(range(0,10)))
except ZeroDivisionError:
print("Zero Division")
except TypeError:
print "Type Error"

for i in range(0,10):
print(collatz(i))

Short answer: the 'return' statement is causing your function to exit on the first iteration, thus preventing further iterations from occurring.
Long answer:
Here's a breakdown of how your code is running.
collatz(number) receives a list [0,1,...10]
A loop is created for [0,1,...10] starting from 0
1st, start with i = 0
0 % 2 evals to 0, which is False, which means we skip to the else statement
We return 3 * (0 + 1), which evaluates to 3.
We finish the call to collatz(number)
The correct approach is answered in some other folks' posts.

algorithm
If the number is even, divide it by two.
If the number is odd, triple it and add one.
code
def f(n):
if n % 2 == 0:
return n // 2
else:
return 3 * n + 1
def a(i, n):
if i == 0:
return n
else:
return f(a(i - 1, n))
def collatz(n):
i = 0
c = 0
out = []
while c != 1:
c = a(i, n)
out.append(c)
i += 1
return out
print(collatz(6))
output
[6, 3, 10, 5, 16, 8, 4, 2, 1]

Related

Python replace every 3rd value with previous 2 items sum when not equal

A given list is n=[3,1,5,9,6,14] , replace 5 with 3+1 and 14 with 9+6. The output will look like [3,1,4,9,6,15]
My approach was using a range and assign value
i+ [i+1]==[i+2]
I tried 2 ways but in both cases I am getting out of bound exception
#Approach 1
for idx,item in enumerate(n):
if (idx + (idx+1))!=(idx+2):
n[idx+2]=(idx + (idx+1))
#Approach2
for i in range(len(n)):
if n[i]+n[i+1]!=n[i+2]:
n[i + 2]==n[i]+n[i+1]
print(n)
Even doing a len(n)-1 does not solve the problem. Some directions will be helpful. Thank You.
You could use the mod (%) operator to check for every third item:
items = [3, 1, 5, 9, 6, 14]
for i, item in enumerate(items):
if ((i+1) % 3 == 0):
items[i] = items[i-1] + items[i-2]
print(items)
Or to be more efficient, use range as mentioned in the comments:
for i in range(2, len(items), 3):
items[i] = items[i-1] + items[i-2]
print(items)

python2.7 : i % 10 == 0 does not work

from __future__ import print_function
i = 0
for i in range (0, 100)
print(i, end = " ")
i += 1
if i % 10 == 0
print(" ")
print()
I just start my python learning several days ago.
It is about the for_loop training.
As my codes tell, it should print out numbers from 0 to 98 increasing by 2 till 98. As 10 digits printed out, it should print another 10 digits in the next line and keep going on. But it do not work properly. However, it works from changing function to
range(0,100) `
range(0,100)
But do not work when I change the function to
range(0, 100, 2)`
range(0, 100, 2)
Hint: When you use range(0, 100, 2), i is always even and i += 1 would make it odd, hence never satisfying i % 10 == 0. Try using different variable for digit counter or modifying the operands for addition and modulus.

prime numbers algorithm efficiency

I have a question about prime numbers algorithm.
why in the following pseudo code i increases by 6 and not by 2 every iteration?
function is_prime(n)
if n ≤ 1
return false
else if n ≤ 3
return true
else if n mod 2 = 0 or n mod 3 = 0
return false
let i ← 5
while i * i ≤ n
if n mod i = 0 or n mod (i + 2) = 0
return false
i ← i + 6
return true
Thanks!
If it increased by 2 it would be testing almost everything twice, that wouldn't make any sense. So I assume you mean: how can it get away with not testing every odd number?
This is because every prime p greater than 3 is of the form 6n±1. Proof:
Consider the remainder r = p mod 6. Obviously r must be odd. Notice also that r cannot be 3, because then p would be divisible by 3, making it not a prime. This leaves only the possibilities 1 and 5, which correspond p being of the form 6n+1 or the form 6n-1 respectively.
The effect is that it avoid testing multiples of 3. Dividing by a multiple of 3 is redundant, because we already know that n is not a multiple of 3, so it cannot be the multiple of a multiple of 3 either.
The assignment in the loop body is i <- i + 6, not i <- i + 2. In the if statement the expression i + 2 just becomes a new value. There is no assignment operator in that expression.
The algorithm is based on the fact that prime numbers can be predicted using the formula 6k ± 1 and this does not apply on 2 and 3.
For instance
(6 * 1) - 1 = 5
(6 * 2) - 1 = 11
(6 * 3) - 1 = 17
The list goes on and on.

Can't finish a mathematical project

I am new to coding and I am finding this site really helpful. So I have been trying to solve this problem and I am getting erroneous results, so I would be really grateful if you could help me out here.
The Problem: Find the sum of all the multiples of 3 or 5 below 1000. (For example, if we list all the positive integers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9, which sum is 23.)
My code:
count = 0
count1 = 0
for x in range(1000):
if x % 5 == 0:
count = count + x
if x % 3 == 0:
count1 = count1 + x
print count1 + count
What am I doing wrong?
Thanks in advance!
You want an elif in your code so you don't count the same x twice but a simpler way is to use an or with a single count variable:
count = 0
for x in range(1000):
if x % 5 == 0 or x % 3 == 0:
count += x
Which can be done using sum:
print(sum(x for x in range(3, 1000) if not x % 5 or not x % 3))
For completeness, a working version using your own code:
count = 0
count1 = 0
for x in range(1000):
if x % 5 == 0:
count += x
elif x % 3 == 0:
count1 += x
print count1 + count
ifs are always evaluated; so, for instance, when x is 15 it is evenly divisible by 5 and 3 so you count 15 twice, an elif is only evaluated if the previous if/elif evaluates to False so using elif only one occurrence of x will be added to the total.
Below 10 there is no number being multiple of both 5 and 3. But below 1000 there are several numbers divided exactly by 3 and 5 also (15, 45 ...).
So you need:
count=0
for x in range(1000):
if x % 5 == 0 or x % 3 == 0:
count=count + x
print count

while statement

def sequence(n):
while n != 1:
print n,
if n%2 == 0: # n is even
n = n/2
else: # n is odd
n = n*3+1
sequence(6)
6 3 10 5 16 8 4 2
Why the output doesn't include 1 here?Many many thanx!
try using <= or >= for instance, while n >= 1. That should do what you need :)
You have the while loop set on breaking if n == 1. Try possibly doing n > 0 or n >= 1.
while n != 1:
print n
Once n gets a value of 1, it won't enter the loop, thus not allowing 'n' to be printed.