Python formatting print - python

I'm having some formatting issues with my call to print function. For lack of knowledge of better ways to format, i've ended up with an issue. here is what it should look like
However the actual result of my print returns this.
def tupleMaker(inputString):
s1 = inputString.split()
# Adding the surname at the end of the string
s2 = [s1[len(s1) - 1]]
# Number of other names(no surname)
global noOfNames
noOfNames = len(s1) - 4
# Adding all the other names
for i in range(noOfNames):
s2.append((s1[i + 3]))
# Adding the Reg number
s2.append(s1[0])
# Adding the Degree scheme
s2.append(s1[2])
# Adding the year
s2.append("Year " + s1[1])
# Making it a tuple
t = ()
for i in range(len(s2)):
t = t + (s2[i],)
return t
def formatting(t):
s1 = ""
for i in range(len(t)):
s1 += t[i]
if (i == 0):
s1 += ", "
elif (i == len(t) - 4):
s1 += " "
else:
s1 += " "
#print(t[0] + ", ", end="")
#for i in range(noOfNames):
#print (t[i+1], end= " ")
#print(format(t[1+noOfNames], "<32s"))
#print(format(thenames, "<32d") + format(regNo, "<7d") + format(degScheme, ">6s") + format(year, ">1s")
print("")
print(s1)

I would recommend looking at using pythons built in string.format() function a small tutorial is located here: https://pyformat.info/

Related

Python reverse each word in a sentence without inbuilt function python while preserve order

Not allowed to use "Split(),Reverse(),Join() or regexes" or any other
helping inbuilt python function
input something like this:
" my name is scheven "
output like this:
"ym eman si nevehcs"
you need to consider removing the starting,inbetween,ending spaces aswell in the input
I have tried 2 tries, both failed i will share my try to solve this and maby an idea to improve it
First try:
def reverseString(someString):
#lenOfString = len(someString)-1
emptyList = []
for i in range(len(someString)):
emptyList.append(someString[i])
lenOfString = len(emptyList)-1
counter = 0
while counter < lenOfString:
if emptyList[counter] == " ":
counter+=1
if emptyList[lenOfString] == " ":
lenOfString-=1
else:
swappedChar = emptyList[counter]
emptyList[counter] = emptyList[lenOfString]
emptyList[lenOfString] = swappedChar
counter+=1
lenOfString-=1
str_contactantion = ""
#emptyList = emptyList[::-1]
#count_spaces_after_letter=0
for letter in emptyList:
if letter != " ":
str_contactantion+=letter
#str_contactantion+=" "
str_contactantion+=" "
return str_contactantion
second try:
def reverse(array, i, j):
emptyList = []
if (j == i ):
return ""
for k in range(i,j):
emptyList.append(array[k])
start = 0
end = len(emptyList) -1
if start > end: # ensure i <= j
start, end =end, start
while start < end:
emptyList[start], emptyList[end] = emptyList[end], emptyList[start]
start += 1
end -= 1
strconcat=""
for selement in emptyList:
strconcat+=selement
return strconcat
def reverseStr(someStr):
start=0
end=0
help=0
strconcat = ""
empty_list = []
for i in range(len(someStr)):
if(someStr[i] == " "):
continue
else:
start = i
j = start
while someStr[j] != " ":
j+=1
end = j
#if(reverse(someStr,start,end) != ""):
empty_list.append(reverse(someStr,start,end))
empty_list.append(" ")
for selement in empty_list:
strconcat += selement
i = end + 1
return strconcat
print(reverseStr(" my name is scheven "))
The following works without managing indices:
def reverseString(someString):
result = crnt = ""
for c in someString:
if c != " ":
crnt = c + crnt # build the reversed current token
elif crnt: # you only want to do anything for the first space of many
if result:
result += " " # append a space first
result += crnt # append the current token
crnt = "" # and reset it
if crnt:
result += " " + crnt
return result
reverseString(" my name is scheven ")
# 'ym eman si nevehcs'
Try this:
def reverseString(someString):
result = ""
word = ""
for i in (someString + " "):
if i == " ":
if word:
result = result + (result and " ") + word
word = ""
else:
word = i + word
return result
You can then call it like this:
reverseString(" my name is scheven ")
# Output: 'ym eman si nevehcs'
Try this:
string = " my name is scheven "
def reverseString(someString):
result = ''
curr_word = ''
for i in someString:
if i == ' ':
if curr_word:
if result:
result = f'{result} {curr_word}'
else:
result = f'{result}{curr_word}'
curr_word = ''
else:
curr_word = f'{i}{curr_word}'
return result
print(repr(reverseString(string)))
Output:
'ym eman si nevehcs'
Note: if you're allowed to use list.append method, I'd suggest using a collections.deque as it's more performant than appending to a list. But of course, in the end you'll need to join the list together, and you mentioned that you're not allowed to use str.join, so that certainly poses an issue.

Rosalind Consensus and Profile Problem code doesn't work

This is the problem: http://rosalind.info/problems/cons/
def file_read(fname):
with open(fname, "r") as myfile:
global data
data = myfile.readlines()
print(data)
i = 0
while i < len(data):
data[i] = data[i].replace("\n", "")
if ">" in data[i]:
data.remove(data[i])
else:
i += 1
file_read('rosalind_cons.txt')
res = ["".join(el) for el in zip(*data)]
print(res)
a_str = ""
c_str = ""
g_str = ""
t_str = ""
for x in range(0, len(res)):
a_str += (str(res[x].count("A"))) + " "
for x in range(0, len(res)):
c_str += (str(res[x].count("C"))) + " "
for x in range(0, len(res)):
g_str += (str(res[x].count("G"))) + " "
for x in range(0, len(res)):
t_str += (str(res[x].count("T"))) + " "
a_str_nospace = a_str.replace(" ", "")
c_str_nospace = c_str.replace(" ", "")
g_str_nospace = g_str.replace(" ", "")
t_str_nospace = t_str.replace(" ", "")
consensus_string = ""
for x in range(0, len(a_str_nospace)):
if max(a_str_nospace[x], c_str_nospace[x], g_str_nospace[x], t_str_nospace[x]) in a_str_nospace[x]:
consensus_string += "A"
elif max(a_str_nospace[x], c_str_nospace[x], g_str_nospace[x], t_str_nospace[x]) in c_str_nospace[x]:
consensus_string += "C"
elif max(a_str_nospace[x], c_str_nospace[x], g_str_nospace[x], t_str_nospace[x]) in g_str_nospace[x]:
consensus_string += "G"
elif max(a_str_nospace[x], c_str_nospace[x], g_str_nospace[x], t_str_nospace[x]) in t_str_nospace[x]:
consensus_string += "T"
print(consensus_string)
print("A: " + a_str)
print("C: " + c_str)
print("G: " + g_str)
print("T: " + t_str)
What's wrong with my code?
For the sample output it works but for the larger datasets it doesn't.
I don't know what is wrong, I think it's the file reading part that's not correct (maybe?)
EDIT: There are some print functions in there but I don't copy them in the answer box so they don't matter in the result
nice to see a fellow Rosalind user. I discovered that page when I studied Bioinformatics and just stumbled upon it again last month.
To answer your question:
You're creating a string of numbers, so that works fine if the numbers are all below 10.
Try building a list of integers first and only convert them to a string in the final step.

Kattis Polish Notation challenge in Python

I'm trying to do the polish notation challenge on kattis.com. Thing is, I feel I have done everything they asked for and I've tried fixing everything I could think of. I even looked up some other's solutions and while theirs are more clean I want to continue on mine as I am learning.
Why is it that for example this person's code works but not mine?
Here is my current code:
import sys
case = 1
valid_ints = set([str(i) for i in range(-10,11)])
def simplify(index, myLine, processed):
while index+1 > 0:
if (myLine[index] == "+" or myLine[index] == "-" or myLine[index] == "*") and index < len(myLine)-2:
if myLine[index+1] in valid_ints and myLine[index+2] in valid_ints:
try:
processed = myLine[index+3:] + processed
a = str(myLine[index+1] + myLine[index] + myLine[index+2])
processed.insert(0, str(eval(a)))
del myLine[index:]
except:
processed = [myLine[index], myLine[index+1], myLine[index+2]] + processed
del myLine[index:]
elif len(myLine) < 3:
processed = myLine + processed
del myLine[index]
index -= 1
processed = myLine + processed
return processed
for line in sys.stdin:
myLine = line.split()
processed = []
index = len(myLine)-1
savedprocessed = []
processed = simplify(index, myLine, processed)
while True:
if savedprocessed == processed:
break
else:
savedprocessed = []
savedprocessed += processed
processed = simplify(len(processed)-1, processed, [])
result = " ".join(savedprocessed)
print("Case " + str(case) + ": " + result)
case += 1
if case > 5:
break
You're bringing some other language style to Python, that's unnecessary because Python is more flexible.
I've simplified as much as I can here.
Split the input string on white spaces and iterate over the tokens.
For every operator in the expression, push a list onto the stack and append the operator and its operands to the list.
Now pop each list off the stack and process the list
def simplify(exp):
stack1 = []
ops = set('+*-')
for token in exp.split():
if token in ops:
stack1.append([])
stack1[-1].append(token)
stack2 = []
while stack1:
top = stack1.pop()
while len(top) < 3 and stack2:
top.append(stack2.pop())
if any(x.isalpha() for x in top):
simplified = ' '.join(top)
else:
top[0], top[1] = top[1], top[0]
simplified = str(eval(''.join(top)))
stack2.append(simplified)
return simplified
exp = '* - 6 + x -6 - - 9 6 * 0 c'
print(exp)
simplify(exp)
Output;
* - 6 + x -6 - - 9 6 * 0 c
* - 6 + x -6 - - 3 * 0 c

Fixing right alignment of string formatting

I'm trying to align the output of the list like shown:
But it keeps coming out like this:
My code for all of this is:
subject_amount = int(input("\nHow many subject do you want to enrol? "))
class Subject:
def __init__(self, subject_code, credit_point):
self.subject_code = subject_code
self.credit_point = credit_point
subjects = []
for i in range(1, (subject_amount + 1)):
subject_code = input("\nEnter subject " + str(i) + ": ")
credit_point = int(input("Enter subject " + str(i) + " credit point: "))
subject = Subject(subject_code, credit_point)
subjects.append(subject)
print ("\nSelected subjects: ")
i, total = 0, 0
print("{0:<} {1:>11}".format("Subject: ", "CP"))
while(i < subject_amount):
print("{0:<} {1:14}".format(subjects[i].subject_code, subjects[i].credit_point))
total += subjects[i].credit_point
i = i + 1
print("{0:<} {1:>11}".format("Total cp: ", total))
I've tried changing the values for the spacing as well with no results.
Any feedback on the rest of my code is also greatly appreciated.
You can't do this using plain Python formatting because the amount of padding depends on both strings. Try defining a function such as:
def format_justified(left, right, total):
padding = total - len(left)
return "{{0}}{{1:>{}}}".format(padding).format(left, right)
then simply use:
print(format_justified("Total cp:", total, 25))
where 25 is the total line width you want.

New Hangman Python

I am working on a Hangman game, but I am having trouble replacing the dashes with the guessed letter. The new string just adds on new dashes instead of replacing the dashes with the guessed letter.
I would really appreciate it if anyone could help.
import random
import math
import os
game = 0
points = 4
original = ["++12345","+*2222","*+33333","**444"]
plusortimes = ["+","*"]
numbers = ["1","2","3"]
#FUNCTIONS
def firstPart():
print "Welcome to the Numeric-Hangman game!"
def example():
result = ""
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
return ori
# def actualGame(length):
#TOP LEVEL
firstPart()
play = raw_input("Do you want to play ? Y - yes, N - no: ")
while (play == "Y" and (points >= 2)):
game = game + 1
points = points
print "Playing game #: ",game
print "Your points so far are: ",points
limit = input("Maximum wrong guesses you want to have allowed? ")
length = input("Maximum length you want for the formulas (including symbols) (must be >= 5)? ")
result = "" #TRACE
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
test = eval(result[:-1])
v = random.choice(plusortimes) #start of randomly generated formula
va = random.choice(plusortimes)
formula = ""
while (len(formula) <= (length - 3)):
formula = formula + random.choice(numbers)
formula2 = str(v + va + formula)
kind = ""
for i in range(2,len(formula2)):
if i % 2 == 0:
kind = kind + formula2[i] + formula2[0]
else:
kind = kind + formula2[i] + formula2[1]
formula3 = eval(kind[:-1])
partial_fmla = "------"
print " (JUST TO TRACE, the program invented the formula: )" ,ori
print " (JUST TO TRACE, the program evaluated the formula: )",test
print "The formula you will have to guess has",length,"symbols: ",partial_fmla
print "You can use digits 1 to 3 and symbols + *"
guess = raw_input("Please enter an operation symbol or digit: ")
a = 0
new = ""
while a<limit:
for i in range(len(formula2)):
if (formula2[i] == partial_fmla[i]):
new = new + partial_fmla[i]
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
a = a+1
print new
guess = raw_input("Please enter an operation symbol or digit: ")
play = raw_input("Do you want to play ? Y - yes, N - no: ")
The following block seems problematic:
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
Python does not allow modification of characters within strings, as they are immutable (cannot be changed). Try appending the desired character to your new string instead. For example:
elif formula2[i] == guess:
new += guess
else:
new += '-'
Finally, you should put the definition of new inside the loop directly under, as you want to regenerate it after each guess.

Categories