formatting print statement based on different end argument values - python

I am making a UI for termux terminal on android.
This code below prints the content of the directory.
It works perfectly fine but the output is not even, ie, irregular spaces between the columns.
I've seen people using format but in my case the end argument value differ on each print.
def display_dir(dir_name):
direc = os.listdir(dir_name)
for index, d in enumerate(direc):
if index % 2 == 0:
print(f"{index}- {d}", end=" " * 10)
else:
print(f"{index}- {d}", end="\n")
but I want perfectly aligned 2 column output.I've tried many things. Is there a short way to do this?
I actually have a solution where I check the longest string and add white spaces for remaining strings but it's not optimal.

You are probably looking for something like this:
def display_dir(dir_name):
direc = os.listdir(dir_name)
max_len = len(max(direc, key=len))
for index, d in enumerate(direc):
if index % 2 == 0:
print("{:2}- {:<{}}".format(index, d, max_len), end=" ")
else:
print("{:2}- {:<{}}".format(index, d, max_len), end="\n")
Or even further:
def display_dir(dir_name):
direc = os.listdir(dir_name)
max_len_even = len(max(direc[::2], key=len))
max_len_odd = len(max(direc[1::2], key=len))
index_pad_len = len(str(len(direc)))
for index, d in enumerate(direc):
if index % 2 == 0:
print("{:{}}- {:<{}}".format(index, index_pad_len, d, max_len_even), end=" ")
else:
print("{:{}}- {:<{}}".format(index, index_pad_len, d, max_len_odd), end="\n")

Related

i have a problem with strings and for loop in python

I have a string and I saved it inside a variable.
I want to change even characters to capitalize with for loop.
so i give my even characters and capitalized it. But
i cant bring them with odd characters .
can someone help me?
here is my code:
name = "mohammadhosein"
>>> for even in range(0, len(name), 2):
... if(even % 2 == 0):
... print(name[even].title(), end=' ')
...
M H M A H S I >>>
>>> ###### I want print it like this:MoHaMmAdHoSeIn```
I assume you are quite new to programing, so use a the following for loop:
name = "mohammadhosein"
output = ''
for i, c in enumerate(name):
if i % 2 == 0:
output += c.upper()
else:
output += c
# output will be 'MoHaMmAdHoSeIn'
enumerate will give you a pair of (i, c) where i is an index, starting at 0, and c is a character of name.
If you feel more comfortable with code you can use a list comprehension and join the results as follows:
>>> ''.join([c.upper() if i % 2 == 0 else c for i, c in enumerate(name)])
'MoHaMmAdHoSeIn'
As #SimonN has suggested, you just needed to make some small changes to your code:
for index in range(0, len(name)):
if(index % 2 == 0):
print(name[index].upper(), end='') # use upper instead of title it is more readable
else:
print(name[index], end='')
print()

Create multiplication table?

Am a beginner in Programming and am practicing how to use nested for loops to make a multiplication table in python 2.7.5.
Here is my code
x=range(1,11)
y=range(1,11)
for i in x:
for j in y:
print i*j
pass
well,the result is correct but it does not appear in a square matrix form as i wish.Please help me improve the code
You should print without a line break.
x = range(1,11)
y = range(1,11)
for i in x:
for j in y:
print i*j, # will not break the line
print # will break the line
you may add formatting to keep constant cell width
x = range(1,11)
y = range(1,11)
for i in x:
for j in y:
# substitute value for brackets
# force 4 characters, n stands for number
print '{:4n}'.format(i*j), # comma prevents line break
print # print empty line
Python's print statement adds new line character by default to the numbers you wish to have in your output. I guess you would like to have just a trailing spaces for inner loop and a new line character at the end of the outer loop.
You can achieve this by using
print i * j, # note the comma at the end (!)
and adding just a new line at the end of outer loop block:
print ''
To learn more about the trailing coma, and why it works, look here: "How to print in Python without newline or space?". Mind that it works differently in Python 3.
The final code should look like:
x=range(1,11)
y=range(1,11)
for i in x:
for j in y:
print i*j,
print ''
You can also look for '\t' special character which would allow you to get better formatting (even this old resource is good enough: https://docs.python.org/2.0/ref/strings.html)
USE This Code. It works MUCH better. I had to do this for school, and I can tell you that after putting about 4 hours into this it works flawlessly.
def returnValue(int1, int2):
return int1*int2
startingPoint = input("Hello! Please enter an integer: ")
endingPoint = input("Hello! Please enter a second integer: ")
int1 = int(startingPoint)
int2 = int(endingPoint)
spacing = "\t"
print("\n\n\n")
if int1 == int2:
print("Your integers cannot be the same number. Try again. ")
if int1 > int2:
print("The second number you entered has to be greater than the first. Try again. ")
for column in range(int1, int2+1, 1): #list through the rows(top to bottom)
if column == int1:
for y in range(int1-1,int2+1):
if y == int1-1:
print("", end=" \t")
else:
individualSpacing = len(str(returnValue(column, y)))
print(y, " ", end=" \t")
print()
print(column, end=spacing)
for row in range(int1, int2+1, 1): #list through each row's value. (Go through the columns)
#print("second range val: {:}".format(row))
individualMultiple = returnValue(row, column)
print(individualMultiple, " ", end = "\t")
print("")
Have a good day.
#Generate multiplication table by html
import random
from copy import deepcopy
N = 15
colors = ['F','E','D','C','B','A']
i = 0
colorsall = []
while i < N:
colornow = deepcopy(colors)
random.shuffle(colornow)
colornow = "#"+"".join(colornow)
colorsall.append(colornow)
i += 1
t = ""
for i in range(1,N+1):
s = ''
for j in range(1,N+1):
if j >= i:
s += '<td style="background-color:' + colorsall[i-1] + '">'+str(i*j)+'</td>'
else:
s += '<td style="background-color:' + colorsall[j-1] + '">'+str(i*j)+'</td>'
s = "<tr>" + s + "</tr>"
t = t + s + '\n'
print('<table>' + t + '</table>')
Taken from https://todaymylearn.blogspot.com/2022/02/multiplication-table-in-html-with-python.html [Disclosure : my blog]

Using raw_input with functions in Python

I want to execute a function certain number of times as specified by the user, for user-specified values. I have written the following code
queries = int(raw_input("The number of queries to run: "))
for i in range(0, queries):
a, b = raw_input().split(" ")
def count_substring(str):
length = len(str) + 1
found = []
for i in xrange(0, length):
for j in xrange(i+1, length):
if str[i] == a and str[j-1] == b:
found.append(str[i:j])
print len(found)
string = 'aacbb'
print count_substring(string)
The function gives the number of sub-strings that start and end with user specified characters.
For ex:
In the string "aacbb" the number of sub strings starting with a and ending with c are 2.
Queries indicates the number of inputs, ex for queries = 2 , there will be two inputs of the sub strings, i.e a & c or a & b
I want this code to return 2 values as answers, but it returns only 1.

Polynomial functions in python

I am very new in writing Python code. I have to represent polynomial like this,
4x^230+7x^96+1
testP = [[4,512],[7,256],[1,0]]
def printPoly2(P):
for i in range(len(P)):
if P[i] != 0:
print("%s x^%s + "%(P[i], i)),
print
printPoly2(testP)
but my answer is not correct. I need help on this.
I (hopefully) improved your code with some pythonic magic. Now it´s a list of tuples and uses automatic tuple-unwrapping.
testP = [(4, 230), (7, 96), (1, 0)]
def printPoly2(P):
for i, e in P:
if e != 0:
print("{} x^{} + ".format(i, e))
printPoly2(testP)
Prints out
4 x^230 +
7 x^96 +
Your problem is in the print statement. By writing:
print("%s x^%s + "%(P[i], i))
You are actually printing the entire tuple. For example, P[0] equals the entire list [4, 512]. So in directly printing P[i] you're just printing the entire sublist.
Instead, you want to print each element in the sublist.
print("%s x^%s" % (P[i][0], P[i][1]))
Additionally, your solution as-is will print each part of the answer on a separate line. To fix this you have a couple options, but here's one that doesn't depend on the python version you have. Basically, you create a string that represents your result, and keep building on it as you go through the loop. Then at the very end of the function, you print that string.
result = '' # initialize an empty string before your loop
Then inside your loop replace the print call with:
result = "%s + %s x^%s" % (result, P[i][0], P[i][1]
And at the very end of the function you can print the string.
print (result)
this is how I would write this code in something I think is a more pythonic way of writting it:
def poly2(P):
result = []
for item in P:
n, e = item
if e == 0:
result.append("1")
else:
result.append("{}x^{}".format(n, e))
return " + ".join(result)
# 4x^230 + 7x^96 + 1
testP = [(4,230), (7,96), (1,0)]
print poly2(testP)
note that its more flexible to return a string representation than to print it directly from the function.
Just had 5 more minutes... here you go
testP = [(4, 230), (7, 96), (1, 0)]
def printPoly2(polynom):
parts = []
for i, e in polynom:
parts.append(_format_polynome(i,e))
print " + ".join(parts)
def _format_polynome(i, e):
if e == 0:
return "{}".format(i)
else:
return "{} x^{}".format(i, e)
printPoly2(testP)

Counting differences between two strings

I'm trying to count the number of differences between two imported strings (seq1 and seq2, import code not listed), but am getting no result when running the program. I want the output to read something like "2 differences." Not sure where I'm going wrong...
def difference (seq1, seq2):
count = 0
for i in seq1:
if seq1[i] != seq2[i]:
count += 1
return (count)
print (count, "differences")
You could do this pretty flatly with a generator expression
count = sum(1 for a, b in zip(seq1, seq2) if a != b)
If the sequences are of a different length, then you may consider the difference in length to be difference in content (I would). In that case, tag on an extra piece to account for it
count = sum(1 for a, b in zip(seq1, seq2) if a != b) + abs(len(seq1) - len(seq2))
Another weirdish way to write that which takes advantage of True being 1 and False being 0 is:
sum(a != b for a, b in zip(seq1, seq2))+ abs(len(seq1) - len(seq2))
zip is a python builtin that allows you to iterate over two sequences at once. It will also terminate on the shortest sequence, observe:
>>> seq1 = 'hi'
>>> seq2 = 'world'
>>> for a, b in zip(seq1, seq2):
... print('a =', a, '| b =', b)
...
a = h | b = w
a = i | b = o
This will evaluate similar to sum([1, 1, 1]) where each 1 represents a difference between the two sequences. The if a != b filter causes the generator to only produce a value when a and b differ.
When you say for i in seq1 you are iterating over the characters, not the indexes. You can use enumerate by saying for i, ch in enumerate(seq1) instead.
Or even better, use the standard function zip to go through both sequences at once.
You also have a problem because you return before you print. Probably your return needs to be moved down and unindented.
in your script there are to mistakes
"i" should be integer, not char
"return" should be in function the same level as print, not in cycle "for"
try not to use "print" in such way in functions
here is working version:
def difference (seq1, seq2):
count = 0
for i in range(len(seq1)):
if seq1[i] != seq2[i]:
count += 1
return (count)
So I had to do what you are asking to do and I came up with a very simple solution. Mine is a little different because I check the string to see which is bigger and put them in the correct variable for comparison later. All done with Vanilla python:
#Declare Variables
a='Here is my first string'
b='Here is my second string'
notTheSame=0
count=0
#Check which string is bigger and put the bigger string in C and smaller string in D
if len(a) >= len(b):
c=a
d=b
if len(b) > len(a):
d=a
c=b
#While the counter is less than the length of the longest string, compare each letter.
while count < len(c):
if count == len(d):
break
if c[count] != d[count]:
print(c[count] + " not equal to " + d[count])
notTheSame = notTheSame + 1
else:
print(c[count] + " is equal to " + d[count])
count=count+1
#the below output is a count of all the differences + the difference between the 2 strings
print("Number of Differences: " + str(len(c)-len(d)+notTheSame))
Correct code would be:
def difference(seq1, seq2):
count = 0
for i in range(len(seq1)):
if seq1[i] != seq2[i]:
count += 1
return count
First the return statement is done at the end of the function, therefore it should not be part of the for loop or the for loop would just run once.
Second the for loop wasn't correct because you weren't really telling giving the for loop an integer, therefore the correct code would be to give it a range the length of seq1, so:
for i in range(len(seq1)):

Categories

Resources