Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
So basically I want to do this generate a random number (this I know how to do) if that number is even (or number%2 == 0) then divide it by 2 then if the resulting number is odd (or number%2 > 0) then multiply by 3 and add 1. If that didn't make much sense here is an exmaple
Pick a number like 26 (this is even so divide by 2)
Resulting number is 13 (this is odd so multiply by 3 add 1)
Resulting number is 40 (this is even so divide by 2)
Continue this process until the number is == 1
I am not sure what loop to use to do this so any help is very appreciated! :)
number = # generate random number
while number != 1:
if number % 2: # if number is odd, multiply by 3, add 1
number *= 3
number += 1
else: # if number is even, divide by 2
number /= 2
You can run a bit of cheeky code to keep track of iterations, if you like:
num_iterations = 0
number = # generate random number
while number != 1:
num_iterations += 1
if number % 2:
number = number * 3 + 1
else:
number /= 2
Since you do not know how many steps would it take to get the number equal to one, i.e. the number of iterations is unknown , use a while loop:
number = # random number
while number != 1:
if number % 2:
number *= 3
number += 1
else:
number /= 2
Or another approach:
number = # random number
while True:
if number == 1:
break
elif number % 2: # odd
number *= 3
number += 1
else: # even
number /= 2
Related
We are given N as a natural number and we can do these 3 operations with him.
1)Subtract 1 from N
2)If it is even, divide by 2
3)If it divides 3, then divide by 3
We stop this when N becomes 1. We need to find minimal operations such that N will become 1
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'count' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER num as parameter.
#
def count(num):
count = 0
while num != 1:
if (num % 3 ==0 ):
count += 1
num = num / 3
elif((num -1) % 3 == 0):
count += 2
num = (num - 1) / 3
elif (num % 2 ==0):
count += 1
num = num / 2
else:
num = num - 1
count += 1
return count
This is my code. From 11 test cases it passed 9 and gave 2 wrong answers. I don't know for which test cases my code gives wrong answers. Can you help to understand where is problem?
You make an assumption that it is better to subtract 1 and divide by 3 first if you can, but that isn't always true.
Consider 16
Your solution would be 16-15-5-4-3-1 = 5 steps
Better solution:
16-8-4-2-1 = 4 steps
Probably not the most efficient solution but:
def count(num):
count1, count2 = float('inf'), float('inf')
if num == 1:
return 0
if num % 3 == 0:
count1 = 1 + count(num // 3)
if num % 2 == 0:
count2 = 1 + count(num // 2)
count3 = 1 + count(num - 1)
return min(count1, count2, count3)
These types of problems usually have a small set of rules that produce the optimal answer.
Your fundamental problem, though, is that you are assuming that your rule set is optimal with no evidence whatsoever. You really have no reason to believe that it will produce the right count.
Unfortunately, answers to these kinds of questions on SO sometimes provide the correct rule set, but always seem to omit any kind of proof that the rule set is optimal.
You have to do something that is guaranteed to work, so unless you have that kind of proof, you should fall back on an A* search or similar.
You may use the non-recursive breadth-first strategy.
Say there is a queue holding lists of numbers. Initially, enter a list holding just N into the queue. Then repeat the following until the queue is empty:
Pick the first list in the queue.
Repeat 3 for all three operations.
Select an operation. If possible, apply it to the last list number and add the result to the end of the list. If the list is a solution, store it somewhere. If not, add it to the end of the queue.
This strategy is exhaustive and finds all solutions. Since only the minimum is of interest, we introduce a limiting bound. Once a solution list is available, we do not enter lists longer than that into the queue, nor do we consider them if they are in the queue already.
My assignment is:
Please write a program which asks the user to type in an upper limit. The program then prints out numbers so that each subsequent number is the previous one doubled, starting from the number 1. That is, the program prints out powers of two in order.
The execution of the program finishes when the next number to be printed would be greater than the limit set by the user. No numbers greater than the limit should be printed.
Upper limit: 8
1
2
4
8
This is what I've written
limit = int(input("Upper limit:"))
number = 0
power = 0
while power < limit:
number += 1
power = number ** 2
print(power)
It's almost correct, except it'll print one row too many. For instance, if I input 50, I'll get:
1
4
9
16
25
36
49
64
I know it's because I put while power < limit, but I'm not sure what to do about it.
Edit: Also, I'm supposed to do this without the True conditional.
Hi and welcome to StackOverflow! You could use a break statement, which exits the loop when executed by the program, like below:
while True:
number += 1
power = number ** 2
if power < limit:
print(power)
else:
break
The loop in this example will continue forever or until the break statement because of the while True: line. This means it will keep executing until the limit is reached. I hope this answers your question!
You can either divide the limit by 2 or just change the starting variables like so:
limit = int(input("Upper limit:"))
number = 1
power = 1
while power < limit:
print(power)
number += 1
power = number ** 2
You can use log_2(limit) as like:
import math
limit = int(input("Upper limit:"))
n = int(math.log(limit, 2)) + 1
for i in range(n):
print(pow(2,i))
Most simple way:
One of possible ways:
limit = int(input("Upper limit:"))
BASE = 2
i = 0
while BASE ** i <= limit:
print(BASE ** i)
i += 1
Upper limit:8
1
2
4
8
This is the answer to the problem as written. Specifically you asked. "The program then prints out numbers so that each subsequent number is the previous one doubled, starting from the number 1."
First, assign a value of 1 to the number variable number = 1. Then, since each number is a doubling of the previous number you want to assign the multiple of the number variable to number, overwriting it number*=2. The numbers will increase as so: 1,2,4,8,16,32,64,128.
If you want to avoid printing the number that breaks the limit. You need to put print above the calculation. This is so that it always prints the previous value of number and not the next value which at the end, will always be over the limit.
limit = int(input("Upper limit:"))
number = 1
while number <= limit:
print(number) # print must be before the calculation to ensure it breaks loop without printing the first number above the limit
number *= 2 # multiply and operator. number *= 2 means number = number*2
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.
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.
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]!