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
Related
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..
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
I ran an experiment in which I got 6 different orders of size and now I'm trying to see if my observations are significant. I have to perform a MC simulation to get a p value to see if my observed values are unusually large or small compared to the null.
I need to:
Set up a scheme where Order 1 is 0 to 1/6, Order 2, is 1/6- to 2/6, order 3 is 2/6 to 3/6
Generate 20 random numbers between 0 and 1 and allocate them to these bins. If the number if < 1/6 put it in bin 1, if it is between 1/6 and 2/6 into bin 2 etc. -
I should have 6 new numbers, one for each bin, that add up to 20, but my output is saying 0. Im new to python so what am I doing wrong?
My code is here:
from random import randint
from random import seed
# seed random number generator
seed(1)
counter = 0
chi_sq_values = []
# want 10,000 simulations
while counter < 10000:
# will eventually mimic your real six orders of size
sim_orders = [0, 0, 0, 0, 0, 0]
# generating 20 random numbers
for i in range(20):
numbers = randint(0, 1)
if 0 <= numbers <= 1 / 6:
numbers += sim_orders[0]
if 1 / 6 <= numbers <= 2 / 6:
numbers += sim_orders[1]
if 2 / 6 <= numbers <= 3 / 6:
numbers += sim_orders[2]
if 3 / 6 <= numbers <= 4 / 6:
numbers += sim_orders[3]
if 4 / 6 <= numbers <= 5 / 6:
numbers += sim_orders[4]
if 5 / 6 <= numbers <= 6 / 6:
numbers += sim_orders[5]
print(sim_orders)
You're not incrementing the values in sim_orders. You're adding the value in sim_orders to numbers, which has no effect because the value is always 0. And then you're not doing anything with numbers after you add to it.
You should increment the appropriate counter in sim_orders.
You need to use random.random(), not random.randint(0, 1). The latter will just return 0 or 1, not a number between 0 and 1.
for i in range(20):
numbers = random.random()
if numbers <= 1 / 6:
sim_orders[0] += 1
elif numbers <= 2 / 6:
sim_orders[1] += 1
elif numbers <= 3 / 6:
sim_orders[2] += 1
elif numbers <= 4 / 6:
sim_orders[3] += 1
elif numbers <= 5 / 6:
sim_orders[4] += 1
else:
sim_orders[5] += 1
You should also use elif for a sequence of mutually exclusive conditions, to avoid unnecessary tests. And if you do this, you don't need to test both ends of the range, since the previous test precludes numbers lower than the bottom of the range.
Your conditions overlapped -- if numbers was an exact multiple of 1/6 it would be put into both bins.
You can also get rid of all the if statements entirely:
sim_orders[floor(numbers*6)] += 1
If you dont want to update your list sim_orders with zeros, then you should put it out of while cycle. Moreover I don't see where you update your list with generated numbers. And if you want your while cycle to be finite then you have to increment counter inside loop body.
Beginner here- trying to make a simple python program that will compute/answer this problem:
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.
Currently this is what I have:
a = 0
b = 0
while a < 1000:
a = a + 3
print (a)
while b < 1000
b = b + 5
print (b)
This will print all the numbers being considered. I just need to add them together and that's my answer.
I would like one of two things to happen, instead of the code that I have written:
I would like all of this to happen internally, and therefore not have to use the "print" function. The just print the sum of all of those multiples.
I would like all of this stuff to print, but then I want to be able to print the sum of all of them too. Is there a way to make the computer take the value of everything it has printed?
Actually this problem can be solved in O(1) instead of O(N) without using any loops or lists:
The required sum is the sum of all multiples of 3 plus sum of all multiples of 5 minus the sum of multiples of (3*5=15) below the given number 1000 (LIMIT=999). The sums are calculated as a sum of arithmetic series.
It can be calculated in following way:
LIMIT=999
# Get the upper bounds for the arithmetic series
upper_for_three = LIMIT // 3
upper_for_five = LIMIT // 5
upper_for_fifteen = LIMIT // 15
# calculate sums
sum_three = 3*upper_for_three*(1 + upper_for_three) / 2
sum_five = 5*upper_for_five*(1 + upper_for_five) / 2
sum_fifteen = 15*upper_for_fifteen*(1 + upper_for_fifteen) / 2
# calculate total
total = sum_three + sum_five - sum_fifteen
# print result with Python 3
print(int(total))
The result is:
>>>
233168
It is possible to do this in one line in Python using a generator expression:
print(sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0))
The range(1000) produces all the integers from 0 to 999 inclusive. For each one of those integers, if it is divisible by 3 or divisible by 5, then it is included in the result. The sum(...) function adds up all those numbers, and finally print(...) prints the result.
I would use a for loop to iterate over each number in your selected range. Then you can check if the modulus % is equal to 0, meaning it has no remainder when divided by those values, if so, add it to the total.
total = 0
for num in range(1000):
if num % 3 == 0 or num % 5 == 0:
print(num)
total += num
>>> total
233168
While a for loop would work, you could also use a generator expression and sum:
sum(n for n in range(1000) if n % 3 == 0 or n % 5 == 0)
def sum_multiply (n):
data = []
for num in range (1, n):
if num % 3 == 0 or num % 5 == 0:
data.append(num)
return sum(data)
sum_multiply(1000)
total=0
i=0
while i<1000:
if i%3==0 or i%5==0:
print(num)
total+=i
i+=1
print("Total is: ")
**with python**
print(sum([i for i in range(1,1000) if i%3==0 or i%5==0 ]))
I'm a python beginner and I'm trying to figure out the following below two python code samples. Both code looks same but printing a different result. The main function of the code is divisor summation.
CODE 1:
def divisor_sum(n):
no_div = 0
tot = int(n / 2) + 1
for i in range(1,tot):
if n % i == 0:
no_div += 1
print no_div
CODE 2:
def divisor2(m):
max_div = int(m / 2) + 1
val = 0
for x in range(1, max_div):
if m % x == 0:
val += x
print val
when calling the function?
divisor_sum(6)
divisor2(6)
Code ouput:
3
6
How it is producing two different results when both code samples are same?
Not exactly the same code:
CODE 1:
no_div += 1
CODE 2:
val += x
The first variant increments by 1 when a divisor is encountered:
no_div += 1
The second variant increments by the divisor:
val += x
This means that the first variant counts the number of divisors. The second variant sums the values of the divisors.
The divisors of 6 are 1, 2 and 3. So, there are a total of 3 divisors whose values sum to 6.
Code in first function i.e divisor_sum() will be giving you the count of divisors of a number (then name of function is misleading). On the other hand code in the second function i.e divisor2() will give you sum of all the divisors of a number.
both function has different code :
divisor_sum() has : "no_div += 1 " that means increment no_div by 1
divisor2() has :"val += x" which means increment the value of val by x i.e if x=2 then val will become val+2.