Is it possible to create a fibonacci series using generator expression? - python-3.x

Recently an interviewer ask me to create a fibonacci seris of len 10 (n=10) using generator expression. We can do it using generator function -
def fibonacci(n):
n1, n2, nth, count = 0, 1, 1, 0
while count < n:
yield nth
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
for item in fibonacci(10):
print(item, end=' ')
print()
OUTPUT: 1 1 2 3 5 8 13 21 34 55
Can we generate same fibonacci series output using generator expression?

Related

Python - How to compute the value of n+nn+nnn+nnnn with a given digit as the value of n

Write a program that computes the value of n+nn+nnn+nnnn with a given digit as the value of n.
For example, if n=9 , then you have to find the value of 9+99+999+9999
I need some pointers to make this code dynamic in nature.... Kindly let me know
taking into account k terms and a value n :
(10**np.arange(k)).cumsum().sum()*n
Example
k=4
n=1
(10**np.arange(k)).cumsum().sum()*n
#1234
I assume that parameters are:
k - the number of numbers to sum (e.g. in the title of your post
there are 4 numbers to sum),
n - the digit with increasing number number of occurrences in each
number to sum.
Then the function counting such a sum can be expressed as:
def mySum(k, n):
return n * sum([ n1 * n2 for n1, n2 in zip(
[ i + 1 for i in range(k) ],
[ 10 ** (k - i - 1) for i in range(k) ])])
E.g. mySum(4, 2) gives 2468 (2 + 22 + 222 + 2222).
Details of the above case
If k == 4, but n == 1, we can break the sum into:
1 = 1
11 = 10 + 1
111 = 100 + 10 + 1
1111 = 1000 + 100 + 10 + 1
---------------------------------------------
1234 = 1000 * 1 + 100 * 2 + 10 * 3 + 1 * 4
Note that:
[ i + 1 for i in range(k) ] yields [1, 2, 3, 4],
[ 10 ** (k - i - 1) for i in range(k) ] yields [1000, 100, 10, 1],
so multiplication of these 2 zipped lists yields [1000, 200, 30, 4]
and sum of it is 1234.
Now, if n is e.g. 2, all that remains to be done is to multiply the
abobe sum just by n and this is the result.
Can try this out. Modify the range of loop as per program.
num = int(input("Enter a number: "))
t = 0
total = 0
for a in range(4):
t = num + t*10
total = total + t
print(total)

To print a pattern in Python using 'for' loop

I tried various programs to get the required pattern (Given below). The program which got closest to the required result is given below:
Input:
for i in range(1,6):
for j in range(i,i*2):
print(j, end=' ')
print( )
Output:
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
Required Output:
1
2 3
4 5 6
7 8 9 10
Can I get some hint to get the required output?
Note- A newbie to python.
Store the printed value outside of the loop, then increment after its printed
v = 1
lines = 4
for i in range(lines):
for j in range(i):
print(v, end=' ')
v += 1
print( )
If you don't want to keep track of the count and solve this mathematically and be able to directly calculate any n-th line, the formula you are looking for is the one for, well, triangle numbers:
triangle = lambda n: n * (n + 1) // 2
for line in range(1, 5):
t = triangle(line)
print(' '.join(str(x+1) for x in range(t-line, t)))
# 1
# 2 3
# 4 5 6
# 7 8 9 10

How can you find the nth digit in a fractal number

The sequence look like this 112123123412345...
If the input is 55,it should return 1,not 10. And if the input is 56,it should return 0,not 1. You got the idea.
So we have a sequence composed of the composition of
1 1 digit 1 digit total
12 2 digits 3 digits total
123 3 digits 3*(3+1)/2 = 6 digits total
1234 4 digits 4*(4+1)/2 = 10 digits total
...
123..89 9 digits 9*(9+1)/2 = 45 digits total
123..8910 11 digits 10*(10+1)/2 + 1 = 56
123..891011 13 digits 11*(10+1)/2 + 3 = 69
123..89101112 15 digits 12*(12+1)/2 + 3*(3+1)/2 = 84 digits
This is OEIS Sequence A165145 and also see the related sequence OEIS A058183.
A formula for the total number of digits is
f(n) = n*(n+1)/2 + {(n-9)*(n-8)/2 : if n>=10} + {(n-99)*(n-98)/2 : if n>=100) + ...
Some key points f(9) = 45, f(99) = 99*100/2 + 90*91/2 = 9045, f(999) = 1,395,495.
An outline algorithm for finding the k-th digit would be
Find which part of the sequence you are in n<=9, 10 <= n <= 99, 100 <= n <= 999 by comparing k with the boundary values 45, 9045, 1395495.
Recover the value of n
Find the actual digit which will be k-f(n) along sequence for the n-th number.
If we take 10 <= n <= 99 the formula for the number of digits is
n*(n+1)/2 + (n-9)*(n-8)/2
= 1/2( n^2 + n + n^2 - 17 n + 72)
= n^2 - 8 n + 36
So given 45 < k <= 9045 we solve k = n^2 - 8 n + 36, using the quadratic formula
n = ceil( ( 8 + sqrt(64 - 4 (36 - k)))/2)
We need a different quadratic formula for k outside the range.
For example take k = 100, using the formula gives n=13. There are f(12)=84 digits for all the numbers upto 12, so the first digit of the 13th string is at position 85. So we are looking for the 16th digit. We can use the formula
digit(l) := l <= 9 ? l : (l%2==0 ? floor((l+10)/20) : ((l-11)/2)%10 )
to find the actual digit, which is 1.

Finding unique triangles given in n number of triangles in python

Given n-number of triangles, we are required to find how many triangles are unique out of given triangles. For each triangle we are given three integers a, b and c (the sides of a triangle).
A triangle is said to be unique if there is no other triangle with same set of sides.
Sample Input:
7 6 5
5 7 6
8 2 9
2 3 4
2 4 3
Sample Output:
1
Explanation:
Each line is a triangle with 3 sides given. The first two triangles are identical since they have similar sides (just the orders are different). ie. the sum of all the sides for both triangles are equal.
The third triangle '8 2 9' is unique since no other triangle has the exact similar sides. So the output is 1 (total number of unique triangles)
Sample Input:
34 5 32
15 20 6
4 2 3
5 6 9
15 20 6
34 5 32
Sample Output:
2
Here the triangles '423' and '560' are unique. So the output is 2 (total number of unique triangles)
This is what I did...
n = int(input())
arr = [list(map(int, input().split())) for x in range(n)]
def uniqueTriangle(arr):
row = len(arr)
col = len(arr[0])
mp = {}
hel = {}
for i in range(row):
tri = arr[i]
tri.sort()
strA = [str(x) for x in tri]
strB = ''
strB = strB.join(strA)
if strB not in mp.values():
mo[i] = strB
else:
hell[i] = strB
count = 0
for i in range(row):
if i in mp:
val = mp.get(i)
if val not in hel.values():
count = count + 1
print (count)
Apologize for the ugly code. But how can I make this code better?
from collections import Counter
arr = [[7, 6, 5],[5, 7, 6],[8, 2, 9],[2, 3, 4],[2, 4, 3]]
def unique_triangles(arr):
counter = Counter([frozenset(a) for a in arr])
return len([res for res in counter if counter[res] == 1])
Use frozenset to mark each unique set of triangle
use collections.Counter to count the number of unique sets found in the input array
return the set appeared only once
This is what I did :
n = int(input())
l=[]
for i in range(n):
t = [int(side) for side in input().split()]
l.append(set(t))
ans=[]
for j in l:
count=0
for i in l:
if i==j:
count+=1
if count==1:
ans.append(j)
print(len(ans))

how to store python console output in python variable

below is my code :
def combinationUtil(arr, n, r,index, data, i):
if(index == r):
for j in range(r):
print(data[j], end = " ")
print(" ")
return
if(i >= n):
return
data[index] = arr[i]
combinationUtil(arr, n, r, index + 1, data, i + 1)
combinationUtil(arr, n, r, index, data, i + 1)
def printcombination(arr, n, r):
data = list(range(r))
combinationUtil(arr, n, r, 0, data, 0)
var = []
pp = 5
r = 3
arr = []
for i in range(1, pp+1):
arr.append(i)
n = len(arr)
printcombination(arr, n, r)
it gives me this output:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
i want to save this output as a variable in python
You have a combination utility routine that produces the output of interest.
If you were calling someone else's routine, you might need to assign
sys.stdout to an io.StringIO() to capture the output.
But as it stands, you have control over the source code,
so you can easily replace
for j in range(r):
print(data[j], end=' ')
print(' ')
with the following more convenient interface:
yield [data[j] for j in range(r)]
Then iterate, e.g.:
for row in combinationUtil(arr, n, r, 0, list(range(r)), 0):
print(row)
Cf itertools.

Resources