Format output right to left - python-3.x

I am trying to learn how to format print to make it look neat. My program would count how many vowels are in a piece of text. But wont print the way I would like which is right to left
As example -
I would like it to print as:
a : 100
e : 50
i : 31
o : 10
u : 1
Currently I have it printing as the following:
a : 100
e : 50
i : 31
o : 10
u : 1
Here is my code and the printing option so far....
import sys
vowels = {i:0 for i in 'aeiou'}
def check(string):
for char in string:
if char in vowels:
vowels[char] +=1
return vowels
def main():
for line in sys.stdin:
lines = line.lower().strip()
check(lines)
sortvowels = sorted(vowels, key=vowels.get, reverse=True)
for r in sortvowels:
print(' {:} {} {:>d}'.format(r,":",vowels[r]))
#for keys, values in sorted(vowels.items(),reverse=False):
# print('{} : {:d}'.format(keys, vowels[maximum]))
if __name__ == '__main__':
main()

I solved this problem by obtaining the max value from my dictionary,
I had to add the additional code,
formt = max(vowels.values())
finalformat = len(str(formt))
I did this by formt = max(vowels.values())
In order to actually use this, I had to convert that into a string.
I did this by finalformat = len(str(formt))
To finally be able to print I did the following:
sortvowels = sorted(vowels, key=vowels.get, reverse=True)
for r in sortvowels:
print('{} {} {:>{}}'.format(r,":",vowels[r],finalformat))

Related

conting of input names

I have a python homework which I need to take n from input to know how many names I have to take from input, save them to a dictionary then count how many each name was inputed, something like voting system.
so far I couldn't save my input into a dic.
Because I stored all inputs in a list after I assign my list with a dict, it turns to str.
for example:
how many vote u want to input : 4
take your votes:
jack
jasmin
jack
sara
result:
jack 2
jasmin 1
sara 1
My code:
vorodi=[]
n=int(input())
counter={}
for i in range(0,n):
vorodi.append(input())
for letter in vorodi:
if letter not in counter:
counter[letter]+=1
else:
counter[letter]=1
print(counter)
This is a classic case where you will want to use defaultdict. With defaultdict you specify the type of new keys and so if the key is not present it will be initialized to the default of the type specified. So you could do:
from collections import defaultdict
n = int(input())
counter = defaultdict(int)
for i in range(n):
counter[input()] += 1
print(counter.items())
OR:
with regular dict using the get method with the default argument:
n = int(input())
counter = {}
for i in range(n):
name = input()
count = counter.get(name, 0)
counter[name] = count + 1
OR:
with regular dict using the setdefault method with the default argument:
n = int(input())
counter = {}
for i in range(n):
name = input()
counter.setdefault(name, 0)
counter[name] += 1
To print it as you showed you can simply iterate the dict afterwards:
for k,v in counter.items():
print(k, v)

Formatting required output for String slicing in Python

Beginner in python here, and I have a code that is supposed to slice a string evenly and oddly and display it.
Here is my code:
def even_bits(str):
result = ""
for i in range(len(str)):
if i % 2 == 0:
result = result + str[i]
return result
def odd_bits(str):
result = ""
for i in range(len(str)):
if i % 2 == 1:
result = result + str[i]
return result
for i in range(int(input())):
w = input('')
print(even_bits(w), ' ' ,odd_bits(w))
This runs correctly however gives output as follows:
Sample Input:
2
Hello
World
Sample Output:
2
Hello
Hlo el
World
Wrd ol
How do I format the output such that I get output as follows:
Sample Output:
Hlo el
Wrd ol
Thank You in advance.
You can first declare an input list that contains all input strings. Then iterate over the input list and print the even and odd characters:
def even_bits(chain):
result = ""
for i in range(len(chain)):
if i % 2 == 0:
result = result + chain[i]
return result
def odd_bits(chain):
result = ""
for i in range(len(chain)):
if i % 2 == 1:
result = result + chain[i]
return result
input_list = [] # input list that contains all input strings
for i in range(int(input())):
w = input('')
input_list.append(w)
# iterate over input list to print even and odd characters
for inp in input_list:
print(even_bits(inp), ' ', odd_bits(inp))
You can make two result lists. One for the even outputs, one for the odd outputs, then zip them and print each element. Also, you can easily take the even and odd letters using a single slice.
x = "Hello world"
# slicing looks like [START:STOP:STEP], so we can do
evens = x[0::2] # Will start at 0, go to the end, and take every 2nd character
odds = x[1::2] # Will start at 1, go to the end, and take every 2nd character
print(evens) # >>> Hlowrd
print(odds) # >>> el ol
This works even if you have an empty string.
Putting it all together, it could look like this:
def even_bits(my_str):
return my_str[0::2]
def odd_bits(my_str):
return my_str[1::2]
even_results = []
odd_results = []
for i in range(int(input("How many inputs: "))):
w = input('Input # {}: '.format(i+1))
even_results.append(even_bits(w))
odd_results.append(odd_bits(w))
for ev, od in zip(even_results, odd_results):
print(ev, od)
Output:
How many inputs: 2
Input # 1: Hello
Input # 2: World
Hlo el
Wrd ol

Longest word in a string using python programming

Hello guys I am still an armature in python was hoping if anyone could help with this solution.
Write a function called longest which will take a string of space separated words and will return the longest one.
For example:
longest("This is Fabulous") => "Fabulous"
longest("F") => "F"
class Test(unittest.TestCase):
def test_longest_word(self):
sentence = "This is Fabulous"
self.assertEqual('Fabulous', longest(sentence))
def test_one_word(self):
sentence = "This"
self.assertEqual("This", longest(sentence))
This is my solution so far;
def find_longest_word(word_list):
longest_word = ''
longest_size = 0
for word in word_list:
if (len(word) > longest_size)
longest_word = word
longest_size = len(word)
return longest_word
words = input('Please enter a few words')
word_list = words.split()
find_longest_word(word_list)
Unfortunately am getting this error when I try to test the code
"File "", line 6
if (len(word) > longest_size)
^
SyntaxError: invalid syntax
Any help please I will highly appreciate?
def find_longest_word(myText):
a = myText.split(' ')
return max(a, key=len)
text = "This is Fabulous"
print (find_longest_word(text)) #Fabulous
EDIT: The solution above works if you want one of the longest words and not all of them. For example if my text is "Hey ! How are you ?" It will return just "Hey". If you want it to return ["Hey", "How", "are", "you"]
Better use this.
def find_longest_word(myText):
a = myText.split(' ')
m = max(map(len,a))
return [x for x in a if len(x) == m]
print (find_longest_word("Hey ! How are you ?")) #['Hey', 'How', 'are', 'you']
See also, this question
You are missing the : at the end of the if statement
Use the updated code below, I fixed your indentation issues too.
def find_longest_word(word_list):
longest_word = ''
longest_size = 0
for word in word_list:
if (len(word) > longest_size):
longest_word = word
longest_size = len(word)
return longest_word
words = input('Please enter a few words')
word_list = words.split()
find_longest_word(word_list)
Code sample is incorrect. I get the following message if I try to output:
Error on line 15: print(longest_word("chair", "couch", "table"))
TypeError: longest_word() takes 1 positional argument but 3 were given
So the code looks like this:
def longest_word(word_list):
longest_word = ''
longest_size = 0
for word in word_list:
if (len(word) > longest_size):
longest_word = word
longest_size = len(word)
return longest_word
words = input("chair", "couch", "table")
word_list = words.split()
find_longest_word(word_list)
# longest word in a text
text = input("Enter your text")
#Create a list of strings by splitting the original string
split_txt = text.split(" ")
# create a dictionary as word:len(word)
text_dic = {i:len(i)for i in split_txt}
long_word = max([v for v in text_dic.values()])
for k,v in text_dic.items():
if long_word == v:
print(k)

Recognize loop for in other python scripts

First: sorry for my English!
I'm trying to write a python script that can recognize any loop for in other python scripts.
import re
with open('boite_a_fonctions_v3_1.py', 'r') as f:
text=f.read()
a = text.split(" ")
#print (a)
loop = re.compile(r'for"(.*):\t(.*)"')
def find_loop(a):
c = []
for line in a:
c += loop.findall(line)
print (c)
#find_loop(a)
I have nothing as a result (which already makes me happy, no mistakes !!). Anyone have any suggestions?
A part of the code 'boite_a_fonctions_v3_1.py':
fidr.seek(0)
reg = compile(fmt.get_motif())
id = 0
for line in fidr :
for seg in reg.findall(line) :
if id == tokenId :
mot, etq = seg
return mot, etq
else :
id += 1
return None
def get_tokens(fid, fmt, tokenIds):
if isinstance(tokenIds, int):
try :
return get_token(fid,fmt, tokenIds)
except :
return None
else:
n = None
for id in tokenIds:
try:
n = len(get_token(fid,fmt, id))
break
except:
pass
if not n :
return None
ret = list()
for i in range(n) :
tmp = list()
for id in tokenIds :
try:
tmp.append(get_token(fid,fmt,id)[i])
except:
pass
ret.append(tmp)
return ret
Though i am not experienced but i think this should give you output.
Make a multi line string variable with name "rr" in this case and run this code
and put all your file text in it as a multi line string
import re
rr="""All your input string here"""
print(len(re.findall(r'for(.*):(.*)',rr,re.M)))

acount total number of letter ONLY alphabet

I have a txt about a English story. My work is counting the total number of letters in this story(alphabet only from "a" to "z" and "A"to "Z" ) . this is what I have wrote:
def count():
file=open("xxx.txt","r")
for line in file:
I dont know how to type next, cuz I only need letter but not 'space",not"!",how can I improve it?
Easy way is to just count them all, then add up the ones you care about (ascii_letters in this case)
from collections import Counter
from string import ascii_letters
def count():
c = Counter()
with open("xxx.txt","r") as file:
for line in file:
c.update(line)
return sum(v for k, v in c.items() if k in ascii_letters)
Another terse approach is to use regex
def count():
with open("xxx.txt","r") as file:
return len(re.findall('[a-zA-Z]', file.read()))
Apparently this is homework and the teacher has imposed some arbitrary restrictions. Still not really any point using ord or chr here
def count():
c = 0
with open("xxx.txt","r") as file:
for line in file:
for ch in line:
if 'a' <= ch <= 'z' or 'A' <= ch <= 'Z':
c += 1
return c

Resources