Keep on halving by integer division until x=1 - python

The function is to take a positive integer n and divide it by 2 (using integer division) until it reaches 1. The output should be the number of times that value is divided. My code so far is
def keep_halving(x):
i=1
for i in range(x):
if x//2==0:
return i
An example of how the function should run is
>>>keep_halving(4)
2

You could try this:
n = int(input("enter number"))
while n > 1:
n //= 2
print (n)
Input: 128
Output:
enter number128
64
32
16
8
4
2
1
This will continuously divide by two using the while loop and stop when n gets to one.
Edit: I read your question too fast. Here is updated code:
count = 0
n = int(input("enter number"))
while n > 1:
n //= 2
print (n)
count +=1
print (count)
This will add one onto count each time n is divided by two.
Input : 128
Output :
enter number128
64
32
16
8
4
2
1
7

Related

line 1, in <module> F,S = list(map(int,input().split())) ValueError: not enough values to unpack (expected 2, got 1)

i am getting errors about listing
i think its because of some inputs have only one integer
i tried seperating them with map split but it didnt work out
Question:
Enter two integers then compare their values.
The first line of the input consist of a single integer number t which determines the number of tests.
In each of next t lines there are two numbers m and n that are separated by a space character.
sample input:
Input Format:
5
9 2
-3 -5
5 28
0 0
19 13
sample output:
9 is greater than 2
-3 is greater than -5
5 is smaller than 28
n is equal m: 0
19 is greater than 13
my code:
n,m = list(map(int,input().split()))
int(n)
int(m)
if n > m:
print(n+('is greater than'+m))
if m < n:
print(m+('is smaller than'+n))
if m > n:
print(m+('is greater than'+n))
if n < m:
print(n+('is smaller than'+m))
if n == m:
print(n+('is equal'+m))
This erros is happening because you try to separate n and m in the first input.
However, the first input should be a loop control bariable.
An example of the code would be:
control = int(input("Control variable: "))
for x in range(control):
n,m = list(map(int, input().split()))
if n > m:
print(f'{n} is grater than {m}')
elif m > n:
print(f'{m} is grater than {n}')
else:
print(f'{n} is equal to {m}')
x += 1
after, you can perform a check if the user actually passed two numbers.

Loop while basics in python 3

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

add up even numbers in list using two nested for loops and the str() function

I am trying to get all of the even numbers from the list, using two nested loops and using str(). My code works, just not how I am intending it to and it is short of what I am looking for.
def evnNmbr ():
a = int(input("Enter 1st integer (lower) "))
b = int(input("Enter 2nd integer (higher) "))
evnCnt = 0
for i in range (a, b):
if i % 2 == 0:
evnCnt += 1
s = str(i)
print("Even number count is , ", s, evnCnt)
evnNmbr()
Ex
Enter 1st integer (lower) 0
Enter 2nd integer (higher) 21
Even number count is , 0 1
Even number count is , 2 2
Even number count is , 4 3
Even number count is , 6 4
Even number count is , 8 5
Even number count is , 10 6
Even number count is , 12 7
Even number count is , 14 8
Even number count is , 16 9
Even number count is , 18 10
Even number count is , 20 11
I would like to get the total number of even numbers between the range of numbers a and b. ie: (2, 4, 6, 8 = 4 even numbers
You just need to print the result evn_cnt once at the end
def evnNmbr():
a = int(input("Enter 1st integer (lower) "))
b = int(input("Enter 2nd integer (higher) "))
evn_cnt = 0
for i in range(a, b):
if i % 2 == 0:
evn_cnt += 1
print("Even number count is", evn_cnt)
See
Enter 1st integer (lower) 10
Enter 2nd integer (higher) 88
Even number count is 39
This is going to be your simplest solution
def find_evens(a,b):
l = []
for i in range(a,b):
if i % 2 == 0:
l.append(i)
answer = len(l)
return answer
print(find_evens(1,21))
I added range of b + 1, because the range function excludes the last value, so if you put an even number at the end it wouldn't count. The only thing you have to modify really is to print separately the evnCnt variable, so it only shows the total value.
def evnNmbr ():
a = int(input("Enter 1st integer (lower) "))
b = int(input("Enter 2nd integer (higher) "))
evnCnt = 0
for i in range (a, (b + 1)):
if i % 2 == 0:
evnCnt += 1
# s = str(i)
# print("Even number count is , ", s)
# if you still want to visualize every number separately you can uncomment the lines
print(f"Even number count is: {evnCnt}")
evnNmbr()

python simple basic program on geeksforgeeks

Can anyone help me with the solution of this ?
Given a number N, print all the composite numbers less than or equal to N. The number should be printed in ascending order.
Input:
The first line contain an Integer T denoting the number of test cases . Then T test cases follow. Each test case consist of an single integer N.
Output:
Print all the composite Number form 0 to N.
Constraints:
1 ≤ T ≤ 50
4 ≤ N ≤ 10000
Example:
Input:
2
10
6
Output:
4 6 8 9 10
4 6
My solution is as below :
def comp(n):
for i in range (4,n+1):
for j in range(2,i):
if i % j == 0 :
print(i)
break
t = int(input(""))
while(t >=1 & t <= 50):
for k in range(0,t):
p = int(input(""))
if(p >=4 & p <= 10000):
comp(p)
but giving EOFError on p = int(input(""))
This error occurs when you are providing lesser input values than required. Your program is expecting more input's than you actually provided.
if you are using a pipe to send data to stdin of the script then make sure each input is sent in a newline as shown below.
time echo -e "2\n'3 4 5 6 7'\n3" | python sample.py
The culprit here is the while loop instead of if. As, the t is a constant value, the while loop will never end and thus, p = int(input("")) will get executed more than the required times. Hence, EOFError on p = int(input("")).
A simple solution using recursion.
def check_prime(n):
for i in range(2,int(math.sqrt(n))+1):
if(n%i==0):
return 0
return 1
def print_composite(n):
if(n<5):
print(n),
return
print_composite(n-1)
if(check_prime(n)==0):
print(n),
return
Sample outputs from my terminal
>>> print_composite(10)
4 6 8 9 10
>>> print_composite(6)
4 6
>>> print_composite(16)
4 6 8 9 10 12 14 15 16

Sum of all the multiples of 3 or 5 below 1000

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

Categories

Resources