Why is python giving me a Syntax error? - python-3.x

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

Related

How many ways to get the change?

While practicing the following dynamic programming question on HackerRank, I got the 'timeout' error. The code run successfully on some test examples, but got 'timeout' errors on others. I'm wondering how can I further improve the code.
The question is
Given an amount and the denominations of coins available, determine how many ways change can be made for amount. There is a limitless supply of each coin type.
Example:
n = 3
c = [8, 3, 1, 2]
There are 3 ways to make change for n=3 : {1, 1, 1}, {1, 2}, and {3}.
My current code is
import math
import os
import random
import re
import sys
from functools import lru_cache
#
# Complete the 'getWays' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts following parameters:
# 1. INTEGER n
# 2. LONG_INTEGER_ARRAY c
#
def getWays(n, c):
# Write your code here
#c = sorted(c)
#lru_cache
def get_ways_recursive(n, cur_idx):
cur_denom = c[cur_idx]
n_ways = 0
if n == 0:
return 1
if cur_idx == 0:
return 1 if n % cur_denom == 0 else 0
for k in range(n // cur_denom + 1):
n_ways += get_ways_recursive(n - k * cur_denom,
cur_idx - 1)
return n_ways
return get_ways_recursive(n, len(c) - 1)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
m = int(first_multiple_input[1])
c = list(map(int, input().rstrip().split()))
# Print the number of ways of making change for 'n' units using coins having the values given by 'c'
ways = getWays(n, c)
fptr.write(str(ways) + '\n')
fptr.close()
It timed out on the following test example
166 23 # 23 is the number of coins below.
5 37 8 39 33 17 22 32 13 7 10 35 40 2 43 49 46 19 41 1 12 11 28

print results to text file in tabular form

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!

To Print each stage of Bubble sort in Python3.6

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=" ")

Python3 Extracting lines between first instance of two markers

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.

Why does this program for creating 10 random coordinates that don't repeat not work?

I am creating a minesweeper program for school. Part of this is randomly assigning coordinates for 10 bombs. These will be placed in a 9x9 square. I don't want the bomb coordinates to repeat. Then I remove the coordinates of the bomb from the list buttonNames. I added print statements to try to figure out why this code didn't work.
This is my code:
for i in range(11):
Bombx = randrange(1,10)
Bomby = randrange(1,10)
newBomb = (Bombx,Bomby)
self.BombList.append(newBomb)
sumValues = []
for (x,y) in self.BombList:
value = x+y
print(x,y)
sumValues.append(value)
for value in sumValues:
count = sumValues.count(value)
while count != 1:
Bombx = randrange(1,10)
Bomby = randrange(1,10)
newBomb = (Bombx,Bomby)
oldBomb = (x, y)
print(oldBomb)
self.BombList.remove(oldBomb)
self.BombList.append(newBomb)
count = 1
self.buttonNames.remove(newBomb)
And it outputs this:
3 4
3 4
6 8
3 4
6 8
4 4
3 4
6 8
4 4
5 4
3 4
6 8
4 4
5 4
9 2
3 4
6 8
4 4
5 4
9 2
4 2
3 4
6 8
4 4
5 4
9 2
4 2
6 1
(6, 1)
(6, 1)
Traceback (most recent call last):
File "/Users/gould942/Documents/Intro Comp Sci/Minesweeper.py", line 222, in <module>
main()
File "/Users/gould942/Documents/Intro Comp Sci/Minesweeper.py", line 219, in main
gameBoard = Sweeper(win)
File "/Users/gould942/Documents/Intro Comp Sci/Minesweeper.py", line 98, in __init__
self.BombList.remove(oldBomb)
ValueError: list.remove(x): x not in list
Any help is appreciated.
I'd ordinarily prefer to try to help you work out why your code is doing what it's doing, but to be honest I'm having a hard time trying to follow the logic. Instead I'll say that since there are only 9x9=81 options to choose from, the simple solution is to generate a sequence of all possible options and use random.sample():
self.BombList = []
for x in range(1, 10):
for y in range(1, 10):
self.BombList.append((x, y))
self.BombList = random.sample(self.BombList, 9)
If you're familiar with list comprehensions, the whole thing can be done in one line:
self.BombList = random.sample([(x, y) for x in range(1, 10) for y in range(1, 10)], 9)

Resources