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

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.

Related

Getting Time out error and run time error in test case 2 and 3 in hackerrank. How to resolve this?

The objective of this code is to print sum of multiples of 3 and 5 between given range. In hackerrank, I am getting error in test case 2 and 3. Anyone knows how to resolve the issue?
t =int(raw_input())
for i in range(0,t):
range = int(raw_input())
a=3
b=5
aa=[]
res=[]
def forA(a): #Calculating Multiple of 3
while True:
if a >=range :
a = a-3
break
else:
aa.append(a)
a += 3;
def forB(b): #Calculating Multiple of 5
while True:
if b >=range :
b=b-5
return b
break
else:
aa.append(b)
b += 5;
forA(a)
forB(b)
for i in aa: #eliminate duplicate values of multiples.
if i not in res:
res.append(i)
print sum(res)
This might resolve your problems because it uses pythons builtin features that are "smart" instead of creating a list one item a time yourself. Therefore they are faster... which might solve the timing errors you get.
You get all the numbers up to your input from 3 or 5 till t by
from itertools import chain
t =15
threes = range(0,t+1,3) # range provides [lower..higher[ not including higher value
fives = range(0,t+1,5)
sums = sum(chain(threes,fives)) # without itertools: sums=sum(threes) + sum(fives)
print(threes)
print(fives)
print(sums)
If you want to avoid multiples, avoid chain(..), uses sets and join them together before summing them up
s = set(threes) | set(fives)
print(sum(s))
Output:
[0, 3, 6, 9, 12, 15] # threes up to 15
[0, 5, 10, 15] # fives up to 15
75 # sum of chained ones
60 # sum of set

How to find a match using "while"

I'm trying to find a random number between 1-100000 that divided with 7 & 13 & 15,
the loop should run until it find the right number,
I'm trying to do:
from random import randint
while True:
for x in range (1,100000):
if x % 7 == 0 and x % 13 ==0 and x % 15 == 0:
print x
You could do that with a list comprehension:
l=[x for x in range(1,100000) if x % 7 == 0 and x % 13 == 0 and x % 15 == 0]
Then, to select a random value from that list, change the top line to import random, and you can do:
random.choice(l)
As we know, 7,13 and 15 are co-primes, then, we should start from 7*13*15 = 1365. Then you can apply #numbermaniac solution.
import random
random.choice([i for i in xrange(1365,1000000) if i%1365 == 0])
another solution might be,
# select random number between your upper_limit/1365
# then multiplying it 1365
random.randint(1, 732)*1365

How do I get "The numbers" Only at the end?

Here is what I want to get:
$ python ex33.py
At the top i is 0
Numbers now: [0]
At the bottom i is 1
At the top i is 1
Numbers now: [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now: [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now: [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now: [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5
This was a while loop:
1 i = 0
2 numbers = []
3
4 while i < 6:
5 print "At the top i is %d" % i
6 numbers.append(i)
7
8 i = i + 1
9 print "Numbers now: ", numbers
10 print "At the bottom i is %d" % i
11
12
13 print "The numbers: "
14
15 for num in numbers:
16 print num
Now Mr Shaw asks me to build this into a function. His exact question is: Convert this while- loop to a function that you can call, and replace 6 in the test (i < 6) with a variable. I am not sure I have build a function (since those mostly start with a def? Or do they always start with a def?)
I am not sure if I understand completely what he is asking, but this is what I did:
i = 0
numbers = []
for i in range (0, 6):
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
Which actually makes me kind of proud for how for I have gotten with this:
At the top i is 0
Numbers now: [0]
At the bottom i is 1
The numbers:
0
At the top i is 1
Numbers now: [0, 1]
At the bottom i is 2
The numbers:
0
1
At the top i is 2
Numbers now: [0, 1, 2]
At the bottom i is 3
The numbers:
0
1
2
At the top i is 3
Numbers now: [0, 1, 2, 3]
At the bottom i is 4
The numbers:
0
1
2
3
At the top i is 4
Numbers now: [0, 1, 2, 3, 4]
At the bottom i is 5
The numbers:
0
1
2
3
4
At the top i is 5
Numbers now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5
Where I am stuck is that "The numbers" is something I only need to get at the end. And that, I can't get my head around. What am I missing (except amazing coding skills and a well functioning brain)?
You have not made a function. While it's not always necessary to use def to make a function, that's the usual way. And I think you've misunderstood what your teacher wanted you to change in your while loop. He wanted you to replace the 6 in the condition i < 6 with a variable (a parameter of the function). You've replaced the while with a for, but still kept the 6 as a constant. Using for loops instead of while loops is often a good idea, but in this case it's now what was being asked for.
As for why your numbers output is being repeated, I suspect it's because that code is inside your main loop now, while it wasn't before. This is not entirely clear though, since you seem to have lost the indentation of the original code when you copied it into Stack Overflow. Since indentation is significant in Python, this makes it hard to know exactly the old code ran.
what you are missing is that in python block of code are defined by the indentation level, you put the part that print the whole list inside the for that fill the list so each time that you put a number in the list also print if afterward. To put that outside reduce the indentation level of that part like this
i = 0
numbers = []
for i in range (0, 6):
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
#this part is now outside the for-loop
print "The numbers: "
for num in numbers:
print num
About your other question, yes functions are defined by the key world def you can check the documentation about the details, but in your case you can transform you code into a function very easy like this
def my_function():
i = 0
numbers = []
for i in range (0, 6):
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
that is, declare that you are creating a new function with the def key world, give it a name, in this case I called my_function, and put your previous code inside it by just give it a extra indentation level as show above.
Functions have the property that they can take a number of arguments and operate according to that, that let you define some behavior and make it more general.
For example: say that you want to print the number 0 to 9 you can do
for num in range(0,10):
print num
Now say that you want to print the number 0-5, 0-20, and 10-20 you can write a similar code for all of them:
for num in range(0,6):
print num
for num in range(0,21):
print num
for num in range(10,21):
print num
but wait there is pattern here all have the same exact code in every case save for the arguments of range, here is when a function come to play, we can define a function that take as arguments 2 numbers and our function do the job of print all the number in between; that is something like this
def my_function(star,stop):
for num in range(star,stop+1): # the +1 is to include the stop number
print num
(this is fun_test.py in the example below)
then we can call our function like this
my_function(0,5)
my_function(0,20)
my_function(10,20)
or if we open the file in a python interpreter or in interactive mode (that is $ python -i ex33.py) we can call with any pair of numbers of our desire
$ python -i fun_test.py
>>> my_function(8,17)
8
9
10
11
12
13
14
15
16
17
>>> my_function(0,5)
0
1
2
3
4
5
>>>
as you can see a function let us re-use a piece of code as many times as we want. The arguments of a function is the part of it that is variable while its code is the behavior we want according to the variable part (if any).
With this little explanation I think that you can modify your function to the requirements that your teacher (?) ask you

Python 2.7. Iterating list not working

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]

Calculating Hamming Sequence in C++ (a sequence of numbers that has only 2, 3, and 5 as dividers) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generating a sequence using prime numbers 2, 3, and 5 only, and then displaying an nth term (C++)
I've been brainstorming over this forever, and I just can't figure this out. I need to solve the following problem:
Generate the following sequence and display the nth term in the
sequence
2,3,4,5,6,8,9,10,12,15, etc..... Sequence only has Prime numbers
2,3,5
I need to use basic C++, such as while, for, if, etc. Nothing fancy. I can't use arrays simply because I don't know much about them yet, and I want to understand the code for the solution.
I'm not asking for a complete solution, but I am asking for guidance to get through this... please.
My problem is that I can't figure out how to check if the number if the number in the sequence is divisible by any other prime numbers other than 2, 3, and 5.
Also let's say I'm checking the number like this:
for(int i=2; i<n; i++){
if(i%2==0){
cout<<i<<", ";
}else if(i%3==0){
cout<<i<<", ";
}else if(i%5==0){
cout<<i<<", ";
}
It doesn't work simply due to the fact that it'll produce numbers such as 14, which can be divided by prime number 7. So I need to figure out how to ensure that that sequence is only divisible by 2, 3, and 5..... I've found lots of material online with solutions for the problem, but the solutions they have are far too advance, and I can't use them (also most of them are in other languages... not C++). I'm sure there's a simpler way.
The problem with your code is that you just check one of the prime factors, not all of them.
Take your example of 14. Your code only checks if 2,3 or 5 is a factor of 14, which is not exactly what you need. Indeed, you find that 2 is a factor of 14, but the other factor is 7, as you said. What you are missing is to further check if 7 has as only factors 2,3 and 5 (which is not the case). What you need to do is to eliminate all the factors 2,3 and 5 and see what is remaining.
Let's take two examples: 60 and 42
For 60
Start with factors 2
60 % 2 = 0, so now check 60 / 2 = 30.
30 % 2 = 0, so now check 30 / 2 = 15.
15 % 2 = 1, so no more factors of 2.
Go on with factors 3
15 % 3 = 0, so now check 15 / 3 = 5.
5 % 3 = 2, so no more factors of 3.
Finish with factors 5
5 % 5 = 0, so now check 5 / 5 = 1
1 % 5 = 1, so no more factors of 5.
We end up with 1, so this number is part of the sequence.
For 42
Again, start with factors 2
42 % 2 = 0, so now check 42 / 2 = 21.
21 % 2 = 1, so no more factors of 2.
Go on with factors 3
21 % 3 = 0, so now check 21 / 3 = 7.
7 % 3 = 1, so no more factors of 3.
Finish with factors 5
7 % 5 = 2, so no more factors of 5.
We end up with 7 (something different from 1), so this number is NOT part of the sequence.
So in your implementation, you should probably nest 3 while loops in your for loop to reflect this reasoning.
Store the next i value in temporary variable and then divide it by 2 as long as you can (eg. as long as i%2 == 0). Then divide by 3 as long as you can. Then by 5. And then check, what is left.
What about this?
bool try_hamming(int n)
{
while(n%2 == 0)
{
n = n/2;
}
while(n%3 == 0)
{
n = n/3;
}
while(n%5 == 0)
{
n = n/5;
}
return n==1;
}
This should return true when n is a hamming nummer and false other wise. So the main function could look something like this
#include<iostream>
using namespace std;
main()
{
for(int i=2;i<100;++i)
{
if(try_hamming(i) )
cout<< i <<",";
}
cout<<end;
}
this schould print out all Hamming numbers less then 100