print results to text file in tabular form - python-3.x

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!

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

Displaying element in my text file when it is lesser than the range?

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])

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 is python giving me a Syntax error?

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

Resources