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

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)

Related

What am I Doing wrong. Google kickstart 2020 [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 1 year ago.
Improve this question
this the question.
Ron read a book about boring numbers. According to the book, a positive number is called boring if all of the digits at even positions in the number are even and all of the digits at odd positions are odd. The digits are enumerated from left to right starting from 1. For example, the number 1478 is boring as the odd positions include the digits {1, 7} which are odd and even positions include the digits {4, 8} which are even.
Given two numbers L and R, Ron wants to count how many numbers in the range [L, R] (L and R inclusive) are boring. Ron is unable to solve the problem, hence he needs your help.
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line with two numbers L and R.
Output
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the count of boring numbers.
Sample
3
5 15 Case #1: 6
120 125 Case #2: 3
779 783 Case #3: 2
And this is the result which I have written.
t = int(input())
for case in range(1, t+1):
total_number = 0
numbers = []
l, r = map(int, input().split())
for number in range(l, r+1):
answer = False
for x in range(len(str(number))):
position = x+1
pos_num = int(str(number)[x])
if ((position%2 == 0) and (pos_num%2 == 0)) or ((position%2 ==1) and (position%2 == 1)):
answer = True
else:
answer = False
if answer == True:
numbers.append(number)
total_number += 1
print(f"Case #{case}: {total_number}")
I am running this and getting the wrong results. Where am I doing wrong?
Sorry guys, I got the answer. This is the answer but if anyone can suggest a more efficient answer then, you are most welcome!
t = int(input())
for case in range(1, t + 1):
total_number = 0
numbers = []
l, r = map(int, input().split())
for number in range(l, r + 1):
answer = []
lst_number = list(str(number))
for x in range(len(lst_number)):
position = x + 1
pos_num = int(lst_number[x])
if ((position % 2 == 0) and (pos_num % 2 == 0)) or ((position % 2 == 1) and (pos_num % 2 == 1)):
answer.append(1)
else:
answer.append(0)
if 0 not in answer:
numbers.append(number)
total_number += 1
print(f"Case #{case}: {total_number}")

How do I check divisibility in python? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am writing a python script right now to check if a number a Wilson Prime, but it says I have a syntax error on line 9.
I've tried both the mod function with x%y == 0 and x/y == int, but both of them have given me a syntax error.
n = int(input("Type a natural number here"))
fact = 1
for i in range(1,n):
fact = fact * i
finalfact = fact + 1
if finalfact % n == 0
print(n, "is a prime number!")
if (finalfact/n) % n == 0
print(n, "is also a Wilson Prime!")
I'm trying to make it check if (n-1)!+1 is divisible by n (which is a way to find prime numbers) and to check if (n-1)!+1 is divisible by n^2 (Wilson Primes), but it gives me a syntax error on line 9 and nothing happens.
You are missing : at the end of if statements.
Change:
if finalfact % n == 0
To:
if finalfact % n == 0:
And:
if (finalfact/n) % n == 0
To:
if (finalfact/n) % n == 0:
Need to indent the code properly:
Change:
for i in range(1,n):
fact = fact * i
To:
for i in range(1,n):
fact = fact * i
Also:
finalfact / n # 5 / 2 = 2.5
Should be:
finalfact // n # 5 // 2 = 2

Project Euler #1 python code not working [closed]

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]!

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.

Python redundancy [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
If I have the code
i = 0
while i < N:
print("Hello")
i += 1
how many times will Hello be printed out? (assume that N is a defined integer)
Answers:
0
N
N-1
N+1
more than N+1
and why? I never get this so I would appreciate of somebody could explain.
The best way to figure it out is to go through it by hand for a few manageable values of N. For instance, if N is 2:
i == 0 and 0 < 2 → print "hello", increment i
i == 1 and 1 < 2 → print "hello", increment i
i == 2 and 2 < 2 → while-loop condition is no longer satisfied → loop ends
So for N = 2, "hello" is printed 2 times. See the pattern?
Hello will be printed out N times.
assume N is 3.
1st iteration
i = 0
i is less than N
print hello
i = i + 1; // i = 1
2nd iteration
i = 1;
i` is less thanN (3)`
print hello
i = i + 1; // i = 2
3rd iteration
i = 2;
i is less than N (3)
print hello
i = i + 1; // i = 3
4th iteration
i = 3;
i is equal to N (3)
break loop
As the other answers described, it would print N times, because it starts at 0 and goes until it is just before N, not equal to N.
In reality, though, this is very redundant in Python. A much easier way to do this, making it a bit more readable (and hopefully easier for you to understand):
N=3
for x in range(0,N):
print "This is loop %d" % (x)
This loop will print from 0 to N, which is really just N amount of times.

Categories

Resources