Error in generating gradient - python

I have an error somewhere in this script that is supposed to generate a gradient. When the depth is equal to the difference the gradient is perfect, but floating point increments seem to screw it up. I've been staring at this code for so long I can't see the answer.
What's wrong with this code?
def interpolate(s, e, n):
start = list(s)
end = list(e)
incrementlst = []
for i in range(0,len(start)):
diff = int(end[i]) - int(start[i])
if diff == 0:
increment = 0.0
else:
increment =diff/n
incrementlst.append(increment)
return incrementlst
def incrementedValue(s, i, n):
start = list(s)
increment = list(i)
n = n-1
finallst = [0,0,0,0]
if n < 1:
return start
for i in range(0,len(start)):
finallst[i] = start[i] + (n*(increment[i]))
return finallst
def formatIncrementedValue(l):
cmykList = list(l)
formattedString = str(int(round(cmykList[0], 0))) + " " + str(int(round(cmykList[1], 0))) + " " + str(int(round(cmykList[2], 0))) + " " + str(int(round(cmykList[3], 0)))
return formattedString
# Get user inputs.
depth = int(ca_getcustomvalue ("depth", "0"))
start = ca_getcustomvalue("start", "0")
end = ca_getcustomvalue("end", "0")
startlst = start.split(" ")
startlst = [int(i) for i in startlst]
endlst = end.split(" ")
endlst = [int(i) for i in endlst]
# draw a line and incrementally change the pen colour towards the end colour
colorlst = interpolate(startlst, endlst, depth)
for i in range(1,depth-1):
color = formatIncrementedValue(incrementedValue(startlst, colorlst, i))
#Draw line at correct offset in colour "color"

This:
increment =diff/n
is doing integer division, so for instance if diff is 3 and n is 2, you get 1, not 1.5.
Make the expression float, to fix this:
increment = float(diff) / n

Related

my decoration sometimes appears just outside the triangle

It seems that my decoration sometimes appears just outside the triangle... How can I fix this?
import random
n = int(input('enter n: '))
x = 1
for i in range(n):
if i == 0:
count = 0
else:
count = random.randint(0, x)
print(' ' * (n - i), '*' * count, end = '')
if i == 0:
print('&', end = '')
else:
print('o', end = '')
print('*' * (x - count - 1))
x += 2
What do I get for value n = 10:
&
***o
*o***
o******
******o**
*********o*
*************o
*****o*********
*************o***
******************o
The random number you generate may return x as randint includes the second value in the set of possible values. So pass x - 1 to randint:
count = random.randint(0, x - 1)
It is also a pity that you have a check for i == 0 in your loop. In that case, why not deal with that first case outside of the loop, and start the loop at 1? It will make your code a bit more elegant.
def tree(n):
from random import sample
body = ["&"] + ["".join(sample("o" + "*" * (k:=x*2+1), k=k)) for x in range(1, n)]
spaces = [" " * (x-2) for x in range(n, 1, -1)]
return "\n".join("".join(tpl) for tpl in zip(spaces, body))
print(tree(10))
Output:
&
o**
****o
o******
*******o*
********o**
*******o*****
**************o
o****************
I love christmas tress! This is my take on the question :-)
import random
n = int(input('Enter tree height: '))
print(" " * (n-1) + "&")
for i in range(2, n+1):
decoration = random.randint(1, (i-1)*2 -1)
print(" " * (n - i) + "*" * decoration + "o" + "*" * ((i-1)*2 - decoration))
Enter tree height: 12
&
*o*
**o**
*o*****
*o*******
********o**
*******o*****
***********o***
********o********
****************o**
***o*****************
*********o*************

Why does my hexadecimal to base64 converter break down on large numbers?

I'm working on a cryptopals problem. Specifically, the first one. I have a, what I feel, decent solution for it, in that it works for given inputs, and for the example they give, but I've been looking at further testing to see if it holds up, and it doesn't seem to. Here's my code:
hex="0123456789abcdef"
base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def hexNumeralToBinary(hexNumeral):
index = hex.index(hexNumeral)
binaryNumber = []
while index > 0:
if (index % 2) == 0:
binaryNumber = ["0"] + binaryNumber
index = index / 2
else:
binaryNumber = ["1"] + binaryNumber
index = (index-1)/2
while len(binaryNumber) < 4:
binaryNumber = ["0"] + binaryNumber
return ''.join(binaryNumber)
def hexToBinary(hexNumber):
length = len(hexNumber) + 1
binaryNumber = []
for i in range(1, length):
hexNumeral = hexNumber[-1*i]
binaryNumeral = hexNumeralToBinary(hexNumeral)
binaryNumber = [binaryNumeral] + binaryNumber
return ''.join(binaryNumber)
def splitString(binaryNumber):
while (len(binaryNumber) % 6) != 0:
binaryNumber = "0" + binaryNumber
binaryNumberSplit = []
while binaryNumber != "":
binaryNumberSplit.append(binaryNumber[0:6])
binaryNumber = binaryNumber[6:]
return binaryNumberSplit
def hexToBase64(hexNumber):
base64Number = []
binaryNumber = hexToBinary(hexNumber)
binaryNumberSplit = splitString(binaryNumber)
for sixBitNum in binaryNumberSplit:
#Convert 6 bit binary number into the base64 index
index = 0
for i in range(1, 7):
index += int(sixBitNum[-1*i]) * (2**(i-1))
base64Digit = base64[index]
base64Number = base64Number + [base64Digit]
return ''.join(base64Number)
hexNumber = input("Please enter a hexadecimal number to convert to base64: ")
print(hexToBase64(hexNumber))
It seems like the hexadecimal number needs to have a number of digits divisible by 3, or it just gets stuck while running. I don't know where, and I'm really stumped. I'm a total beginner to programming, and this is easily the most complex thing I've done, just trying to work it out as I go, and this isn't coming to me.

Complexity for two approaches of finding next biggest palindrome of a number

I have come up with a problem online about the next biggest palindrome of a number and i have solved the problem by two different approaches in python. The first one is,
t = long(raw_input())
for i in range(t):
a = (raw_input())
a = str(int(a) + 1)
palin = ""
oddOrEven = len(a) % 2
if oddOrEven:
size = len(a) / 2
center = a[size]
else:
size = 0
center = ''
firsthalf = a[0 : len(a)/2]
secondhalf = firsthalf[::-1]
palin = firsthalf + center + secondhalf
if (int(palin) < int(a)):
if(size == 0):
firsthalf = str(int(firsthalf) + 1)
secondhalf = firsthalf[::-1]
palin = firsthalf + secondhalf
elif(size > 0):
lastvalue = int(center) + 1
if (lastvalue == 10):
firsthalf = str(int(firsthalf) + 1)
secondhalf = firsthalf[::-1]
palin = firsthalf + "0" + secondhalf
else:
palin = firsthalf + str(lastvalue) + secondhalf
print palin
and the another one is,
def inc(left):
leftlist=list(left)
last = len(left)-1
while leftlist[last]=='9':
leftlist[last]='0'
last-=1
leftlist[last] = str(int(leftlist[last])+1)
return "".join(leftlist)
def palin(number):
size=len(number)
odd=size%2
if odd:
center=number[size/2]
else:
center=''
print center
left=number[:size/2]
right = left[::-1]
pdrome = left + center + right
if pdrome > number:
print pdrome
else:
if center:
if center<'9':
center = str(int(center)+1)
print left + center + right
return
else:
center = '0'
if left == len(left)*'9':
print '1' + (len(number)-1)*'0' + '1'
else:
left = inc(left)
print left + center + left[::-1]
if __name__=='__main__':
t = long (raw_input())
while t:
palin(raw_input())
t-=1
As a computer science perspective, what is the complexity of both of this algorithms? which one is more efficient to use?
I see you are making a sublist within your for loop, and the largest sublist is of size n-1. And then a loop that goes to n.
So worst case for both is O(n^2), where n is the length of t.

Implementing Knuth-Morris-Pratt (KMP) algorithm for string matching with Python

I am following Cormen Leiserson Rivest Stein (clrs) book and came across "kmp algorithm" for string matching. I implemented it using Python (as-is).
However, it doesn't seem to work for some reason. where is my fault?
The code is given below:
def kmp_matcher(t,p):
n=len(t)
m=len(p)
# pi=[0]*n;
pi = compute_prefix_function(p)
q=-1
for i in range(n):
while(q>0 and p[q]!=t[i]):
q=pi[q]
if(p[q]==t[i]):
q=q+1
if(q==m):
print "pattern occurs with shift "+str(i-m)
q=pi[q]
def compute_prefix_function(p):
m=len(p)
pi =range(m)
pi[1]=0
k=0
for q in range(2,m):
while(k>0 and p[k]!=p[q]):
k=pi[k]
if(p[k]==p[q]):
k=k+1
pi[q]=k
return pi
t = 'brownfoxlazydog'
p = 'lazy'
kmp_matcher(t,p)
This is a class I wrote based on CLRs KMP algorithm, which contains what you are after. Note that only DNA "characters" are accepted here.
class KmpMatcher(object):
def __init__(self, pattern, string, stringName):
self.motif = pattern.upper()
self.seq = string.upper()
self.header = stringName
self.prefix = []
self.validBases = ['A', 'T', 'G', 'C', 'N']
#Matches the motif pattern against itself.
def computePrefix(self):
#Initialize prefix array
self.fillPrefixList()
k = 0
for pos in range(1, len(self.motif)):
#Check valid nt
if(self.motif[pos] not in self.validBases):
self.invalidMotif()
#Unique base in motif
while(k > 0 and self.motif[k] != self.motif[pos]):
k = self.prefix[k]
#repeat in motif
if(self.motif[k] == self.motif[pos]):
k += 1
self.prefix[pos] = k
#Initialize the prefix list and set first element to 0
def fillPrefixList(self):
self.prefix = [None] * len(self.motif)
self.prefix[0] = 0
#An implementation of the Knuth-Morris-Pratt algorithm for linear time string matching
def kmpSearch(self):
#Compute prefix array
self.computePrefix()
#Number of characters matched
match = 0
found = False
for pos in range(0, len(self.seq)):
#Check valid nt
if(self.seq[pos] not in self.validBases):
self.invalidSequence()
#Next character is not a match
while(match > 0 and self.motif[match] != self.seq[pos]):
match = self.prefix[match-1]
#A character match has been found
if(self.motif[match] == self.seq[pos]):
match += 1
#Motif found
if(match == len(self.motif)):
print(self.header)
print("Match found at position: " + str(pos-match+2) + ':' + str(pos+1))
found = True
match = self.prefix[match-1]
if(found == False):
print("Sorry '" + self.motif + "'" + " was not found in " + str(self.header))
#An invalid character in the motif message to the user
def invalidMotif(self):
print("Error: motif contains invalid DNA nucleotides")
exit()
#An invalid character in the sequence message to the user
def invalidSequence(self):
print("Error: " + str(self.header) + "sequence contains invalid DNA nucleotides")
exit()
You might want to try out my code:
def recursive_find_match(i, j, pattern, pattern_track):
if pattern[i] == pattern[j]:
pattern_track.append(i+1)
return {"append":pattern_track, "i": i+1, "j": j+1}
elif pattern[i] != pattern[j] and i == 0:
pattern_track.append(i)
return {"append":pattern_track, "i": i, "j": j+1}
else:
i = pattern_track[i-1]
return recursive_find_match(i, j, pattern, pattern_track)
def kmp(str_, pattern):
len_str = len(str_)
len_pattern = len(pattern)
pattern_track = []
if len_pattern == 0:
return
elif len_pattern == 1:
pattern_track = [0]
else:
pattern_track = [0]
i = 0
j = 1
while j < len_pattern:
data = recursive_find_match(i, j, pattern, pattern_track)
i = data["i"]
j = data["j"]
pattern_track = data["append"]
index_str = 0
index_pattern = 0
match_from = -1
while index_str < len_str:
if index_pattern == len_pattern:
break
if str_[index_str] == pattern[index_pattern]:
if index_pattern == 0:
match_from = index_str
index_pattern += 1
index_str += 1
else:
if index_pattern == 0:
index_str += 1
else:
index_pattern = pattern_track[index_pattern-1]
match_from = index_str - index_pattern
Try this:
def kmp_matcher(t, d):
n=len(t)
m=len(d)
pi = compute_prefix_function(d)
q = 0
i = 0
while i < n:
if d[q]==t[i]:
q=q+1
i = i + 1
else:
if q != 0:
q = pi[q-1]
else:
i = i + 1
if q == m:
print "pattern occurs with shift "+str(i-q)
q = pi[q-1]
def compute_prefix_function(p):
m=len(p)
pi =range(m)
k=1
l = 0
while k < m:
if p[k] <= p[l]:
l = l + 1
pi[k] = l
k = k + 1
else:
if l != 0:
l = pi[l-1]
else:
pi[k] = 0
k = k + 1
return pi
t = 'brownfoxlazydog'
p = 'lazy'
kmp_matcher(t, p)
KMP stands for Knuth-Morris-Pratt it is a linear time string-matching algorithm.
Note that in python, the string is ZERO BASED, (while in the book the string starts with index 1).
So we can workaround this by inserting an empty space at the beginning of both strings.
This causes four facts:
The len of both text and pattern is augmented by 1, so in the loop range, we do NOT have to insert the +1 to the right interval. (note that in python the last step is excluded);
To avoid accesses out of range, you have to check the values of k+1 and q+1 BEFORE to give them as index to arrays;
Since the length of m is augmented by 1, in kmp_matcher, before to print the response, you have to check this instead: q==m-1;
For the same reason, to calculate the correct shift you have to compute this instead: i-(m-1)
so the correct code, based on your original question, and considering the starting code from Cormen, as you have requested, would be the following:
(note : I have inserted a matching pattern inside, and some debug text that helped me to find logical errors):
def compute_prefix_function(P):
m = len(P)
pi = [None] * m
pi[1] = 0
k = 0
for q in range(2, m):
print ("q=", q, "\n")
print ("k=", k, "\n")
if ((k+1) < m):
while (k > 0 and P[k+1] != P[q]):
print ("entered while: \n")
print ("k: ", k, "\tP[k+1]: ", P[k+1], "\tq: ", q, "\tP[q]: ", P[q])
k = pi[k]
if P[k+1] == P[q]:
k = k+1
print ("Entered if: \n")
print ("k: ", k, "\tP[k]: ", P[k], "\tq: ", q, "\tP[q]: ", P[q])
pi[q] = k
print ("Outside while or if: \n")
print ("pi[", q, "] = ", k, "\n")
print ("---next---")
print ("---end for---")
return pi
def kmp_matcher(T, P):
n = len(T)
m = len(P)
pi = compute_prefix_function(P)
q = 0
for i in range(1, n):
print ("i=", i, "\n")
print ("q=", q, "\n")
print ("m=", m, "\n")
if ((q+1) < m):
while (q > 0 and P[q+1] != T[i]):
q = pi[q]
if P[q+1] == T[i]:
q = q+1
if q == m-1:
print ("Pattern occurs with shift", i-(m-1))
q = pi[q]
print("---next---")
print("---end for---")
txt = " bacbababaabcbab"
ptn = " ababaab"
kmp_matcher(txt, ptn)
(so this would be the correct accepted answer...)
hope that it helps.

How to change Letters to Numbers for numbers to be assigned with nodes?

I want to know how to put say for example, A(both capital and lowercase) into the node 0 in my code but I really have no idea how. I get that there's chr but I have never used it before and I tried to read and do it and, I just can't get my head around it.
Here's my code:
infinity = 1000000
invalid_node = -1
class Node:
previous = invalid_node
distFromSource = infinity
visited = False
def populateNetwork(fileName):
network = []
networkFile = open(fileName, "r")
for line in networkFile:
network.append(map(int, line.strip().split(',')))
return network
def populateNodeTable(network, StartNode):
nodeTable = []
for node in network:
nodeTable.append(Node())
nodeTable[StartNode].distFromSource = 0
nodeTable[StartNode].visited = True
return nodeTable
def nearestNeighbour(network, currentNode):
neighbours = []
column = 0
for node in network[currentNode]:
if node !=0:
neighbours.append(column)
column +=1
return neighbours
def tentativeDistance(neighbours, network, nodeTable, currentNode):
for neighbour in neighbours:
if nodeTable[neighbour].visited == False:
tentative = nodeTable[currentNode].distFromSource + network[currentNode][neighbour]
if tentative < nodeTable[neighbour].distFromSource:
nodeTable[neighbour].distFromSource = tentative
nodeTable[neighbour].previous = currentNode
print tentative
##Testing this Function
def newNodeTable(nodeTable):
nextNode == invalid_node
currentIndex = 0
nextDestination == infinity
for node in nodeTable:
if node.visited == False and node.distanceFromSource < nextDestination:
nextNode = currentIndex
nextDestination = node.distanceFromSource
currentIndex+=1
return nextNode
##Testing this Function
def getRoute(routePath):
getRoutePath = []
getRouteFile = open(routePath, "r")
for line in getRouteFile:
getRoutePath.append(int,line.split(">"))
return getRoutePath
network = populateNetwork('network.txt')
nodeTable = populateNodeTable(network, 1)
neighbours=nearestNeighbour(network, 1)
tentativeDistance(neighbours, network, nodeTable, 1)
print
print "Current nodes and visited"
for node in nodeTable:
print node.previous, node.distFromSource, node.visited
##for line in network:
## print line
print
print "Visual representation of the network array"
for index, val in enumerate(network):
print index, val
Here is my network.txt file:
0,2,4,1,6,0,0
2,0,0,0,5,0,0
4,0,0,0,0,5,0
1,0,0,0,1,1,0
6,5,0,1,0,5,5
0,0,5,1,5,0,0
0,0,0,0,5,0,0
And my route.txt file is basically either going to be "A>G" , "a>G" or "a>g".
You can use text
import string
print string.ascii_uppercase
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
print string.ascii_lowercase
# abcdefghijklmnopqrstuvwxyz
print string.ascii_letters
# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
char = string.ascii_uppercase[0] # A
char = string.ascii_uppercase[1] # B
char = string.ascii_uppercase[2] # C
char = string.ascii_lowercase[0] # a
char = string.ascii_lowercase[1] # b
char = string.ascii_lowercase[2] # c
Or you can use chr(number)
print chr(65 + 0) # A
print chr(65 + 1) # B
print chr(65 + 2) # C
print chr(97 + 0) # a
print chr(97 + 1) # b
print chr(97 + 2) # c
You can find character number using ord(letter)
print ord('A') # 65
print ord('a') # 97

Categories

Resources