Why will this not stop when len(prime) increments to 9,
I also tried using the counter but that did not work either. In this case it runs until it has check for primes to 100 not until if finds the first 10 primes.
prime = [2]
odd_list = [x for x in range(100) if x % 2 != 0 and x > 2]
count = 0
while len(prime) < 10:
for z in odd_list:
for y in range(2, z):
if z % y == 0: # is not prime
break
else:
prime.append(z)
count += 1
print 'count = ', count
print 'length of prime =', len(prime)
print prime
You need to check number of primes in internal loop:
prime = [2]
odd_list = [x for x in range(100) if x % 2 != 0 and x > 2]
count = 0
for z in odd_list:
for y in range(2, z):
if z % y == 0: # is not prime
break
else:
prime.append(z)
count += 1
if len(prime) >= 10:
break
print 'count = ', count
print 'length of prime =', len(prime)
print prime
In each interation of external while loop you run whole for loop:
while len(prime) < 10:
for z in odd_list:
...
so after first while iteration all primes will already be found, and only then you will stop while loop.
Related
def solution(number):
x = 0
total = 0
while x < number:
if x % 3 == 0 or x % 5 == 0:
total = total + x
x = x + 1
print total
return total
solution(10)
Hello, when I run this code through IDE nothing happens.
What's wrong with it? There are no errors or anything.
I think you enter an infinite loop due to x incremental issue.
def solution(number):
x = 0
total = 0
while x < number:
if x % 3 == 0 or x % 5 == 0:
total = total + x
x = x + 1
print total
return total
Just increment x independently from the if condition that may prevent its incremental.
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
I need to check in Haskell if a four digit number is a palindrome, the problem is that I can't use lists, and in spite of having a fixed digit number, I should use recursion. I have been think on the problem and I couldn't get a solution using recursion. The closest that I could get was this:
pldrm :: Integer -> Bool
pldrm x
|x > 9999 = False
|x > 999 = (div x 1000 == mod x 10) && (mod (div x 100) 10) == div (mod x 100) 10
|otherwise = False
Do you have any idea? thanks
How about just checking if a number is equal to its reversal?
palindrome :: Integer -> Bool
palindrome x = reversal x == x
reversal :: Integral a => a -> a
reversal = go 0
where go a 0 = a
go a b = let (q,r) = b `quotRem` 10 in go (a*10 + r) q
This lets negative numbers like -121 be palindromes, which is easy to check for if you don't want that to be true.
nonNegativePalindrome x = x >= 0 && palindrome x
reversal gives us the integer with digits in reverse order of our input (ignoring the infinite leading zeroes implicit in 12 == ...000012).
reversal works by peeling off the digits from the bottom (using quotRem, which is a lot like divMod) and putting them together in reverse order (via muliplication and adding).
reversal 12345
= go 0 12345
= go 5 1234
= go 54 123
= go 543 12
= go 5432 1
= go 54321 0
= 54321
It's worth noting that n == reversal $ reversal n only if n is zero or has a non-zero 1s digit. (reversal (reversal 1200) == 12), but that integers in the range of reversal are all invertible: reversal x == reversal (reversal (reversal x)) forall x.
More thorough explanation of how to reach this solution in this blog post.
Ok, this is indeed a bit tricky and more math than Haskell so let's look at a possible solution (assuming a decimal system).
The idea is to use div and mod to get at the highest and lowest digit of a number.
Remember that you can write
(q,r) = n `divMod` m
to get numbers q and r so that q * m + r = n with 0 <= r < q. For m = 10 this
will conveniently get (for positive n):
in q all but the last digits
in r the last digit
remark: I had this wrong for some time - I hope it's correct now - the edge cases are really tricky.
palindrome :: Integer -> Bool
palindrome n = palin n (digits n)
where
palin x dgts
| x < 0 = False
| x == 0 = True
| x < 10 = dgts == 1
| otherwise = q == x `mod` 10 && palin inner (dgts-2)
where
inner = r `div` 10
(q,r) = x `divMod` size
size = 10^(dgts-1)
digits :: Integer -> Integer
digits x
| x < 10 = 1
| otherwise = 1 + digits (x `div` 10)
Obvious I did not know the size of your problem so digits will look for the number of digits:
digits 5445 = 4
digits 123 = 3
...
The edge cases are these:
| x < 0 = False
| x == 0 = True
| x < 10 = digits == 1
Obvious negative numbers should not be palindromes
if all digits are 0 then it's an palindrome
one-digit numbers are palindromes if indeed we are looking only at length 1 (this had me bad, as the inner of stuff like 1011 is a one digit nubmer 1)
The rest is based on this observations:
x div 10^(digits-1) = the highest digit (5445 div 1000 = 5)
x mod 10^(digits-1) = all but the highest digit (5445 mod 1000 = 445)
x mod 10 = the lowest digit (5445 mod 10 = 5)
number div 10 = remove the lowest digit (5445 div 10 = 544)
just to be safe let's test it using Quickcheck:
Let's use Quickcheck to test it (should be a nice example :D )
module Palindrome where
import Test.QuickCheck
main :: IO ()
main = do
checkIt palindrome
palindrome :: Integer -> Bool
palindrome n = palin n (digits n)
where
palin x dgts
| x < 0 = False
| x == 0 = True
| x < 10 = dgts == 1
| otherwise = q == x `mod` 10 && palin inner (dgts-2)
where
inner = r `div` 10
(q,r) = x `divMod` size
size = 10^(dgts-1)
digits :: Integer -> Integer
digits x
| x < 10 = 1
| otherwise = 1 + digits (x `div` 10)
checkIt :: (Integer -> Bool) -> IO ()
checkIt p =
quickCheckWith more (\n -> n < 0 || p n == (reverse (show n) == show n))
where more = stdArgs { maxSuccess = 10000, maxSize = 999999 }
seems ok:
runghc Palindrom.hs
+++ OK, passed 10000 tests.
If only four digit numbers considered, you can recursively subtract 1001 to check if first and last digits are equal and then subtract 0110 to check if middle digits are equal.
pldrm :: Int -> Bool
pldrm x
| x > 1000 = pldrm (x - 1001)
| x > 100 = pldrm (x - 110)
| otherwise = x == 0
Please note that this function will give incorrect results for numbers outside of [1000,9999] range.
It is a pity that you cannot use lists. Here is cumbersome solution based on arithmetic operations (works only for four-digit numbers):
pldrm :: Int -> Bool -- no need for Integer if you work only with four
-- digit numbers
pldrm x = (div x 1000 == mod x 10) && (div y 10 == mod y 10)
where y = rem x 1000 `quot` 10 -- extracts two inner digits
> pldrm 3113
True
> pldrm 3111
False
isPolindrom :: Integer -> Bool
isPolindrom n = if let i = read (reverse (show n)) :: Integer in i==n then True else False
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.
Here is my code:
program change
integer:: amount, remainder, q, d, n, p
amount = 47
remainder = amount
print*,remainder
q = 0
d = 0
n = 0
p = 0
do while (remainder >= 25)
remainder = remainder - 25
print*,remainder
q = q + 1
end do
do while (remainder >= 10)
remainder = remainder - 25
print*,remainder
d = d + 1
end do
do while (remainder >= 5)
remainder = remainder - 25
print*,remainder
n = n + 1
end do
do while (remainder >= 1)
remainder = remainder - 25
print*,remainder
p = p + 1
end do
print*, "# Quarters:", q
print*, "# Dimes:", d
print*, "# Nickels:", n
print*, "# Pennies:", p
end program change
Output:
47
22
-3
# Quarters: 1
# Dimes: 1
# Nickels: 0
# Pennies: 0
The first loop (>=25) should exit once the remainder becomes 22, but it runs through once more and yields a negative number. Why is this not exiting even though the condition is false? I'm using IDEone.com's Fortran "compiler" which appears to be Fortran 95-like.
Your DO loops are fine. You simply need to subtract the correct denomination from remainder in each loop. For instance change your second DO loop to:
do while (remainder >= 10)
remainder = remainder - 10
print*,remainder
d = d + 1
end do
and change the rest in a similar manner.