How can we get n times 1 by using n. you can use only arithmetic operations not string functions. like
if n equals 1 output equals 1
if n equals 2 output equals 11
if n equals 3 output equals 111
if n equals 4 output equals 1111
any loop is not allowed
Try this:
def func(n):
if n==1:
return 1
return 10**n - 8*func(n-1)*10 - 9
test:
In [49]: func(10)
Out[49]: 1111111111
In [50]: func(3)
Out[50]: 111
In [51]: func(4)
Out[51]: 1111
You can do it this way. It is a recursive function:
def get_ones(n):
if (n == 0):
return 0
elif (n == 1):
return 1
return 10**(n-1) + get_ones(n-1)
print(get_ones(5))
The idea is that 111 = 1*(10^0) + 1*(10^1) + 1*(10^2)
Related
My code should verify if a number is even, if it is, it prints the number multiplied by 2, if it isn't, it should print the number multiplied by 3, but just doesn't work.
m = int(input())
for i in range(m):
n = int(input())
n*=2 if n%2==0 else n*3
print(n)
When i try this input:
3
1
2
3
It returns:
3
4
**27** <- ?
n *= 2 if n % 2 == 0 else n * 3
means
n *= (2 if n % 2 == 0 else n * 3)
which means
if n % 2 == 0:
n = n * 2
else:
n = n * n * 3
You meant to write
n *= 2 if n % 2 == 0 else 3
n*=2 if n%2==0 else n*3
Operator precedence.
This statement is interpreted as
n *= (2 if n%2==0 else n*3)
And for input 3, n%2==0 is not true, so the statement becomes
n *= 9
Which is 27.
Let's put int 5 as a sample input; in my code its expressed as this:
n = int(input())
for i in range(0, n):
n = n - 1
print(n**2)
I get an output as:
16
9
4
1
0
Instead I want to reverse the result to:
0
1
4
9
16
How do you go about solving this problem?
The following will reverse the output:
n = int(input())
for i in range(0,n):
print(i**2)
It will loop from 0 to your inputted n value, printing it's square at each iteration. This also negates the need for the n = n - 1 line.
Output:
0 ** 2
1 ** 2
.
.
.
n ** 2
I'm new to Python and I'm having some trouble. I know if I'm trying to find the number of numbers from 0-1000 that are divisible by 3 or 7 for example I would use the equation np.floor(1000/3)+np.floor(1000/7)-np.floor(1000/21). However, this time the range doesn't start from 0, so what should I replace 1000 with? Thanks! np is numpy btw
O(n) approach:
result = 0
for x in range(1001):
if (x % 3 == 0 and x % 7 == 0):
result += 1
print(result)
More concise:
result = sum(x % 3 == 0 and x % 7 == 0 for x in range(1001))
I want to create a dict with lists as values, where the content on the lists depends on whether or not the key (numbers 1 to 100) is dividable by 3,5 and/or 7
The output would be like this:
{
1: ['nodiv3', 'nodiv5', 'nodiv7'],
3: ['div3', 'nodiv5', 'nodiv7'],
15: ['div3', 'div5', 'nodiv7'],
}
Similar questions where about filtering the list/values, not creating them.
dict_divider = {}
for x in range(0,101):
div_list= []
if x % 3 == 0:
div_list.append('div3')
else:
div_list.append('nodiv3')
if x % 5 == 0:
div_list.append('div5')
else:
div_list.append('nodiv5')
if x % 7 == 0:
div_list.append('div7')
else:
div_list.append('nodiv7')
dict_divider[x] = div_list
This works just fine, but is there a way to do this with a pythonic one-/twoliner?
Something along like this: d = dict((val, range(int(val), int(val) + 2)) for val in ['1', '2', '3'])
Pythonic is not about one or two liners. In my opinion is (mainly) about readability, perhaps this could be considered more pythonic:
def label(n, divisor):
return f"{'' if n % divisor == 0 else 'no'}div{divisor}"
def find_divisors(n, divisors=[3, 5, 7]):
return [label(n, divisor) for divisor in divisors]
dict_divider = {x: find_divisors(x) for x in range(1, 101)}
print(dict_divider)
You don't actually need to do all these brute-force divisions. Every third number is divisible by three, every seventh number is divisible by seven, etc:
0 1 2 3 4 5 6 7 8 9 ... <-- range(10)
0 1 2 0 1 2 0 1 2 0 ... <-- mod 3
0 1 2 3 4 5 6 7 8 9 ... <-- range(10)
0 1 2 3 4 5 6 0 1 2 ... <-- mod 7
So the best approach should take advantage of that fact, using the repeating patterns of modulo. Then, we can just zip the range with however many iterators you want to use.
import itertools
def divs(n):
L = [f"div{n}"] + [f"nodiv{n}"] * (n - 1)
return itertools.cycle(L)
repeaters = [divs(n) for n in (3, 5, 7)]
d = {x: s for x, *s in zip(range(101), *repeaters)}
There is actually a one liner that isnt even that complicated :)
my_dict = {}
for i in range(100):
my_dict[i] = ['div' + str(n) if i % n == 0 else 'nodiv' + str(n) for n in [3,5,7]]
you could write a second loop so that you only have to write if...else only once
dict_divider = {}
div_check_lst = [3, 5, 7]
for x in range(0,101):
div_list= []
for div_check in div_check_lst:
if x % div_check == 0:
div_list.append(f'div{str(div_check)}')
else:
div_list.append(f'nodiv{str(div_check)}')
dict_divider[x] = div_list
or
dict_divider = {x:[f'{'no' * x % div_check != 0}div{str(div_check)}' for x in range(0,101) for div_check in div_check_lst]}
def estDiviseur(i,n):
return n%i==0
def estPremier(n):
b=0
if n==1:
return False
for i in range(1 , n+1):
if estDiviseur(i,n)==True:
b=b+1
if b>2:
return False
else:
return True
def nbPremiers(n):
c=0
for i in range(0,n):
if estPremier(i)==True:
c=c+1
return c
problem is with nbPremiers, if n = 2 it returns to me 2 when it should be 0. the 2 first functions are right and they work exactly as i wanted to. last one is to count the numbers of primal numbers stricly less than n.
All those functions can be written as one-liners:
from math import sqrt
def is_divisor(i,n):
return n % i == 0
def is_prime(n):
return n >= 2 and not any(is_divisor(i, n) for i in range(2,int(sqrt(n)) + 1))
def primes_count(n):
return sum(1 for x in range(2,n+1) if is_prime(x))
print(primes_count(100))
# 25
Whichever country you're coming from, it's usually a good idea to write function names in English, especially if you're asking questions on an internation, english-speaking website.
Note that you only need to check divisors between 2 and sqrt(n).
A more efficient way would be to use the sieve of Erathostenes.
Finally, this prime-counting function is usually defined for primes lower than or equal to n.
You had several mistakes in your code; one of which was getting confused with i and n - using better names for parameters will help you.
Note that 0, and '1' are not primes.
def est_diviseur(diviseur, n):
return n % diviseur == 0
def est_premier(n):
b = 0
if n < 2:
return False
for diviseur in range(1, n+1):
if est_diviseur(diviseur, n) == True:
b = b + 1
if b > 2:
return False
else:
return True
def nb_de_premiers_inferieurs_a(nombre):
"""retourne le nombre de nombres premiers inferieurs a n
returns the number of primes whose value is lower than n
"""
compteur = 0
for n in range(nombre):
if est_premier(n):
compteur += 1
return compteur
for n in range(20):
print(n, est_premier(n), nb_de_premiers_inferieurs_a(n))
output:
0 False 0
1 False 0
2 True 0
3 True 1
4 False 2
5 True 2
6 False 3
7 True 3
8 False 4
9 False 4
10 False 4
11 True 4
12 False 5
13 True 5
14 False 6
15 False 6
16 False 6
17 True 6
18 False 7
19 True 7