Can someone enlighten me how to do this?
Write a Python program that reads a series of lines one by one from the keyboard (ending by an empty line) and, at the end, outputs the number of times that the first line occurred. For example, if it reads
hello
world
We say hello
hello
Birkbeck
hello
it would output 3 since the first line ("hello") occurred three times.
You may assume that the user enters at least two non-empty lines before the empty line.
not sure if you want to separate word with spaces or with the newline character and if we count the first occurence.
This is a sample solution for spaces separation between words. This works for the example that you provided
freq_dict = {}
word = input().split()
for w in word:
if w not in freq_dict.keys():
freq_dict[w] = 0
else:
freq_dict[w] += 1
print(freq_dict[word[0]])
Related
So I'm having trouble with enters and line breaks in my code. I must use easyinput library (and import read).
My code stands for:
Input: Input consists of several cases separated by an empty line. Every case has three parts ('lines'). The first one is a line with the translation table: 26 different characters (with no spaces nor ‘_’), the first one corresponding to ‘a’, the second one to ‘b’, …, and the last one to ‘z’. The second part is a number n > 0 in a line. The third part consists of n encrypted lines of text.
Output: For each case, write the original text, also with n lines. Change each ‘_’ of the encrypted text for a space. Write an empty line at the end of each case.
So I figured out how to solve the problem, the things is that my code prints 'well' entering line by line in input. But the problem input must be entered the whole entire. I put an example for better understanding:
Some input should be:
52-!813467/09*+.[();?`]<:>
6
5_3++!_305))_6*_;48_26)4+.)_4+);80_6*_;48_!8`60)_)85;
;]8*;:_+*8_!83(88)_5*!_;46(;88*_96*?;8)
*+(;485);_5*!_2:_*+(;4
956*_2(5*-4_)8`8*;4_0692_85);_)6!8
)4++;_1(+9_;48_081;_8:8_+1_;48_!85;4)_485!
5_288_06*8_1(+9_;48_;(88_;4(+?34_;48_)4+;_161;:_188;_+?;
bcdefghijklmnopqrstuvwxyza
3
cfxbsf_pg_cvht_jo_uif_bcpwf_dpef
j_ibwf_pomz_qspwfe_ju_dpssfdu
opu_usjfe_ju
And its output must be:
a good glass in the bishops hostel in the devils seat
twenty one degrees and thirteen minutes
northeast and by north
main branch seventh limb east side
shoot from the left eye of the deaths head
a bee line from the tree through the shot fifty feet out
beware of bugs in the above code
i have only proved it correct
not tried it
My code far now is:
from easyinput import read
abc = 'abcdefghijklmnopqrstuvwxyz'
values = [letter for letter in abc]
old_abc = read(str)
while old_abc is not None:
keys = [old_letter for old_letter in old_abc]
dict_abc = dict(zip(keys, values))
num_lines = read(int)
for i in range(num_lines):
line = read(str)
for j in line:
if j == '_':
print(' ', end = '')
else:
print(dict_abc[str(j)], end = '')
print('\n')
old_abc = read(str)
I do not find a way of making my code easier, I just want some help to finally print the desired output. Thanks
I have an assignment that has instructions as follows:
write a program that reads in 4 sets of 4 dashed lines and outputs the four binary symbols that each set of four lines represents.
input consists of 16 lines in total, consisting of any number of dashes and spaces.
the first four lines represents a symbol, the next four lines represents the next symbol and so on.
print out the four binary-encoded symbols represented by the 16 lines in total.
each binary symbol should be on its own line
This is based upon a previous program that I wrote where input is a single line of text consisting of any number of spaces and dashes. If there is an even number of dashes in the line, output 0. Otherwise, output 1.
This is the code for the above:
line = input()
num_dashes = line.count("-")
mod = num_dashes % 2
if mod == 0:
print("0")
else:
print("1")
Please may someone assist me?
Thank you.
The code you have for processing one line is fine, although you could replace the if...else with just:
print(mod)
Now to extend this to multiple lines, it might be better not to call print like that, but to collect the output in a variable, and only output that variable when all 16 lines have been processed. This way the output does not get mixed with the input from the console.
So for instance, it could happen like this:
output = []
for part in range(4): # loop 4 times
digits = ""
for line in range(4): # loop 4 times
line = input()
num_dashes = line.count("-")
mod = num_dashes % 2
digits += str(mod) # collect the digit
output.append(digits) # append 4 digits to a list
print("\n".join(output)) # print the list, separated by linebreaks
This is for a homework assignment, we were asked to write a for loop that starts at the beginning of a user inputted string and then print every 2nd letter
I have tried to add a new line but that didn't solve the issue. I have tried to do it without using the range function by using
for char in s: and that produces the same results as using the range function
s = input('Please enter a string: ')
for i in range(len(s)):
print(i, s[0::2].upper())
If the word was Testing it should print out like this
T
S
I
G
with every letter capitalized. It wouldn't be double spaced I just had to format it look right on here. My code will pick up every 2nd letter but it prints it all out on one line instead of printing it out individually and then prints out TSIG 7 times.
This one is probably what you want.
INPUT:
s = raw_input('Please enter a string: ')
s=s[0::2].upper()
for i in range(len(s)):
print(s[i])
OUTPUT:
Please enter a string: TESTING
T
S
I
G
Try this:
s = 'testing'
for i in s[::2]:
print(i)
Your issue is that you are printing s[0::2].upper() every loop, and it is not affected by i:
I have 3 parts in my code. My first part tells me what line number the condition is on for line1. My second part tells me what line number the condition is on for line2. The last part makes the numbers as a range and prints out the range.
The first part of the code: I get a result of 6 for num1.
For the second part of the code I get 24 when i run it by itself but a 18 when i run it with part 1.
Then at the 3rd part i index the file and i try to get the proper lines to print out, but they dont work because my first part of my code is changing numbers when i have both conditions running at the same time.
Is there a better way to run this code with either just indexing or just enumerating? I need to have user input and be able to print out a range of of the file based off the input.
#Python3.7.x
#
#
import linecache
#report=input('Name of the file of Nmap Scan:\n')
#target_ip=input('Which target is the report needed on?:\n')
report = "ScanTest.txt"
target_ip = "10.10.100.2"
begins = "Nmap scan report for"
fhand = open(report,'r')
beginsend = "\n"
#first statement
for num1,line1 in enumerate(fhand, 1):
line1 = line1.rstrip()
if line1.startswith(begins) and line1.endswith(target_ip):
print(num1)
print(line1)
break
#second statement
for num2,line2 in enumerate(fhand, 1):
line2 = line2.rstrip()
if line2.startswith(beginsend) and num2 > num1:
print(num2)
print(line2)
break
with open('ScanTest.txt') as f:
linecount = sum(1 for line in f)
for i in range(num1,num2):
print(linecache.getline("ScanTest.txt", i))
The first part of the code: I get a result of 6 for num1. for the second part of the code I get 24 when i run it by itself but a 18 when i run it with part 1.
Obviously the second part continues reading the file where the first part stopped.
The minimal change is to put
num2 += num1
after the second loop, or just change the 3rd loop to for i in range(num1, num1+num2):. The condition and num2 > num1 within the second loop is to be removed.
I want to write a program that reads every word from every line of a text file.
I tried using nested loop but the second loop starts reading each word. Can someone explain this? Accodrding to me it should read the individual words instead of letters.
fh=open("romeo.txt")
d=dict()
c=0
for i in fh:
for j in i:
d[c]=j
c+=1
print(d)
for i in d:
print(d.get('moon',None))
the output is shown in Picture 1
I made a code which does the thing I want but is there any short way to do it?
fh=open("romeo.txt")
d=dict()
c=0
for i in fh:
i=i.rstrip()
print("by the first loop ######################", i)
k=i.split()
for j in k:
print("by the second loop ##################", j)
d[c]=j
c+=1
print(d)
the output which I want is given in Picture 2
Also, can I use split() function here to do it?
How can I use it because it seems to get only the last line of the file as a list and I want all the words in list or dictionary.
Thank You
for i in fh:
This line iterates through each line of text in the file
for j in i:
Since i is a string, this line iterates through each letter in each line. Instead of doing it this way, split() the line over whitespace and then iterate through the resulting list:
for line in fh:
for word in line.split():
#do stuff
Anyway since you wanted a short way to do it here's a neat one liner:
To make a list of each word in the file:
[word for line in open("romeo.txt") for word in line.split()]
To make a dict (list is better since your keys are integer indices anyway):
{c: i for c, i in enumerate([word for line in open("romeo.txt") for word in line.split()])}