Formatting lists to display leading zero - Python 3.x - python-3.x

I'm trying to create a matrix with 4 rows and 10 columns and display the leading 0 for all the single digit numbers that will randomly get generated later. This is what I would like it to look like: My teacher gave me this snippet as a way to format the numbers:
print('{:02}'.format(variable))
But when I use this in my function, it gives me the error: unsupported format string passed to list.__format__
I reworked my code and was able to get the leading zero, but now the 4x10 matrix is just 40 ints side by side. Anyone able to give me some help and an explanation?
My code:
def printMatrix(matrix):
for r in range(ROWS):
for c in range(COLS):
print('{:02}'.format(matrix[r][c]), end=' ')
def main():
matrix = [0]*ROWS
for i in range(ROWS):
matrix[i] = [0]*COLS
printMatrix(matrix)

You're really close, looks like you may just need another print() after the for-loop to put a newline after each row. Try this:
def printMatrix(matrix):
for r in range(ROWS):
for c in range(COLS):
print('{:02}'.format(matrix[r][c]), end=' ')
print()
Demo

you need a 0 in front .. i.e. {0:02}
print('{0:02}'.format(variable))
This 0 refer to the index of the parameters passed in e.g. this should work too:
print('{2:02}'.format("x", "y", variable))
Your code:
def printMatrix(matrix):
for r in range(ROWS):
for c in range(COLS):
print('{0:02}'.format(matrix[r][c]), end=' ')
def main():
matrix = [0]*ROWS
for i in range(ROWS):
matrix[i] = [0]*COLS
printMatrix(matrix)

Related

Alien Dictionary Python

Alien Dictionary
Link to the online judge -> LINK
Given a sorted dictionary of an alien language having N words and k starting alphabets of standard dictionary. Find the order of characters in the alien language.
Note: Many orders may be possible for a particular test case, thus you may return any valid order and output will be 1 if the order of string returned by the function is correct else 0 denoting incorrect string returned.
Example 1:
Input:
N = 5, K = 4
dict = {"baa","abcd","abca","cab","cad"}
Output:
1
Explanation:
Here order of characters is
'b', 'd', 'a', 'c' Note that words are sorted
and in the given language "baa" comes before
"abcd", therefore 'b' is before 'a' in output.
Similarly we can find other orders.
My working code:
from collections import defaultdict
class Solution:
def __init__(self):
self.vertList = defaultdict(list)
def addEdge(self,u,v):
self.vertList[u].append(v)
def topologicalSortDFS(self,givenV,visited,stack):
visited.add(givenV)
for nbr in self.vertList[givenV]:
if nbr not in visited:
self.topologicalSortDFS(nbr,visited,stack)
stack.append(givenV)
def findOrder(self,dict, N, K):
list1 = dict
for i in range(len(list1)-1):
word1 = list1[i]
word2 = list1[i+1]
rangej = min(len(word1),len(word2))
for j in range(rangej):
if word1[j] != word2[j]:
u = word1[j]
v = word2[j]
self.addEdge(u,v)
break
stack = []
visited = set()
vlist = [v for v in self.vertList]
for v in vlist:
if v not in visited:
self.topologicalSortDFS(v,visited,stack)
result = " ".join(stack[::-1])
return result
#{
# Driver Code Starts
#Initial Template for Python 3
class sort_by_order:
def __init__(self,s):
self.priority = {}
for i in range(len(s)):
self.priority[s[i]] = i
def transform(self,word):
new_word = ''
for c in word:
new_word += chr( ord('a') + self.priority[c] )
return new_word
def sort_this_list(self,lst):
lst.sort(key = self.transform)
if __name__ == '__main__':
t=int(input())
for _ in range(t):
line=input().strip().split()
n=int(line[0])
k=int(line[1])
alien_dict = [x for x in input().strip().split()]
duplicate_dict = alien_dict.copy()
ob=Solution()
order = ob.findOrder(alien_dict,n,k)
x = sort_by_order(order)
x.sort_this_list(duplicate_dict)
if duplicate_dict == alien_dict:
print(1)
else:
print(0)
My problem:
The code runs fine for the test cases that are given in the example but fails for ["baa", "abcd", "abca", "cab", "cad"]
It throws the following error for this input:
Runtime Error:
Runtime ErrorTraceback (most recent call last):
File "/home/e2beefe97937f518a410813879a35789.py", line 73, in <module>
x.sort_this_list(duplicate_dict)
File "/home/e2beefe97937f518a410813879a35789.py", line 58, in sort_this_list
lst.sort(key = self.transform)
File "/home/e2beefe97937f518a410813879a35789.py", line 54, in transform
new_word += chr( ord('a') + self.priority[c] )
KeyError: 'f'
Running in some other IDE:
If I explicitly give this input using some other IDE then the output I'm getting is b d a c
Interesting problem. Your idea is correct, it is a partially ordered set you can build a directed acyclcic graph and find an ordered list of vertices using topological sort.
The reason for your program to fail is because not all the letters that possibly some letters will not be added to your vertList.
Spoiler: adding the following line somewhere in your code solves the issue
vlist = [chr(ord('a') + v) for v in range(K)]
A simple failing example
Consider the input
2 4
baa abd
This will determine the following vertList
{"b": ["a"]}
The only constraint is that b must come before a in this alphabet. Your code returns the alphabet b a, since the letter d is not present you the driver code will produce an error when trying to check your solution. In my opinion it should simply output 0 in this situation.

Could anybody explain inside functioning of .replace method in Python?

I want to solve a problem which takes two inputs, 1st is a string and 2nd is it's substring. Then i have to remove all occurences of the substring in the string and return the remaining part of string.
Without using replace method.
Now if I know the length of substring, it's doable, but what if the length is unknown?
Thanks
Here's my answer, it fails when there are multiple occurrences of substring in the string. Now it works correctly.
inputS=input('string?')
inputSub=input('substring?')
s=list(inputS)
sub=list(inputSub)
print(sub)
z=len(s)-len(sub)+1
y=len(sub)
def remove_sub():
li=[] #index at which substring is present
for x in range(z):
if s[x]==sub[0]:
if y==1:
li.append(x)
continue
for temp in range(1,y):
if s[x+temp]==sub[temp]:
temp+=1
if temp==y:
li.append(x)
else:
print(x)
else:
continue
return(li)
li=remove_sub()
print(li)
temp2=0
for i in range(len(li)): #removing substring
del s[li[i]+temp2:(li[i]+y+temp2)]
temp2-=(y)
out=''.join(s)
print(out)
This works and doesn't use str.replace():
>>> "".join("bananaann".split("an"))
'ban'
Put it in a new function and you're done.
def replace_(original, sub_from, sub_to=""):
return sub_to.join(original.split(sub_from))
>>> replace_("bananaann", "an")
'ban'
inputS=input('string?')
inputSub=input('substring?')
s=list(inputS)
sub=list(inputSub)
print(sub)
z=len(s)-len(sub)+1
y=len(sub)
def remove_sub():
li=[] #index at which substring is present
for x in range(z):
if s[x]==sub[0]:
if y==1:
li.append(x)
continue
for temp in range(1,y):
if s[x+temp]==sub[temp]:
temp+=1
if temp==y:
li.append(x)
else:
print(x)
else:
continue
return(li)
li=remove_sub()
print(li)
temp2=0
for i in range(len(li)): '''removing substrings, works even for multiple occurences'''
del s[li[i]+temp2:(li[i]+y+temp2)]
temp2-=(y)
out=''.join(s)
print(out)

Error in reverse of string as the way i want to make this code useful is not working can olyone sort this out

a=input("Enter a line ")
b=a.split()
j=b
print(b)
c=int(len(b))
print(c)
for i in range(c):
print(i,-(i+1))
j[i]=b[-(i+1)]
print(j[i],b[-(i+1)])
print(j)
print(b)
r=" ".join(j)
print(r)
why there is error in this code like everytime a input some line to reverse it the result is not showing in the reverse order
If you just want to reverse the word order, you can do it like this:
def reverse_word_order(line):
parts = line.split()
return ' '.join(parts[::-1])
print(reverse_word_order(input('Enter a line:')))

Python3 Function returning only first values

I'm trying to make a function that opens a textfile, counts the words and then returns the top 7 words in percent. However when I run the code with "return" it only retrieves the first value but "print" gives me what I need + a "None".
def count_wfrequency(fname):
with open(fname,"r") as f:
dictionary = dict()
for line in f:
line = line.rstrip()
delaorden = line.split()
for word in delaorden:
dictionary[word] = dictionary.get(word,0) + 1
tmp = list()
for key, value in dictionary.items():
tmp.append((value, key))
tmp.sort(reverse=True)
for value, key in tmp[:7]:
b = ("{0:.0f}%".format(value / len(tmp)* 100))
print(key, b, end=", ")
the 9%, to 6%, of 5%, and 4%, in 3%, a 3%, would 2%, Frequency of words: None
What am I doing wrong?
edit: To clarify, I want to make it so that it prints out "Frequency of words: the 9%, to 6%...and so on.
Trying to use the function like this:
if args.word_frequency:
print("Frequency of words: {}".format(funk.count_wfrequency(args.filename)))

Inquiry about removing duplicates

Alright so I'm required to eliminate spaces and duplicate values in a list (of only numbers). Here's my code:
def eliminateDuplicates(lst):
i=0
while i<len(lst):
while lst.count(lst[i])!=1:
lst.remove(lst[i])
i=i+1
print(lst)
def main():
a=input("Enter numbers: ")
lst=list(a)
while ' ' in lst:
lst.remove(' ')
eliminateDuplicates(lst)
main()
while this method is effective and works, when the input is say
Enter numbers: 1 2 3 4 5 3 2 1 1 22
The output results in
['4', '5', '3', '1', '2']
I need my program to recognize 22 and 2 as different items so it doesn't delete the last 2 and the 2 in 22. Any suggestions?
EDIT: Sorry to the two posters that have already given me answers. I am not allowed to use the set function, and order does not matter.
This doesn't do what you think it does:
b="".join(a) # doesn't do anything useful since `a` is already a string
lst=list(b) # this is converting the string to a list of characters
Try this instead:
lst = a.split() # automatically cleans up the whitespace for you
print(list(set(lst)))
Turning a list into a set and back again is a handy way to remove duplicates. It's also quite efficient compared to the way you are doing it by scanning the list over and over
If you really want to keep the eliminateDuplicates function then it can just be
def eliminate_duplicates(lst):
return list(set(lst))
def main():
a=input("Enter numbers: ")
lst = a.split() # split automatically cleans up the whitespace
print(eliminate_duplicates(lst))
if __name__ == "__main__":
main()
Edit: since you're not allowed to use set, Collections is another fairly efficient method to remove duplicates
from collections import Counter
def eliminate_duplicates(lst):
return list(Counter(lst))
This is not quite so efficient, but still much better than two nested loops
from itertools import groupby
def eliminate_duplicates(lst):
[k for k,g in groupby(sorted(lst))]
Does order matter? If not cast it to a set and then cast it back to a list.
lst = [1,2,3,3,6,4,5,6, 3, 22]
lst2 = list(set(lst))
Also, you should probably use lst = a.split(' ') rather than join
def main():
a=input("Enter numbers: ") # Input the numbers
clean_a = a.strip(); #Cleans trailing white space.
lst=list(set(clean_a.split(' '))) #Split into tokens, and remove duplicates

Resources