Project Euler #1 python code not working [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
For Project Euler, question #1:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
I am trying to use Python, and I have the following code:
def findNums():
numsToAdd = []
num = 1
while num < 999:
if 3 % num == 0 or 5 % num == 0:
numsToAdd.extend([num])
num +=1
#print(num) optional
for i in numsToAdd:
lastNum = 0
addition = numsToAdd[i] + lastNum
lastNum = numsToAdd[i]
print(lastNum)
findNums()
But I get the following error when I try to run it:
addition = numsToAdd[i] + lastNum
IndexError: list index out of range
Could someone please tell me what this is and how to fix it?

You have a few issues:
if 3 % num == 0 or 5 % num == 0:
Your conditionals are backward. How you have it set up now, you are checking if 3 or 5 is evenly divisible by num, not if num is evenly divisible by 3 or 5.
for i in numsToAdd:
Assume that numsToAdd has the following values when you get to this point: [100, 500].
When you get to addition = numsToAdd[i] + lastNum you are saying the following:
addition = numsToAdd[100] + lastNum
and
addition = numsToAdd[500] + lastNum
There isn't a 100th or 500th element. Instead, you can remove the indexing (to keep your existing format):
addition = i + lastNum
You could also do this to add up all the values in the list in one line:
sum(numsToAdd)
This can replace the entire for loop.
Finally, your first while is wrong:
Find the sum of all the multiples of 3 or 5 below 1000.
You are checking for everything less than 999. Change your while loop:
while num < 1000:

The problem with your code is that your list numsToAdd has just 465 items in it.
Instead of this:
numsToAdd[0]
numsToAdd[1]
numsToAdd[2]
.
.
numsToAdd[462]
numsToAdd[463]
numsToAdd[464]
You are doing this:
numsToAdd[3]
numsToAdd[5]
numsToAdd[6]
.
.
numsToAdd[459]
numsToAdd[460]
numsToAdd[462]
The error occurs because your list index is out of range! There is no numsToAdd[465]!

Related

what is the most efficient way of getting digit sum? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have to find the digit sum until its in single digit.
if input is -9999 then output should be -9
(-(9+9+9+9))==-9)
if input is 9012 then output should be 3 (+(9+0+1+2)==1+2==3))
ps: i have solved this but the negative inputs are giving wrong output.I am using the division by 9 property(you can google it) in order to get o(1) solution
my code:
def digSum(n):
if (n == 0):
return 0
if (n % 9 == 0):
return 9
else:
(n % 9)
just a simple recursion should help, add this to your code
if n < 0:
return - digSum(abs(n))
Your code is close, but you need to check to see if the input is a negative number BEFORE you evaluate if it modulates 9 or not. Your current code evaluates if n % 9 == 0 and returns 9, but you should add a condition to check if it's negative and n % 9 first, otherwise it will always return a positive number.
Modify your code to be this:
def digSum(n):
if (n == 0):
return 0
if (n % 9 == 0 and n < 0):
return -9
if (n % 9 == 0):
return 9
else:
(n % 9)

How to find the sum of all the divisors of a number, without including it [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Finding the sum of all the divisors of a number, without including that particular number that is being divided.
For example if we want to find the divisors of number 6 they would be 1,2,3. Number 6 should be included as it is a divisor, but for this scenario we are not considering it.
Note:- number 3 and 4 are not included since, when you divide number 6 by number 3, there would be a remainder.
A divisor is a number that divides into another without a remainder.
def sum_divisors(n):
sum = 0
# Return the sum of all divisors of n, not including n
return sum
print(sum_divisors(0)) # 0
print(sum_divisors(3)) # Should sum of 1 # 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18 # 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51 # 114
I think I got it:
def sum_divisors(n):
return sum([i for i in range(1, n)
if n % i == 0])
print(sum_divisors(0))
print(sum_divisors(3)) # Should sum of 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
Output
0
1
55
114
You could use a combined filter() and lambda() function
num = 36
div_sum = sum(list(filter(lambda div : num % div == 0 , range(1, num))))
# divisors : [1, 2, 3, 4, 6, 9, 12, 18]
# divisors sum : 55
print('divisors sum : ', div_sum)
We need to find the divisors of the number first, and then sum them. Finding out if a number is a divisor of another number is pretty simple:
if x % y == 0:
is_divisor = True
Modulo - % - returns the remainder of a division. 9 % 2 = 1. 10 % 3 = 1. However, we'll need to know which numbers to check. We could just loop through every number up to our input:
for i in range(n):
if n % i == 0:
is_divisor = True
...but that's too much. For example, we know that the highest possible divisor of n that isn't n itself, is 1/2n if n is even, and lower if it's not. Instead, let's focus on getting each pair, and then check if we should continue. We also need to store all of these numbers, so lets create some lists:
lower_divisors = []
upper_divisors = []
We'll want to know what our current highest lower divisor and lowest highest divisor are, and also know where to start. We can populate the lower divisor list with 1 and the highest with n. We can worry about removing n later.
lower_divisors = [1]
upper_divisors = [n]
continu = True
while continu:
# Let's get the last item in each list
highest_low = lower_divisors[-1]
lowest_high = upper_divisors[-1]
for i in range(highest_low + 1, lowest_high):
if n % i == 0:
lower_divisors.append(i)
upper_divisors.append(n // i)
break
continu = False
# If we've left the loop, we have all of our divisors.
lower_sum = sum(lower_divisors)
higher_sum = sum(upper_divisors) - n #Gotta take it back out!
sm = lower_sum + higher_sum
return sm
That should be a fast way to achieve your goal, without making your computer work harder - but... it's a lot more steps to write. I wrote it in far more steps to make it clear what I was doing and to be readable, but it could definitely be trimmed up a lot.
Upon running the code, the simple method of looping through each number from 1 to n starts to really add up when n is over 8 digits. 9 digit numbers were taking around 12-16 seconds on my machine. The longer approach above returns 32-digit values for n in under 1/10th of a second.

Python programming and the use of for loops [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Am new to programming and I just started studying and practicing. I started with python and am at for loops now. I kinda coded something that’s getting confusing for me because I can’t seem to understand how the code arrived at that output. Can someone please explain it to me. Would be very grateful.
Here’s the code I did:
a = range(1,20)
total = 0
for i in a :
if i%3==0 or i%5==0 :
total new = total + i
print (total new)
And the output was 18.
a = range(1,20)
Your program is creating a range of numbers between 1 and 19 (ranges go to one less than the max number you specify) like [1, 2, 3, 4, ..., 19]
total = 0
Your program is initializing the variable total to equal 0
for i in a:
You start looping through the range you made earlier, the first iteration i=1, the next i=2 and so on until i=19
if i % 3 == 0 or i % 5 == 0:
You are selecting only the data where the modulo of 5 or 3 is 0. For example:
3 % 3 == 0 (0 remainder)
4 % 3 == 1 (1 remainder)
Now altering your variable to a reasonable name (without spaces) that will actually utilize the variable we initialized above
total = total + i # alternatively written "total += i"
This says that every time the value i is evenly divisible by 3 or 5 we will add it to our total
print(total)
We show the final result after adding values. You incorrectly scripted your program to do this though so it only showed the largest value that was evenly divisible by 5 or 3 which is 18.
When scripted correctly:
a = range(1, 20)
total = 0
for i in a:
if i % 3 == 0 or i % 5 == 0:
total += i
print(total)
Outputs
78

Python Modularity for a number [duplicate]

This question already has answers here:
How do I sort a dictionary by value?
(34 answers)
Closed 5 years ago.
How to create a itterative number 10digit long by taking a base number
A Simple approach for Solution:
a=input()
while len(a)<10:
b=int(a[len(a)-1])+int(a[len(a)-2])
a=a+str(b%10)
print (a)
May This one helpful for you.
n= 16
while(len(str(n)) < 10):
print(n)
a = n %10 + (int(n/10))%10 # sum of last two digits
n *= 10
n += a%10 #adding the last
print(n)
Based on your example, I'm assuming you want to stop once you reach a 0.
Certain numbers, like 18 wouldn't reach a 0 ever, so also want to add a meximum length that the ID can be.
The following code runs the math until you reach a 0, or until it reaches 40 digits.
def getID(number)
maxlength = 40 - len(str(number))
while maxlength:
string = str(number)
answer = (int(string[-2]) + int(string[-1])) % 10
if answer == 0:
break
number = number * 10 + answer
maxlength -= 1
return number
getID(14) == 1459437
getID(15) == 15617853819
getID(16) == 1673
getID(18) == 17853819
getID(18) == 189763921347189763921347189763921347189763
18 is a number that repeats forever, so instead the loop ends once it reaches a set length.

Python:Project Euler #1 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I've tried looking up some questions that were already on StackOverflow for project Euler problem 1 but not much has helped me. This is my code, it runs, but it's not correct. not sure whats wrong?
def sumOfMultiples(number):
sum = 0
for i in range(1,number):
if i % 3 == 0 or i % 5 == 0:
sum += 1
return sum
print (sumOfMultiples(15))
You are not using i at all. When the number meets the condition (divisible by 3 or 5), you want to add it, not 1.
sum += 1
should be
sum += i
The question asks for "the sum of all the multiples of 3 or 5 below 1000". You're adding 1 to the sum instead of adding the multiple of 3 or 5 to the sum.
So sum += 1 should be sum += i.
import time
#Recording start time of the program
start=time.time()
#A variable to store the sum
result=0
#calculating the sum for all the numbers below 1000
for i in range(1,1000):
#Checking the the condition
if i%3==0 or i%5==0:
result=result+i
print("Sum of all numbers that are multiples of 3 or 5 below 1000 is",result)
print("Execution time of program is",time.time()-start)
def sumOfMultiples(number):
sum = 0
for i in range(1,number):
if i % 3 == 0 or i % 5 == 0:
sum += i
return sum
print (sumOfMultiples(15))
In place of sum+=1 write sum+=i.
Here is a single-liner for you to ponder:
print sum([x for x in xrange(1,1000) if x%3==0 or x%5==0])
or you could also do it like this:
print sum([[0,x][x%3==0 or x%5==0] for x in xrange(1,10**3)])
try using this:
def sumOfMultiples(number):
sum = 0
for i in range(1,number):
if i % 3 == 0 or i % 5 == 0:
sum += i ## You needed to add i, not 1. Probably just a type-o as they are similar looking characters.
print(sum)
(sumOfMultiples(1000)) ## Also Euler1 requires this input to be 1000 for correct answer.

Categories

Resources