dummy numbers generator in Python - python

With an = (an-2 + 1)×an-1 with a0 = 0 and a1 = 1 formula find dummy_numbers(max)
My code:
def dummy_numbers(nums):
binsize = (((nums - 2) +1) * (nums -1))
return map(lambda x: int(nums + binsize * x), range(nums))
for num in dummy_numbers(10):
print(num)
my code prints different result than I expected

Use an actual generator with yield to make this easier. The tricky part here is keeping track of an-1 and an-2 as you iterate. This can be achieve like so:
second_last, last = None, None
for current in range(10):
second_last, last = last, current
assert (second_last, last) == (8, 9)
You also need to hardcode in the constant value that get returned for 0 and 1:
def dummy_numbers(an):
if an == 0:
yield 0
elif an == 1:
yield 0
yield 1
else:
an_2, an_1 = None, None
for an_0 in dummy_numbers(an - 1):
an_2, an_1 = an_1, an_0
yield an_0
yield (an_2 + 1) * an_1
for num in dummy_numbers(10):
print(num)
Outputs:
0
1
1
2
4
12
60
780
47580
37159980
1768109008380
You could also make this non-recursive like so:
def dummy_numbers(an):
an_2, an_1 = None, None
for i in range(an):
if i == 0:
an_0 = 0
elif i == 1:
an_0 = 1
else:
an_0 = (an_2 + 1) * an_1
yield an_0
an_2, an_1 = an_1, an_0

Related

Finding common outputs of 3 functions

I have 3 functions.These are
A(n) = n(n+1)/2
B(n) = n(3n-1)/2
C(n) = n(2n-1)
Their first common output and indexes are:
A(285)=B(165)=C(143)=40755
I need second one,so I tried this:
def equation1(x):
return x*(x+1)/2
def equation2(x):
return x*((3*x)-1)/2
def equation3(x):
return x*((2*x)-1)
for i in range(144,30000):
x = equation3(i)
for a in range(i,2*i):
y = equation2(a)
if(x==y):
for b in range(a,2*a):
z = equation1(b)
if(x==y==z):
print("Term =" + str(x))
print("A" + str(b))
print("B" + str(a))
print("C" + str(i))
But it takes too much time to find it.How can I handle this in an easier way?
Since all three functions are increasing for positive values, you can write a loop that increases the number with the smallest value at each iteration:
a = b = c = 1
eq_a = equation1(a)
eq_b = equation2(b)
eq_c = equation3(c)
while True:
if eq_a == eq_b and eq_b == eq_c:
print("Found {}, {}, {}, result={}".format(a,b,c,eq_a))
if eq_a <= eq_b and eq_a <= eq_c:
a += 1
eq_a = equation1(a)
elif eq_b <= eq_a and eq_b <= eq_c:
b += 1
eq_b = equation2(b)
elif eq_c <= eq_a and eq_c <= eq_b:
c += 1
eq_c = equation3(c)
else:
print("Should never be here")
assert(False);
Test run:
Found 1, 1, 1, result=1
Found 285, 165, 143, result=40755
Found 55385, 31977, 27693, result=1533776805
Found 10744501, 6203341, 5372251, result=57722156241751

how to fix this combination program using binomial factorial equation?

my answer for finding the number of combinations given drawing 3 cards out of 52 is off by a spot. Like 0 cards from 52 should = 1, 1 should = 52, 2 = 1326 and so on. but I have 0 = 1, 1 = 1, 2 = 52 and so on. What would I modify to reach the desired result? I think the error is in def factorial() but I can not seem to fix/ find the issue, no matter what I try.
def factorial(num):
i = 2
if num == 0:
num = 1
print(num)
elif num > 1:
for i in range(i, num):
num = num * i
return num
def combinations(n,r):
l = n-r
nn = factorial(n)
rn = factorial(r)
ln = factorial(l)
result = nn / (rn * ln)
print(result)
return result
def main():
h = 52
a = 0
while a<4:
combinations(h,a)
a = a + 1
You're printing extra stuff in factorial which may lead to the confusion. I suggest you print out your final result with comparison to your a variable at the end of the combinations function like so:
print("For a=" + str(r) + ", result=" + str(result))
Here is the overall edited code:
def factorial(num):
if num == 0:
num = 1
elif num > 1:
for i in range(2, num): # Setting i=2 at the start is redundant
num = num * i
return num
def combinations(n,r):
l = n-r
nn = factorial(n)
rn = factorial(r)
ln = factorial(l)
result = nn / (rn*ln)
print("For a=" + str(r) + ", result=" + str(result))
return
h = 52
a = 0
while a<4:
combinations(h,a)
a = a + 1

Convert between str and int without using built-in typecasting

NB: You may not use built-in typecasting: code this yourself.
def str2int(s):
result = 0
if s[0] == '-':
sign = -1
i = 1
while i < len(s):
num = ord(s[i]) - ord('0')
result = result * 10 + num
i += 1
result = sign * result
return result
else:
i = 0
while i < len(s):
num = ord(s[i]) - ord('0')
result = result * 10 + num
i += 1
return result
NB: You may not use built-in str() or string template. Code this yourself.
def int2str(i):
strng = ""
if i > 0:
while i != 0:
num = i % 10
strng += chr(48+num)
i = i / 10
return strng[::-1]
else:
while i != 0:
num = abs(i) % 10
strng += chr(48+num)
i = abs(i) / 10
return '-' + strng[::-1]
I am a newbie and I have to write code based on basic. I write these function by myself but these look weird. Can you help me to improve code? Thank you
This maybe a better question for https://codereview.stackexchange.com/.
Not withstanding there is no error checking, one obvious comment is you have common code that can be factored out. Only capture in the if, else what is unique rather than repeat the while loop:
def str2int(s):
if s[0] == '-':
sign = -1
i = 1
else:
sign = 1
i = 0
result = 0
while i < len(s):
num = ord(s[i]) - ord('0')
result = result * 10 + num
i += 1
return sign * result
It is generally considered better form in python to iterate over list rather than indices:
def str2int(s):
sign = 1
if s[0] == '-':
sign = -1
s = s[1:]
result = 0
for c in s:
num = ord(c) - ord('0')
result = result * 10 + num
return sign * result
These last lines are equivalent to a standard map and reduce (reduce is in functools for py3). Though some would argue against it:
from functools import reduce # Py3
def str2int(s):
sign = 1
if s[0] == '-':
sign = -1
s = s[1:]
return sign * reduce(lambda x,y: x*10+y, map(lambda c: ord(c) - ord('0'), s))
There are similar opportunities to do the same for int2str().

How do I run a binary search for words that start with a certain letter?

I am asked to binary search a list of names and if these names start with a particular letter, for example A, then I am to print that name.
I can complete this task by doing much more simple code such as
for i in list:
if i[0] == "A":
print(i)
but instead I am asked to use a binary search and I'm struggling to understand the process behind it. We are given base code which can output the position a given string. My problem is not knowing what to edit so that I can achieve the desired outcome
name_list = ["Adolphus of Helborne", "Aldric Foxe", "Amanita Maleficant", "Aphra the Vicious", "Arachne the Gruesome", "Astarte Hellebore", "Brutus the Gruesome", "Cain of Avernus"]
def bin_search(list, item):
low_b = 0
up_b = len(list) - 1
found = False
while low_b <= up_b and found == False:
midPos = ((low_b + up_b) // 2)
if list[midPos] < item:
low_b = midPos + 1
elif list[midPos] > item:
up_b = midPos - 1
else:
found = True
if found:
print("The name is at positon " + str(midPos))
return midPos
else:
print("The name was not in the list.")
Desired outcome
bin_search(name_list,"A")
Prints all the names starting with A (Adolphus of HelBorne, Aldric Foxe .... etc)
EDIT:
I was just doing some guess and check and found out how to do it. This is the solution code
def bin_search(list, item):
low_b = 0
up_b = len(list) - 1
true_list = []
count = 100
while low_b <= up_b and count > 0:
midPos = ((low_b + up_b) // 2)
if list[midPos][0] == item:
true_list.append(list[midPos])
list.remove(list[midPos])
count -= 1
elif list[midPos] < item:
low_b = midPos + 1
count -= 1
else:
up_b = midPos - 1
count -= 1
print(true_list)
Not too sure if this is what you want as it seems inefficient... as you mention it seems a lot more intuitive to just iterate over the entire list but using binary search i found here i have:
def binary_search(seq, t):
min = 0
max = len(seq) - 1
while True:
if max < min:
return -1
m = (min + max) // 2
if seq[m][0] < t:
min = m + 1
elif seq[m][0] > t:
max = m - 1
else:
return m
index=0
while True:
index=binary_search(name_list,"A")
if index!=-1:
print(name_list[index])
else:
break
del name_list[index]
Output i get:
Aphra the Vicious
Arachne the Gruesome
Amanita Maleficant
Astarte Hellebore
Aldric Foxe
Adolphus of Helborne
You just need to found one item starting with the letter, then you need to identify the range. This approach should be fast and memory efficient.
def binary_search(list,item):
low_b = 0
up_b = len(list) - 1
found = False
midPos = ((low_b + up_b) // 2)
if list[low_b][0]==item:
midPos=low_b
found=True
elif list[up_b][0]==item:
midPos = up_b
found=True
while True:
if found:
break;
if list[low_b][0]>item:
break
if list[up_b][0]<item:
break
if up_b<low_b:
break;
midPos = ((low_b + up_b) // 2)
if list[midPos][0] < item:
low_b = midPos + 1
elif list[midPos] > item:
up_b = midPos - 1
else:
found = True
break
if found:
while True:
if midPos>0:
if list[midPos][0]==item:
midPos=midPos-1
continue
break;
while True:
if midPos<len(list):
if list[midPos][0]==item:
print list[midPos]
midPos=midPos+1
continue
break
else:
print("The name was not in the list.")
the output is
>>> binary_search(name_list,"A")
Adolphus of Helborne
Aldric Foxe
Amanita Maleficant
Aphra the Vicious
Arachne the Gruesome
Astarte Hellebore

Disappeared list variable

Could you please tell why list variable have disappeared after "while" cycle?
#staticmethod
def division(f, s):
result = []
tr = []
if len(s) > len(f):
return [Polynomial(0), Polynomial(f)]
while len(f) >= len(s):
r = []
k = 0
mf = 2*f[len(f)-1]
ms = 2*s[len(s)-1]
m = []
if mf < 0:
mf *= -1
if ms < 0:
ms *= -1
if mod(f[len(f)-1], mf) < mod(s[len(s)-1], ms):
return [Polynomial(0), Polynomial(f)]
while mod(f[len(f)-1], mf) >= k:
k += mod(s[len(s)-1], ms)
k -= mod(s[len(s)-1], ms)
r.append([k/mod(s[len(s)-1], ms), len(f)-len(s)])
if f[len(f)-1] > 0 and s[len(s)-1] < 0 or f[len(f)-1] < 0 and s[len(s)-1] > 0:
r[len(r)-1][0] *= -1
for i in xrange(r[len(r)-1][1]+1):
m.append(0)
m[len(m)-1] = r[len(r)-1][0]
result.append(r[len(r)-1])
subtrahend = Polynomial.multiplication(Polynomial(m).Coefficients,
Polynomial(s).Coefficients).Coefficients
f = Polynomial.subtraction(f, subtrahend).Coefficients
print result
print result
o = []
for i in xrange(result[0][1]+1):
o.append(0)
for i in xrange(len(result)):
o[i] = result[i][0]
o.reverse()
if len(f) == 0:
f = [0]
return [Polynomial(o), Polynomial(f)]
f = Polynomial.subtraction(f, subtrahend).Coefficients
print result
print result
First print shows correct result, but second print (after end of cycle) shows nothing. If I try to redefine it like this:
f = Polynomial.subtraction(f, subtrahend).Coefficients
print result
result = 'asdf'
print result
nothing happened. Result variable is still None.
Your function returns early:
return [Polynomial(0), Polynomial(f)]
The code after the while loop is never reached if that return statement is executed, which happens if mod(f[len(f)-1], mf) < mod(s[len(s)-1], ms) is ever True.

Categories

Resources