Assignment to gather upper limits and squared integers - python

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

Related

how to use while loop?

number = 50
while number >= 0:
if number % 5 == 0:
print(number)
number = number - 1
elif number % 5 == 1:
continue
number = number = number - 1
the answer it's giving me is 50 then the loop stops executing
Here is the program I am trying to make:
While Loops Practice #2
Create a While Loop that subtracts one by one the numbers from 50 to 0 (both numbers included) with the following additional conditions:
If the number is divisible by 5, show that number on the screen (remember that here you can use the modulus operation dividing by 5 and checking the remainder!)
If the number is not divisible by 5, continue executing the loop without showing the value on the screen (don't forget to continue subtracting so that the program doesn't run infinitely).
Here is your code, improved:
number = 50
while number >= 0:
if number % 5 == 0:
print(number)
number = number - 1
I'm confused about that too, but here are my thoughts: you only subtracted when number % 5 == 1, but it can also be 2, 3, 4 or 5.
num = 50
while num != 0:
if num % 5 == 0:
print(num)
num -= 1
would work for this as it will only print the number if it is divisible by 5, and always subtract.
Make sure you always subtract 1 from number before continuing the loop. As the prompt reminds you, this is especially important when you use the continue statement, since that brings you straight back to the top of the loop -- if you haven't subtracted before then, the loop will repeat infinitely!
One way to make sure that something always happens even if execution is interrupted (not just a continue but maybe a return, a break, a raise, etc) is try/finally:
number = 50
while number >= 0:
try:
if number % 5 == 0:
print(number)
elif number % 5 == 1:
continue
finally:
number -= 1
prints:
50
45
40
35
30
25
20
15
10
5
0
In this case, though, there's no need to immediately continue the loop, since there's nothing in the loop that you explicitly need to skip in the number % 5 == 1 case (note that this isn't the same as "not divisible by 5" -- what you're testing for here is "has a reminder of 1 after dividing by 5", i.e. 1, 6, 11, and so on, which isn't part of the problem statement).
You can therefore just do:
number = 50
while number >= 0:
if number % 5 == 0:
print(number)
number -= 1
The main structure is corret, but in the last line you wrote two times the code "number =" and "else" is useless in this case, because you need to substract 1 in every loop.
here's the code solved:
number = 50
while number != 0:
if (number%5) == 0:
print(number)
number = number - 1

Squaring numbers in a loop

I have this python problem:
Write a program that asks the user for a limit, and then prints out
the sequence of square numbers that are less than or equal to the
limit provided.
Max: 10
1
4
9 ​
Here the last number is 9 because the next square number (16) would be
greater than the limit (10).
Here is another example where the maximum is a square number:
Max: 100 1
4
9
16
25
36
49
64
81
100
But I don't exactly know how to do this. So far I have
maximum = int(input("Max: "))
for i in range(1, maximum):
But don't really know how to process the numbers and squaring them.
Thanks
Edit: I have
maximum = int(input("Max: "))
for i in range(1, maximum):
if i*i <= maximum:
print(i*i)
'''
Ask the user input a limit and
convert input string into integer value
'''
limit = int(input("Please input the limit: "))
'''
Extract the squre root of `limit`.
In this way we discard every number (i) in range [0, limit]
whose square number ( i * i ) is not in range [0, limit].
This step improves the efficiency of your program.
'''
limit = int(limit ** .5)
'''
`range(a, b)` defines a range of [a, b)
In order to exclude zero,
we assign `a = 1`;
in order to include `limit`,
we assign `b = limit + 1`;
thus we use `range(1, limit + 1)`.
'''
for i in range(1, limit + 1):
print(i * i)
I think a while loop may be better suited for this problem.
maximum = int(input("Max: "))
i = 1
while(i*i <= maximum):
print(i*i)
i+=1
First, the simplest change to your existing code is to get rid of that nested loop. Just have the for loop and an if:
for i in range(1, maximum+1):
if i*i > maximum:
break
print(i*i)
Or just have the while loop and increment manually:
i = 1
while i*i <= maximum:
print(i*i)
i += 1
One thing: Notice I used range(1, maximum+1)? Ranges are half-open: range(1, maximum) gives us all the numbers up to but not including maximum, and we need to include maximum itself to have all the numbers up to maximum squared, in case it's 1. (That's the same reason to use <= instead of < in the while version.
But let’s have a bit more fun. If you had all of the natural numbers:
numbers = itertools.count(1)
… you could turn that into all of the squares:
squares = (i*i for i in numbers)
Don’t worry about the fact that there are an infinite number of them; we’re computing them lazily, and we’re going to stop once we pass maximum:
smallsquares = itertools.takewhile(lambda n: n<=maximum, squares)
… and now we have a nice finite sequence that we can just print out:
print(*smallsquares)
Or, if you’d prefer if all on one line (in which case you probably also prefer a from itertools import count, takewhile):
print(*takewhile(lambda n: n<=maximum, (i*i for i in count(1)))
But really, that lambda expression is kind of ugly; maybe (with from functools import partial and from operator import ge) it’s more readable like this:
print(*takewhile(partial(ge, maximum), (i*i for i in count(1)))
You got a few good, detailed answers.
But let's also have some fun, here is a one-line solution:
print(*(x**2 for x in range(1, 1 + int(int(input('Limit: '))**(1/2)))))
I have decided to post the answer that works. Thanks all for the help.
maximum = int(input("Max: "))
for i in range(1, maximum + 1):
if i*i <= maximum:
print(i*i)
THE BELOW PROGRAM IS TO FIND SQUARE VALUE OF GIVE NUMBERS
Enter the value you want to find.(Give a range)
the value you give runs and goes to r command.
i have used for loop in this case.
output will be displayed
give the input
maximum = input("Enter Max: ")
r = range(1, maximum)
Square = maximum * maximum
Execute THE loop
for i in r:
if i * i <= Square:
print (i * i),

For triangular numbers, how do I check the next input in the equation is greater than the limit?

I have a program where the user inputs a limit, and then prints out the sequence of triangular numbers that are less than or equal to the limit provided. The triangular numbers should be printed out one number per line. However, I cannot solve if e.g. The limit is 18 and the number is currently 15, it will print the next number even though that next number will be greater than the limit, 18.
Here's my code:
limit = int(input("Limit: "))
n = 0
x = 1
while x <= limit and (x + 1) * ((x+1) + 1) / 2 <= limit:
n = n + 1
x = n * (n + 1) / 2
print(int(x))
So pretty much what I'm trying to do here is while the number is less than the limit and while the next number after that is less than the limit it prints it but doesn't seem to work. Some tips would be so good, I'm pretty stuck, thanks! :)
Hint: see how you need to change your code to print at the start of the loop, not at the end.
The effect will be that you'll print right after you've checked the terminal condition and so won't be printing any extraneous numbers.
Right now you're checking the terminal condition, then doing some calculation, then printing the result of the calculation (when the terminal condition might no longer hold).

Sum of Even Fibonacci Numbers < X

I'm working on this one and I seem to have a working solution but I have difficulty understanding its behaviour.
Here is what I have.
#!/usr/bin/python
def even_fib_sums(limit):
number = 1
last = 0
before_last = 0
total = 0
for counter in range (0,limit):
before_last = last
last = number
number = before_last + last
if not number % 2:
total += number
yield total
print sum(even_fib_sums(4000000))
I'm new to programming but it makes sense to me that this is not very effective considering I need to cycle through all 4000000 numbers in the range.
If I use the same approach in generating the Fibonacci sequence up to 5 as follows, you will see the results below.
def generate_fib(limit):
number = 1
last = 0
before_last = 0
total = 0
for counter in range (0,limit):
before_last = last
last = number
number = before_last + last
print number
generate_fib(5)
Result: 1,2,3,5,8
Of these numbers in the result, only 2 and 8 % 2 == 0.
The sum should be 10 but I am returning 12 if I am to use the first snippet above. Why so?
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
You only need to loop until you hit a fib that is > 400000 not the 4 millionth fibonacci number which your code is trying to do, you can simplify to a using generator function with sum, only yielding even numbers and breaking the loop when you hit a fibonacci number > 4000000:
def fib(n):
a, b = 0, 1
while a <= n:
a, b = b, a + b
if not b & 1:
yield b
print(sum(fib(4000000)))
It takes a fraction of a second to compute:
In [5]: timeit sum(fib(4000000))
100000 loops, best of 3: 6 µs per loop
trying to timeit even_fib_sums(4000000) is still running after a few minutes.
by using for counter in range(0, limit) you are having 'limit' iteration in your function. for example, if your 'limit' variable is 10, you won't have the sum of even fibonachi numbers that are less than 10, but you will have the sum of the first 10 fibonachi numbers that are even.
To make your code works properly, you need to remplace for counter in range(0, limit) by while last < limit, and each time you find that last is even, you add it to total.
You can probably clean up that generating function a bit. Here is how I would write it.
def fib(x):
a = 1
b = 1
yield a
yield b
a,b = b,a+b
while b<=x:
yield b
a,b = b,a+b
This will give you a generating function which will give you all Fibonacci numbers less than or equal to x (we should be a little more careful here, as we will return the first two numbers no matter what).
Then we can just do
sum(x for x in fib(4000000) if x%2==0)
You should change your code to just yield the number, not the sum or just change yield to return, and remove the sum() keyworkd like this:
def even_fib_sums(limit):
number = 1
last = 0
before_last = 0
total = 0
for counter in range (0,limit):
before_last = last
last = number
number = before_last + last
if not number % 2:
total += number
return total
print even_fib_sums(5)
In the first code snippet, you sum the total of round numbers, instead of just yielding the number. If you expect to get 10 in your first snippet for an input of 5, you should amend the code in either of the following ways (not trying to be efficient here, just to fix the problem):
...
number = before_last + last
if not number % 2:
yield number
print sum(even_fib_sums(4000000))
or
...
number = before_last + last
if not number % 2:
total += number
return total
print even_fib_sums(4000000)

Optimized way for finding the number which satisfies specific conditions

I saw this question somewhere.
There is a 8 digit number. First digit from left to right tells how many zeroes in the number. Second digit tells you how many 1s in the number, third digit tells u how many 2 in the number and so on till 8th digit which tells u how many 7 in the number. Find the number.
So I wrote a piece of code in python to find out the digit. Apart from the conditions mentioned above, I have few additional checks like 'sum of digits should be 8' and 'no 8 or 9 should be present in the number'. I've pasted the code below. This is just brute force since I take every number and check for conditions. I was curious to know if there is any better way of solving the problem
def returnStat(number, digit, count):
number = str(number)
digit = str(digit)
print "Analysing for ",digit," to see if it appears ",count, " times in ",number,"."
actCnt = number.count(digit)
count = str(count)
actCnt = str(actCnt)
if (actCnt == count):
return 1
else:
return 0
def validateNum(number):
numList = str(number)
if '8' in numList:
print "Skipping ",number, " since it has 8 in it"
return (-1)
elif '9' in numList:
print "Skipping ",number, " since it has 9 in it"
return (-1)
elif (sum(int(digit) for digit in numList) != 8):
print "Skipping ",number, " since its sum is not equal to 8"
return (-1)
index = 0
flag = 0
for num in numList:
if (returnStat(number,index,num)) :
index = index+1
continue
else:
flag = 1
break
if (flag == 1):
return (-1)
else:
return number
for num in range(0,80000000):
number = '{number:0{width}d}'.format(width=8,number=num)
desiredNum = "-1"
desiredNum = validateNum(number)
if (desiredNum == -1):
print number," does not satisfy all "
continue
else:
print "The number that satisfies all contition is ",number
break
You can go further than to simply say that digits of 8 or 9 are impossible.
Can the last digit ever be greater than 0? The answer is no. If the last digit was 1, this means there is one 7 somewhere else. However, if there is a 7, it means that the same number has occurred 7 times. This is clearly impossible. Thus the last digit has to be 0.
So we have xxxxxxx0.
What about the second to last digit?
If xxxxxx10, then there has to be at least one 6, which means the same number occurred 6 times. We can try 60000010, but this is incorrect, because there is a 1, which should be reflected in the second digit. The second to last digit can't be higher than 1 because 2 means there are 2 sixes, which in turn means one number occurred six times while another number also occurred 6 times, which is impossible.
So we have xxxxxx00.
If xxxxx100, then there has to be at least one 5, which means the same number occurred 5 times. Let us start with 51000100. Almost, but there are now 2 1s. So it should be 52000100. But wait, there are now one 1. and one 2. So we try 52100100. But now we only have 4 0s. We can't have xxxxx200 because this means there are 2 5s, which is impossible as explained above.
So we have xxxxx000.
If xxxx1000, we can try 40001000, nope, 41001000, nope, 42101000.
Ah there it is. 42101000.
Even if you iterate over all 8 digit numbers with no 8s or 9s in them, there's not many possibilities (actually, 8^8 = 1<<24 ~= 17 million).
Here's a naive program that tries them all:
import itertools
for digs in itertools.product(range(8), repeat=8):
counts = [0] * 8
for d in digs:
counts[d] += 1
if counts == list(digs):
print digs
It completes (with exactly one solution) in 15 seconds on my machine.
To make it faster, you can only consider 8-digit numbers whose digits add up to 8. Here's the same code as before, but now it uses sum_k to produce the possibilities. (sum_k(n, k) generates all n-digit tuples where all the digits are less than 8 which sum to k).
def sum_k(n, k):
if k < 0 or n * 7 < k: return
if n == 1:
yield k,
return
for d in xrange(8):
for s in sum_k(n-1, k-d):
yield (d,) + s
for digs in sum_k(8, 8):
counts = [0] * 8
for d in digs:
counts[d] += 1
if counts == list(digs):
print digs
This code completes in 0.022 seconds on my machine.
Adapting the code to solve the general case produces these solutions:
1210
2020
21200
3211000
42101000
521001000
6210001000
72100001000
821000001000
9210000001000

Categories

Resources