I imported a text file from URL and want to process it. The file looks as below. There are two instances of " innings " and "Extras ". I want to extract lines between the FIRST instance of " innings " and FIRST instance of "Extras ". The code that I wrote extracts ALL instances. How do I resolve this?
Toss: Sri Lanka Umpires: M Erasmus (South Africa) and NJ Llong
(England) TV umpire: S Ravi (India) Match referee: DC Boon
(Australia) Reserve umpire: SD Fry (Australia) Player of the
match: CJ Anderson New Zealand innings (50 overs maximum)
R M B 4 6 MJ Guptill c Sangakkara b Lakmal
49 94 62 5 0 CJ Anderson c Lakmal b
Kulasekara 75 77 46 8 2
+L Ronchi not out 29 29 19 4 0
Extras (lb 2, w 8, nb 3) 13 Total (6 wickets, 50 overs, 226 mins) 331
Sri Lanka innings (target: 332 runs from 50 overs) R
M B 4 6 HDRL Thirimanne b Boult
65 90 60 8 0 RAS Lakmal not out
7 21 17 0 0
Extras (w 10, nb 1) 11 Total (all out, 46.1 overs, 210 mins) 233
Here is my code:
flag = 1
for line in data:
if " innings " in line:
flag = 0
print('')
if line.startswith("Extras "):
flag = 1
print('')
if not flag and not " innings " in line:
print(line)
Your program must stop on the first occurrence of Extras:
active = False # A variable `flag` is not very precisely named,
# better call it `active`, make it boolean
# and flip the values
for line in data:
if " innings " in line:
active = True # now we want to do things
print('')
continue # but not in this loop
if line.startswith("Extras "):
print('')
break # now we're done!
# alternative Method:
# active = False
if active:
print(line)
If you want to store all occurrences:
active = False
stored = []
for line in data:
if " innings " in line:
tmp = []
active = True # now we want to do things
continue # but not in this loop
if line.startswith("Extras "):
stored.append(tmp)
active = False
continue
if active:
tmp.append(line)
You'll end up with a list of lists of lines for further processing.
Related
Receiving this error when trying to compile code on replit. I have already tried to declare two arrays, you need to use separate DIM statements for each array:
as 20 DIM W$(10)
30 DIM G$(26)
Error: ParseError: Parse error on line 20: Unexpected token DIM
Any suggestions on how to resolve this issue
10 REM Hangman game
20 REM Set up variables
30 DIM W$(10), G$(26)
40 LET C = 0
50 LET I = 0
60 LET J = 0
70 REM Set up word list
80 W$(1) = "HANGMAN"
90 W$(2) = "BASIC"
100 W$(3) = "COMPUTER"
110 W$(4) = "PROGRAM"
120 W$(5) = "VINTAGE"
130 REM Select a random word
140 LET R = INT(RND(1) * 5) + 1
150 LET W = W$(R)
160 REM Set up guess string
170 FOR I = 1 TO LEN(W)
180 G$(I) = "-"
190 NEXT I
200 REM Main game loop
210 DO
220 CLS
230 PRINT "Hangman"
240 PRINT
250 PRINT "Word: ";
260 FOR I = 1 TO LEN(W)
270 PRINT G$(I);
280 NEXT I
290 PRINT
300 PRINT "Guesses: ";
310 FOR I = 1 TO 26
320 IF G$(I) <> "-" THEN PRINT G$(I);
330 NEXT I
340 PRINT
350 INPUT "Enter a letter: ", L$
360 IF LEN(L$) > 1 THEN 400
370 IF L$ < "A" OR L$ > "Z" THEN 400
380 LET L = ASC(L$) - 64
390 GOTO 420
400 PRINT "Invalid input. Please enter a single letter."
410 GOTO 350
420 REM Check if letter is in word
430 LET F = 0
440 FOR I = 1 TO LEN(W)
450 IF MID$(W, I, 1) = L$ THEN G$(I) = L$: F = 1
460 NEXT I
470 IF F = 0 THEN C = C + 1
480 IF C = 6 THEN 600
490 REM Check for win
500 LET WN = 1
510 FOR I = 1 TO LEN(W)
520 IF G$(I) = "-" THEN WN = 0
530 NEXT I
540 IF WN THEN PRINT "You win!": GOTO 650
550 REM Check for loss
560 IF C = 6 THEN PRINT "You lose. The word was "; W: GOTO 650
570 LOOP
600 REM Draw hangman
610 PRINT " _____"
620 PRINT " | |"
630 IF C > 1 THEN PRINT " O |" ELSE PRINT " |"
640 IF C > 2 THEN PRINT "/|\ |" ELSE PRINT " |"
650 END
/////
I tried declaring separate arrays. I also tried running it on a vintage basic terminal, and received an error with line 150 "type mismatch"
I am trying to create a Top 5 leaderboard for my game in Python 3.
Here's what I have
Top_Score = open("highscore.txt", "r+")
score_list = []
print(" Top 5")
print("==========")
for line in Top_Score.readlines(): # Read lines
score_list.append(line)
score_list.sort()
for i in range(5):
print("Pos", str(i + 1), ":", score_list[i])
print("==========")
Top_Score.close()
highscore.txt
50
18
20
40
50
60
70
Output
Top 5
==========
Pos 1 : 18
Pos 2 : 20
Pos 3 : 40
Pos 4 : 50
Pos 5 : 50
==========
But how can I display element in my text file if it is lesser than the range(5) without any errors? Any help would be appreciated
Example highscore.txt
50
18
20
Example Output
Top 5
==========
Pos 1 : 18
Pos 2 : 20
Pos 3 : 50
==========
In the print loop, you need to check if the size of the list is smaller than 5. If so, only loop until the size.
So, something like this:
loop_range = 5
if len(score_list) < loop_range:
loop_range = len(score_list)
for i in range(loop_range):
print("Pos", str(i + 1), ":", score_list[i])
This can be rewritten using the min function to select the smaller of the two numbers, 5 or the size:
loop_range = min(5, len(score_list))
for i in range(loop_range):
print("Pos", str(i + 1), ":", score_list[i])
I am currently printing onto console, can I print the output onto a text file in tabular form?
I am trying to write the file with:
with open("increment.txt", "w") as file:
file.write(i, mol)
file.close()
Here is the program:
import numpy as np
i: int
for i in range(1, 100,5):
mol = int((i*5)/(i+2))
print('i & mol are:',i, mol)
with open("incre.txt", "w") as file:
file.write(i, mol)
file.close()
Error message..
file.write(i, mol)
TypeError: write() argument must be str, not tuple
You are defining mol inside of your loop; here is the corrected code as far as I understand your question:
with open("incre.txt", "w") as file:
for i in range(1, 100, 5):
mol = int((i * 5) / (i + 2))
file.write(str(i) + " " + str(mol))
file.close()
This will write your i variable separated by a space, then your mol variable. Note since you haven't specified an output directory, it will create the file wherever your python script is stored.
Here is a more pythonic approach:
def write_example(output_path):
with open(output_path, "w") as file:
for i in range(1, 100, 5):
mol = int((i * 5) / (i + 2))
file.write(str(i) + " " + str(mol) + "\n")
file.close()
outpath = "/home/some_path_here/test.txt"
write_example(outpath)
This produces a txt file with the following contents:
1 1
6 3
11 4
16 4
21 4
26 4
31 4
36 4
41 4
46 4
51 4
56 4
61 4
66 4
71 4
76 4
81 4
86 4
91 4
96 4
Each of these being on a new line.
Let me know if this helped! Cheers!
Sort the given set of numbers using Bubble Sort. The first line of the input contains the number of elements, the second line of the input contains the numbers to be sorted. In the output print the status of the array at the 3rd iteration and the final sorted array in the given format
alist=[]
def bubble_sort(alist):
for i in range(len(alist) - 1, 0, -1):
no_swap = True
for j in range(0, i):
if alist[j + 1] < alist[j]:
alist[j], alist[j + 1] = alist[j + 1], alist[j]
no_swap = False
if no_swap:
return
n=int(input())
for i in range(n):
alist.append(int(input()))
alist = [int(x) for x in alist]
bubble_sort(alist)
print('Sorted array: ', end='\n')
for i in alist:
print(i,end=" ")
Test Case 1
7
64
34
25
12
22
11
90
Expected Output:
It should print the following 3 lines
12 22 11 25 34 64 90
Sorted array:
11 12 22 25 34 64 90
Test Case 2
8
14
83
25
47
9
77
1
0
Expected Output:
It should print the 3 following lines
14 9 25 1 0 47 77 83
Sorted array:
0 1 9 14 25 47 77 83
Just add in your for loop a print when you reach the third iteration
alist=[]
def bubble_sort(alist):
number_of_iterations = 0
for i in range(len(alist) - 1, 0, -1):
no_swap = True
for j in range(0, i):
if alist[j + 1] < alist[j]:
alist[j], alist[j + 1] = alist[j + 1], alist[j]
no_swap = False
if i == len(alist) - 3:
print(*alist) # Using the unpacking operator for pretty print, if you are in python2 you can print it this way : " ".join(map(str, alist))
if no_swap:
return
n=5
alist = [7, 64, 34, 25, 12, 22, 11, 90]
bubble_sort(alist)
print('Sorted array: ', end='\n')
for i in alist:
print(i,end=" ")
I have this code from a tutorial:
#File called test
1 def sanitize(time_string):
2 if '-' in time_string:
3 splitter = '-'
4 elif ':' in time_string:
5 splitter = ':'
6 else:
7 return(time_string)
8 (mins, secs) = time_string.split(splitter)
9 return(mins + '.' + secs)
10
11
12
13 def get_coach_data(filename):
14 with open(filename) as f:
15 data = f.readline()
16 temp1 = data.strip().split(',')
17 return(Athlete(temp1.pop(0), temp1.pop(0), temp1)
18
19
20 james = get_coach_data('james2.txt')
21 julie = get_coach_data('julie2.txt')
22 mikey = get_coach_data('mikey2.txt')
23 sarah = get_coach_data('sarah2.txt')
24
25 print(james.name+"'s fastest times are: " + str(james.top3()))
26 print(juliename+"'s fastest times are: " + str(julie.top3()))
27 print(mikey.name+"'s fastest times are: " + str(mikey.top3()))
28 print(sarah.name+"'s fastest times are: " + str(sarah.top3()))
and I put this class separately because I thought it may have been causing the error:
1 class Athlete:
2 def __init__(self, a_name, a_dob=None, a_times=[]):
3 self.name = a_name
4 self.dob = a_dob
5 self.times = a_times
6
7 def top3(self):
8 return(sorted(set([sanitize(t) for t in self.times]))[0:3])
The error is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "test.py", line 20
james = get_coach_data('james2.txt')
But the error doesn't make any sense. I am new to python. I appreciate anyones help. Thanks in advance.
The errors that I can see are:
return(Athlete(temp1.pop(0), temp1.pop(0), temp1)
in get_coach_data should just be
return Athlete(temp1.pop(0), temp1.pop(0), temp1)
on line 17
juliename should be julie.name on line 26