How to print elements with variables as the index - python

How would I print an element inside a for loop using its index?
flag = "T"
while flag == "T":
x = []
y = []
x1 = int(input())
y1 = int(input())
x.append(x1)
y.append(y1)
for i in range(len(x)):
v = len(x)-1
print(x[v])
print("First value: " + x[v] + "\r\n" + "Second value: " + y[v])
The main question is that printing x with the index of v works in the first print call, but not the second. Why?

You are trying to print integers. Wrap it in str() to be able to print them:
flag = "T"
while flag == "T":
x = []
y = []
x1 = int(input())
y1 = int(input())
x.append(x1)
y.append(y1)
for i in range(len(x)):
v = len(x)-1
print(x[v])
print("First value: " + str(x[v]) + "\r\n" + "Second value: " + str(y[v]))

Don’t bother trying to concatenate elements together only to print them. Use the ability of print to print all its arguments.
print("First value: ", x[v], "\r\nSecond value: ", y[v])

Related

How to reduce my execution time in python when i am using print function?

So, When i am using print()/sys.stdout.write() to print my results (I have checked all the results are correct) the program execution time is increasing to min of 100times when i was not using print.
N = Number of elements in lists(numpy array)
C = C is an element of array
T = Number of Arrays
1≤N≤1000
1≤Ci≤10^5
1≤T≤100
I am thinking this is happening because of print function. If yes How would I solve this issue
Without Print Execution time = 0.012797699999999967
With Print Execution time = 1.1667817
This is a question From Google KickStart
def sub_one(inputlist, inputlength):
smalllist = np.array([], dtype='int32')
outputlist = np.array([], dtype='int32')
h_score = 1
for mainnum in inputlist:
if mainnum > h_score:
smalllist = np.append(smalllist, mainnum)
else:
outputlist = np.append(outputlist, mainnum)
continue
eachlist = np.array([], dtype='int32')
for num in smalllist:
if num >= h_score:
eachlist = np.append(eachlist, h_score)
if np.count_nonzero(eachlist) == h_score:
outputlist = np.append(outputlist, h_score)
smalllist = smalllist[smalllist > h_score]
h_score += 1
return outputlist
def caseprinter(thelist):
returnstring = ""
for i in thelist:
returnstring += (str(i) + " ")
return returnstring
if __name__ == "__main__":
cases = int(input())
for i in range(cases):
inputlength = int(input())
inputlist = input().split(" ")
inputlist = np.array(inputlist, dtype='int32')
outputlist = sub_one(inputlist, inputlength)
print(f'Case #{i+1}: {caseprinter(outputlist)}')```
Your
def caseprinter(thelist):
returnstring = ""
for i in thelist:
returnstring += (str(i) + " ")
return returnstring
might take quadratic time. Try linear time:
def caseprinter(thelist):
return " ".join(map(str, thelist))

How can i add a While loop to detect errors in the input in python

So, i am trying to write a code to not only do arithmetic equations, but also, give feedback if there is an error as well as give me 3 tries max. any advice?
arithmetic=input("Enter an arithmetic operation:")
arithmetic= arithmetic.replace(" ", "")
w=arithmetic.split('/')
x= arithmetic.split('-')
y=arithmetic.split('+')
z=arithmetic.split('*')
if ("+" in arithmetic):
a= int(y[0])
b= int(y[1])
sum = a + b
print("The result is = " + str(sum))
elif ("*" in arithmetic):
a= int(z[0])
b= int(z[1])
result = a * b
print("The result is = " + str(result))
elif ("/" in arithmetic):
a= int(w[0])
b= int(w[1])
result = a / b
result = round(result,3)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x)==3):
a= int(x[1])
b= int(x[2])
result = a + b
result = result * (-1)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x)==2):
a= int(x[0])
b= int(x[1])
result = a - b
print("The result is = " + str(result))
#tries = 0
#while(tries < 3):
# arithmetic=input("Enter an arithmetic operation:")
# match = arithmetic.find('+')
# print(match)
# if(match == -1):
# print ("Invalid")
# tries += 1
# else:
# tries= 3
I tried to add the while in the beginning. However, when i put an input such as 11 and 12 without the + sign, it just printed the input without giving me an error. why is that?
tries = 0
while tries < 3:
arithmetic = input("Enter an arithmetic operation:")
arithmetic = arithmetic.replace(" ", "")
w = arithmetic.split('/')
x = arithmetic.split('-')
y = arithmetic.split('+')
z = arithmetic.split('*')
try:
if ("+" in arithmetic):
a = int(y[0])
b = int(y[1])
sum = a + b
print("The result is = " + str(sum))
elif ("*" in arithmetic):
a = int(z[0])
b = int(z[1])
result = a * b
print("The result is = " + str(result))
elif ("/" in arithmetic):
a = int(w[0])
b = int(w[1])
result = a / b
result = round(result, 3)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x) == 3):
a = int(x[1])
b = int(x[2])
result = a + b
result = result * (-1)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x) == 2):
a = int(x[0])
b = int(x[1])
result = a - b
print("The result is = " + str(result))
else:
print("Invalid")
tries += 1
continue
break
except ValueError: # for case split not working good due cases like first input is a negative number
print("Invalid")
tries += 1
At the end of your if / else if chain, just add:
else:
print("invalid")
tries += 1
Replace everything you have inside your while loop currently with the uncommented code above it and that should work.

formatting print statement for different values and function call

I'm practicing my python and trying to format the print statement of the below code for match_string so it will print in this format:
There are 5 numbers, 4 letters and 2 other characters.
I've tried to do:
print("There are:", + x.nums, + "numbers", +x.letters,+"letter", + x.other, +"other characters")
and I get the error:
AttributeError: 'tuple' object has no attribute 'nums'
I also think I have an issue with the getDupes part as well but i can't figure out what, it just prints the same as.
Here's my code:
def match_string(words):
nums = 0
letter = 0
other = 0
for i in words :
if i.isalpha():
letter+=1
elif i.isdigit():
nums+=1
else:
other+=1
return nums,letter,other
def getDupes(x):
d = {}
for i in x:
if i in d:
if d[i]:
yield i
d[i] = False
else:
d[i] = True
x = match_string(input("enter a sentence"))
c = getDupes(x)
print(x)
#print("There are:", + str(x.nums), + "numbers", +x.letters,+"letter", + x.other, +"other characters")
print("PRINT",x)
funtion match_string returns a tuple hence cannot be accessed by using x.nums
instead try the below code
nums,letter,other = match_string(input("enter a sentence"))
print("There are:", + nums, + "numbers", + letters,+"letter", + other, +"other characters")

Better way to print a true group in Python

I want to make a program that returns a group of True variables that i found in my program. Like this:
1 = True
2 = True
3 = False
4 = False
5 = True
What I want is to return as a print
The true numbers are: 1, 2 and 5
Edit 1:
The code is a letter counter!
eacha letter in a group has a value.
Like
a=1
b = 2
...
If a number repeats more than 4 times, that number is a true
The group would be a name. like John in an imput.
The program reads it and gives a number for each letter.
what I am using right now is this (Preatty ugly I know, but I started programing this month...), where "a" is the amount of letter a in the name, b is the amount of b in the name....
if (a + j + s) >=4:
exe1 = 1
else:
exe1 = ""
if (b + k + t) >=4:
exe2 = 2
else:
exe2 = ""
if (c + l + u) >=4:
exe3 = 3
else:
exe3 = ""
if (d + m + v) >=4:
exe4 = 4
else:
exe4 = ""
if (e + n + w) >=4:
exe5 = 5
else:
exe5 = ""
if (f + o + x) >=4:
exe6 = 6
else:
exe6 = ""
if (g + p + y) >=4:
exe7 = 7
else:
exe7 = ""
if (h + q + z) >=4:
exe8 = 8
else:
exe8 = ""
if (i + r) >=4:
exe9 = 9
else:
exe9 = ""
print("Excesses:", exe1, exe2, exe3, exe4, exe5, exe6, exe7, exe8, exe9)
Why don't you use a dictionary? Take a look in this code as an example.
dict1 = {1:'True', 2:'True', 3:'False', 4:'False', 5:'True'}
list = []
for k, v in dict1.items():
if v == 'True':
#print(k, sep=' ', end=',')
list.append(k)
print(list)
Now you the list - although inside brackets and I don't know how to remove them since they are part of the list... Maybe iteration over it again should solve the problem, although I am not a truly expert in Python.

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.

Categories

Resources