I'm trying to improve my algorithm skills. When I run my code, I get an "Execution Timed Out" error.
Pseudocode
[This is writen in pseudocode]
if(number is even) number = number / 2
if(number is odd) number = 3*number + 1
My Code
def hotpo(n):
calculator = 0
while n >= 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
calculator = calculator + 1
return calculator
you are dividing number by 2 if number is even but multiplying it by 3 and adding 1 into it.
so for any number it will keep doing this
2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,.....
you just have to change condition to n>1 in while loop
because at last 2 will come and it got divided by 2, then n becomes 1 then again it will consider 1 as odd as per your condition then again 1*3+1=4 and again 4/2=2 and so on...
I hope you understood..
Related
I'm trying to do the Collatz conjecture on a list of numbers to check which one is "holding" the most. the problem is the code keeps telling me "TypeError: unsupported operand type(s) for %: 'list' and 'int'"
Collatz = range(1, 1001)
counting = 0
print(Collatz)
while Collatz != 1:
if Collatz % 2 == 0:
Collatz = int(Collatz / 2)
print(Collatz)
counting += 1
else:
Collatz = int(Collatz * 3 + 1)
print(Collatz)
counting += 1
print(counting)
if it's with input it works great...
Would appreciate help :)
try to get a list of all of the ranges, with a number and how long it took to get to "1" or just which one is the longest.
for example:
number 1 took 1 steps to get to "1"
number 2 took 2 steps to get to "1"
number 3 took 8 steps to get to "1" etc
or
number 153 took 736 steps to get to "1" (IDK, just for the example)
This code will work:
def get_collatz(n):
i=1
while True:
if n % 2 == 0:
n /= 2
else:
n = 3 * n + 1
if n == 1:
return(i)
i += 1
for i in range(1, 100000):
print(i, get_collatz(i))
If you want to know the number that took most steps, you can do this:
steps = dict()
for i in range(1, 100000):
steps[i] = get_collatz(i)
n_max = max(steps, key=steps.get)
total_steps = steps[n_max]
print(f'Number {n_max} took {total_steps} steps to reach 1.')
This prints:
Number 77031 took 350 steps to reach 1.
You can also create a sorted dictionary:
sorted_steps = dict(sorted(steps.items(), key=lambda item: item[1]))
When you use range() you get a list of numbers in that range. Did you mean number instead of Collatz because in the for loop you are looping through the Collatz and the value is in number. And while loop isn't doing anything so I recommend removing it.
Use this code:
Collatz = range(1, 1001)
counting = 0
for number in Collatz:
if number % 2 == 0:
number = int(number / 2)
print(number)
counting += 1
else:
number = int(number * 3 + 1)
print(number)
counting += 1
print(counting)
I am reading a python basics book and there is one function which I don't understand how it works. How is is possible that output looks like pow function even there are not any ** or pow operation? Would be nice if anyone can help because I am getting more and more frustrated
loop while
summary = 1
number = 1
while number <= 6:
i = 1
p = number
while i < 5:
p *= number
i += 1
print(number, "to 5", p)
summary += p
number += 1
print("sum of fifth powers of numbers from 1 to 6 is", summary)
output
1 to 5 1
2 to 5 32
3 to 5 243
4 to 5 1024
5 to 5 3125
6 to 5 7776
sum of fifth powers of numbers from 1 to 6 is 12202
Let me explain this code briefly,
first we are defining,
> summary = 1
> number = 1
Here we are defining and initialising the two variables summary and number.
> while number <= 6:
> i = 1
> p = number
In above code we are starting a while loop which will run while the value of number variable is less than or equal to 6. So, the loop will run from 1 to 6. we are taking a variable i = 1 and p = number here.
> while i < 5:
> p *= number
> i += 1
> print(number, "to 5", p)
> summary += p
> number += 1
> print("sum of fifth powers of numbers from 1 to 6 is", summary)
Now, we are having an another nested while loop and this will run for the values 1 to 4 of i variable. As we can see in the loop, the variable p will be multiplied with itself for 4 times so we will get the 5th power of the particular number. then we are increasing value of number by 1 and adding the value of 5th power in variable summary and lastly we are printing that.
Let me explain with an example
when number=2 (i.e after finding fifth power of 1)
value of p=2 and i=1
then inner loop i.e
while i<5 :
p* = number //i.e p = p*number
i+= 1 //i.e i=i+1
goes like this,
iteration 1: p= 2*2 i.e p=4
i=1+1 i.e i=2 which is less than 5
iteration 2: p= 4*2 i.e p=8
i=2+1 i.e i=3 which is less than 5
iteration 3: p= 8*2 i.e p=16
i=3+1 i.e i=4 which is less than 5
iteration 4: p= 16*2 i.e p=32
i=4+1 i.e i=5 which is equal to 5, so it comes out of loop
therefore, 2 to 5=32
this is how we get fifth power of a number
I tried to do the codewars Sum of Digits/Digital Root problem, where you have to:
Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.
So passing through 52 would return 7, as 5 + 2 is 7 and passing through 942 would return 6, as 9 + 4 + 2 = 15 and then 1 + 5 = 6.
I came up with this code:
def digital_root(n):
n_str = str(n)
digit_total = 0
while len(n_str) != 1:
for digit in n_str:
digit_total += int(digit)
n_str = str(digit_total)
return(n_str)
But it only works for 2 digit numbers and it won't work for higher digit numbers, it just endlessly runs. This code is probably a bad way to do it and I've looked over other people's answers and I get their solution but I just don't get why this won't work for higher digit numbers.
You have got your program almost right. The only challenge I see is with resetting the variable digit_total = 0 after each iteration.
def digital_root(n):
n_str = str(n)
while len(n_str) != 1:
digit_total = 0 #move this inside the while loop
for digit in n_str:
digit_total += int(digit)
n_str = str(digit_total)
return(n_str)
print (digital_root(23485))
The output for print (digital_root(23485)) is 4
2 + 3 + 4 + 8 + 5 = 22
2 + 2 = 4
If the digit_total = 0 is not inside the while loop, then it keeps getting added and you get a never ending loop.
While you have a lot of code, you can do this in a single line.
def sum_digits(n):
while len(str(n)) > 1: n = sum(int(i) for i in str(n))
return n
print (sum_digits(23485))
You don't need to create too many variables and get lost in keeping track of them.
Alex,
running a recursive function would always be better than a while loop in such scenarios.
Try this :
def digital_root(n):
n=sum([int(i) for i in str(n)])
if len(str(n))==1:
print(n)
else:
digital_root(n)
I'm new to programming. While trying to solve this problem, I'm getting the wrong answer. I checked my code a number of times but was not able to figure out the mistake. Please, help me on this simple problem. The problem is as follows:
Given a positive integer N, calculate the sum of all prime numbers between 1 and N (inclusive). The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains one line of input containing N. For each testcase, in a new line, print the sum of all prime numbers between 1 and N.
And my code is:
from math import sqrt
sum = 0
test = int(input())
for i in range(test):
max = int(input())
if max==1:
sum = 0
elif max==2:
sum += 2
else:
sum = sum + 2
for x in range(3,max+1):
half = int(sqrt(max)) + 1
for y in range(2,half):
res = x%y
if res==0:
sum = sum + x
break
print(sum)
For input 5 and 10, my code is giving output 6 and 48 respectively, while the correct answer is 10 and 17 respectively. Please, figure out the mistake in my code.
Here, I implemented simple program to find the sum of all prime numbers between 1 to n.
Consider primeAddition() as a function and ip as an input parameter. It may help you to solve your problem.Try it.
Code snippet:
def primeAddition(ip):
# list to store prime numbers...
prime = [True] * (ip + 1)
p = 2
while p * p <= ip:
# If prime[p] is not changed, then it is a prime...
if prime[p] == True:
# Update all multiples of p...
i = p * 2
while i <= ip:
prime[i] = False
i += p
p += 1
# Return sum of prime numbers...
sum = 0
for i in range (2, ip + 1):
if(prime[i]):
sum += i
return sum
#The program is ready... Now, time to call the primeAddition() function with any argument... Here I pass 5 as an argument...
#Function call...
print primeAddition(5)
This is the most broken part of your code, it's doing the opposite of what you want:
res = x%y
if res==0:
sum = sum + x
break
You only increment sum if you get through the entire loop without breaking. (And don't use sum as you're redefining a Python built-in.) This can be checked using the special case of else on a for loop, aka "no break". I've made that change below as well as corrected some inefficiencies:
from math import sqrt
T = int(input())
for _ in range(T):
N = int(input())
sum_of_primes = 0
if N < 2:
pass
elif N == 2:
sum_of_primes = 2
else:
sum_of_primes = 2
for number in range(3, N + 1, 2):
for odd in range(3, int(sqrt(number)) + 1, 2):
if (number % odd) == 0:
break
else: # no break
sum_of_primes += number
print(sum_of_primes)
OUTPUT
> python3 test.py
3
5
10
10
17
23
100
>
A slight modification to what you have:
from math import sqrt
sum = 0
test = int(input())
max = int(input())
for x in range(test,max+1):
if x == 1:
pass
else:
half = int(sqrt(x)) + 1
for y in range(2,half):
res = x%y
if res==0:
break
else:
sum = sum + x
print(sum)
Your biggest error was that you were doing the sum = sum + x before the break rather than outside in an else statement.
PS: (although you can) I'd recommend not using variable names like max and sum in your code. These are special functions that are now overridden.
Because your logic is not correct.
for y in range(2,half):
res = x%y
if res==0:
sum = sum + x
break
here you check for the factors and if there is a factor then adds to sum which is opposite of the Primes. So check for the numbers where there is no factors(except 1).
from math import sqrt
test = int(input())
for i in range(test):
sum = 0
max = int(input())
if max==1:
sum = 0
elif max==2:
sum += 2
else:
sum = sum + 2
for x in range(3,max+1):
half = int(sqrt(x)) + 1
if all(x%y!=0 for y in range(2,half)):
sum = sum + x
print(sum)
First of all, declare sum to be zero at the beginning of the for i loop.
The problem lies in the if statement at almost the very end of the code, as you add x to the sum, if the res is equal to zero, meaning that the number is indeed not a prime number. You can see that this is the case, because you get an output of 6 when entering 5, as the only non-prime number in the range 1 to and including 5 is 4 and you add 2 to the sum at the beginning already.
Last but not least, you should change the
half = int(sqrt(max)) + 1
line to
half = int(sqrt(x)) + 1
Try to work with my information provided and fix the code yourself. You learn the most by not copying other people's code.
Happy coding!
I believe the mistake in your code might be coming from the following lines of code:
for x in range(3,max+1):
half = int(sqrt(max)) + 1
Since you are looping using x, you should change int(sqrt(max)) to int(sqrt(x)) like this:
for x in range(3,max+1):
half = int(sqrt(x)) + 1
Your code is trying to see if max is prime N times, where you should be seeing if every number from 1-N is prime instead.
This is my first time answering a question so if you need more help just let me know.
So I know that this is something simple that can be done without a recursion function but I need to know the backside to this as I can't seem to figure out how to write this using recursion. im using this so far
n = int(raw_input("What is n? "))
def digit(n):
if n< 10:
return 1
else:
new = n/10
print 1 + digit(new/10)
return 1 + digit(new/10)
digit(n)
Now if I type in a number such as 33 then it outputs 2 but if I do a longer number then it doesn't print it properly and I was unsure as to what exactly it wrong with it.
The problem is,
new = n/10
return 1 + digit(new/10)
You are already dividing the number by 10, in new = n / 10, which reduces the last digit and you are again dividing it by 10 before calling digit. So, you are ignoring 1 digit in every recursive call.
Instead, you can simply do
return 1 + digit(n / 10)
or
new = n / 10
return 1 + digit(new)
#!/usr/bin/python
n = int(raw_input("What is n? "))
def digit(n):
if n < 10:
return 1
else:
return 1 + digit(n/10)
print digit(n)
You can do like this too.
def counter(number):
if(number == 0):
return 0
return counter(int(number/10)) + 1
number = 1998
print(counter(number)) // it will print 4