Related
I am trying to convert arrays that contain both Inches and Feet into Inches. The feet are denoted with a single quote (') and inches are denoted with double quotes ("). The data comes in the following forms:
[8'x10']
[60\" x 72\"]
[5'x8',5x8,60\"x92\"]
[8'10\"x12']
What I want:
["96x120"]
["60x72"]
["60x96","60x96","60x96","60x92"]
["106x144"]
What I have:
def ft_inch(numbers):
if str(numbers).find("x") > -1:
numbers=numbers.replace('[','').replace('"','').replace('[','').replace(']','')
try:
nom = numbers.split("x")[0]
nom=nom.replace(r'\\|\"|\]|\[','')
nom_one = nom.split("'")[0]
nom_two = nom.split("'")[1]
den = numbers.split("x")[1]
den=den.replace(r'\\|\"|\[|\]','')
den_one = den.split("'")[0]
den_two = den.split("'")[1]
ft=int(nom_one)*12
inch=nom_two.replace(r'\"| |\\','')
try:
inch=int(inch)
except:
print('B')
tmp = int(ft)+int(inch)
fts=int(den_one)*12
inchs=den_two.replace(r'\"| |\\','')
try:
inchs=int(inchs)
except:
print('B')
tmp_two = int(fts)+int(inch)
return f'["{tmp}x{tmp_two}"]'
except:
return numbers
else:
return numbers
x="[5'1x8'1]"
ft_inch(x)
This works for a single array as long as it has both feet and inches but fails if its only feet [8'x8']. If anyone has a simpler solution please let me know
A regex-based approach:
import re
inputs = [["8'1x10'1"], ["60\" x 72\""], ["5'x8'", "5x8", "60\"x92\""], ["8'10\"x12'"]]
for inpt in inputs:
sub_output = []
for measurement in inpt:
m = re.match(r"(\d+['\"]?)(\d+['\"]?)?x(\d+['\"]?)(\d+['\"]?)?",
"".join(measurement.split()))
groups = [m.groups()[:2], m.groups()[2:]]
result_inches = [0, 0]
for i, group in enumerate(groups):
for raw_val in group:
if raw_val == None:
continue
if '"' in raw_val:
result_inches[i] += int(raw_val[:-1])
elif "'" in raw_val:
result_inches[i] += int(raw_val[:-1])*12
else:
result_inches[i] += int(raw_val)*12
sub_output.append(result_inches)
print([f"{x}x{y}" for x, y in sub_output])
Output:
['108x132']
['60x72']
['60x96', '60x96', '60x92']
['106x144']
I saw your edit and included the ["8'1x10'1"] case :)
I rewrote the entire thing, but this seems to work:
input_ = ["8'x10'", "60\" x 72\"", "5'x8'","5x8","60\"x92\"", "8'10\"x12'", "8'1x10'1\""]
inches_only = []
for s in input_:
s.replace(" ", "")
sides = s.split("x")
new_sides = []
for side in sides:
inches = 0
split1 = side.split("'")
if len(split1) > 1 or (len(split1) == 1 and not side.__contains__('"')):
inches = int(split1[0]) * 12
split2 = side.split('"')
if len(split2) > 1:
inches += int(split2[0].split("'")[-1])
elif len(split2) == 1 and len(split1) > 1 and len(split1[1]) > 0:
inches += int(split1[1])
new_sides.append(str(inches) + '"')
inches_only.append("x".join(new_sides))
print(inches_only)
Output:
['96"x120"', '60"x72"', '60"x96"', '60"x96"', '60"x92"', '106"x144"', '97"x121"']
I have a list of data (extracted from a .cv) and I want to print a list of average with the inputed data in other color. I was able to do everything, but the color is messing me up.
Can an angel help me on how to put in this code?
(i just paste the final print part)
import colorama
from colorama import Fore, Back, Style
prefage = []
prefcheck = input("Choose a prefecture: ")
print("MINORITY RATIO IN DESCENDING ORDER WITH SELECTED PREFECTURE IN RED")
for pref in range(0, len(prefage)) :
print(prefage[pref][0].rjust(10), end=" ")
for minor in range(1, len(prefage[0])) :
print(prefage[pref][minor].rjust(10))
else:
print("Sorry, no prefecture with that name.")
Before this idea i was just printing the result in a very simple way:
for x in prefage:
if prefcheck in x:
print(x)
break
(removed second question)
EDIT:
the entire code is this:
import colorama
from colorama import Fore, Back, Style
table = []
f = open("population.csv", "r")
for line in f :
line = line.rstrip("\r\n")
field = line.split(",")
table.append(field) ##### field is a list
f.close()
#AVERAGE AGE MATH FOR EACH PREFECTURE
agelist = [ "Age" ]
ag = 2.5
for i in range(1, len(table[1])) :
agelist.append(ag)
ag += 5
#PRINT AVERAGE AGE LIST
prefage = []
for pref in range(1, len(table)) :
sum = 0
asum = 0
ysum = 0
for age in range(1, len(table[1])):
sum += int(table[pref][age])
asum += int(table[pref][age]) * agelist[age]
average = round(asum / sum, 1)
for age in range(1, 5):
ysum += int(table[pref][age])
yave = round(ysum*100 / sum, 1)
prefage.append([(table[pref][0]), str(yave)])
#SORT AVARAGE IN DESCENDING ORDER
n = len(prefage)
while n > 1 :
for p in range(0, n - 1) :
if prefage[p][1] < prefage[p+1][1] :
prefage[p], prefage[p+1] = prefage[p+1], prefage[p]
n = n -1
print("MINORITY RATIO IN DESCENDING ORDER:")
for pref in range(0, len(prefage)) :
print(prefage[pref][0].rjust(10), end=" ")
for avnum in range(1, len(prefage[0])) :
print(prefage[pref][avnum].rjust(10))
print()
prefcheck = input("Choose a prefecture: ")
for x in prefage:
if prefcheck in x:
print(x)
break
else:
print("Sorry, no prefecture with that name")
You can do
print(Fore.RED, x, Fore.RESET)
but it will add spaces between value and colors so better use f-string
print( f"{Fore.RED}{x}{Fore.RESET}" )
And then you can use f-string to justify: {x:>10}, {x:<10}, {x:^10}
from colorama import Fore, Back, Style
x = 10
print('|', x, '|') # without color
print('|', Fore.RED, x, Fore.RESET, '|') # with color
print( f'|{Fore.RED}{x}{Fore.RESET}|' ) # f-string
print( f'|{Fore.RED}{x:>10}{Fore.RESET}|' )
print( f'|{Fore.RED}{x:<10}{Fore.RESET}|' )
print( f'|{Fore.RED}{x:^10}{Fore.RESET}|' )
Result:
| 10 | # without colors
| 10 | # with colors
|10| # f-string with colors
| 10| # x:>10
|10 | # x:<10
| 10 | # x:^10
You can also use variable to set justify - with nested { }
max_len = 10
print( f'|{Fore.RED}{x:^{max_len}}{Fore.RESET}|' )
EDIT:
If you want bright colors then you can add Style.BRIGHT and remove it with Style.NORMAL
print( f'|{Fore.RED+Style.BRIGHT}{x:^10}{Fore.RESET+Style.NORMAL}|' )
You may also use variables
start_color = Fore.RED+Style.BRIGHT
reset_color = Fore.RESET+Style.NORMAL
print( f'|{start_color}{x:^10}{reset_color}|' )
So you can use it with if/else
if prefcheck in x:
start_color = Fore.RED+Style.BRIGHT
reset_color = Fore.RESET+Style.NORMAL
else:
start_color = ''
reset_color = ''
print( f'|{start_color}{x:^10}{reset_color}|' )
Or define shorter names
CR = Fore.RED+Style.BRIGHT # Color Red
CG = Fore.GREEN+Style.BRIGHT # Color Green
CX = Fore.RESET+Style.NORMAL # Color reset
if prefcheck in x:
start_color = CR
reset_color = CX
else:
start_color = ''
reset_color = ''
print( f'|{start_color}{x:^10}{reset_color}|' )
below is c.txt
CO11 CSE C1 8
CO12 ETC C1 8
CO13 Electrical C2 12
CO14 Mech E 5
my program needs to print a course summary on screen and save that summary into a file
named cr.txt. Given the above c.txt, your program output should look like
below. The content of course_report.txt should also be the same, except the last line. Course
names in the second column use * to indicate a compulsory course and – to indicate an elective
course. The fourth column is the number of students enrolled in that course. The fifth column is the average score of the course.
CID Name Points. Enrollment. Average.
----------------------------------
CO11 * CSE 8 2 81
CO12 * ETC 8 10 71
CO13 * Electrical 12 8 61
CO14 - Mech 5 4 51
----------------------------------
poor-performing subject is CO14 with an average 51.
cr.txt generated!
below is what I've tried:
def read(self):
ctype = []
fi = open("c.txt", "r")
l = fi.readline()
while l != "":
fields = l.strip().split(" ")
self.c.append(fields)
l = fi.readline().strip()
f.close()
# print(f"{'CID'}{'Name':>20}{'Points.':>16}{'Enrollment.':>18}{'Average.':>10}")
# print("-" * 67, end="")
print()
for i in range(0, len(self.c)):
for j in range(len(self.c[i])):
obj = self.c[i][j]
print(obj.ljust(18), end="")
print()
print("-" * 67, end="")
print()
you can try use 'file.read' or 'file.readlines' after use 'open' function, if you choose 'file.readlines' you'll have to use 'for row in file.readlines()' look my example with 'file.read':
headers = ['CID', 'Name', 'Points.', 'Enrollment.', 'Average.']
compulsory_course = ['CO11', 'CO12', 'CO13']
elective_course = ['CO14']
count = 0
with open('c.txt', 'r') as file_c:
file_c.seek(0, 0)
file_string = file_c.read().replace('\n', ' ')
fields = file_string.split(' ')
with open('cr.txt', 'w') as file_cr:
for field in headers:
file_cr.write(f'{field} ')
file_cr.write('\n')
for v in fields:
if count == 4:
file_cr.write('\n')
count = 0
count += 1
if v in compulsory_course:
file_cr.write(f'{v} * ')
continue
elif v in elective_course:
file_cr.write(f'{v} - ')
continue
elif count == 3:
file_cr.write(f' ')
continue
file_cr.write(f'{v} ')
Write a python program that will take 3 lists:
Name Wage Hours
Juan 7.50 35
Rae 11.00 41
Ivanna 18.25 26
Lilly 9.25 35
Robert 11.10 45
and use this logic:
An employee gets overtime when they have worked more than 40 hours
Overtime pay is calculated using this formula:
Gross Pay = (35*Wage) + ((Hours-35)*Wage*1.5)
Regular pay is calculated using this formula:
Gross Pay = (Hours*Wage)
Use a loop to process these lists.
Print each employee, their wages, Hours and gross pay.
I'm running this program and I have the for loop. The input works fine, but the while loop that its supposed to have the same output is not giving me any output at all. Here's my code.
`Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
for X in range(5):
GP = 0
if(Hours[X] > 40):
GP = (35*Wage[X]) + ((Hours[X]-35)*Wage[X]*1.5)
else:
GP = Hours[X] * Wage[X]
print (Name[X],"\t", Wage[X],"\t", Hours[X],"\t", GP)
Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
counter = 5
Y = 0
while (Y):
if (Hours[Y] > 40):
GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
else:
GP = Hours[Y] * Wage[Y]
print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)`
my output is going as
Name Wage Hours GP
Juan 7.5 35 262.5
Rae 11 41 484.0
Ivanna 18.25 26 474.5
Lilly 9.25 35 323.75
Robert 11.1 45 555.0
Name Wage Hours GP
Juan 7.5 35 555.0
I don't know where the error is in the while loop.
Your last line needs to be indented. So instead of
while (Y):
if (Hours[Y] > 40):
GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
else:
GP = Hours[Y] * Wage[Y]
print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)
it needs to be
while (Y):
if (Hours[Y] > 40):
GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
else:
GP = Hours[Y] * Wage[Y]
print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)
because right now the print is outside of the while loop, so it is only printing with the value Y=0.
Have to follow python code indented and need to give proper while loop condition with (increment/decrement/boolean). As your code need to increment the value of Y.
Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
for X in range(5):
GP = 0
if(Hours[X] > 40):
GP = (35*Wage[X]) + ((Hours[X]-35)*Wage[X]*1.5)
else:
GP = Hours[X] * Wage[X]
print (Name[X],"\t", Wage[X],"\t", Hours[X],"\t", GP)
Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
counter = 5
Y = 0
while (Y<counter):
if (Hours[Y] > 40):
GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
else:
GP = Hours[Y] * Wage[Y]
print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)
Y=Y+1
I wanna read a binary file (K7120127.SRS) with caractristhics detailed in the word file (Documentacion SRS DATA.doc) ,2.2. chapter, that adding in the next link
https://drive.google.com/folderview?id=0B_NlxFaQkpgHb00yTm5kU0MyaUU&usp=sharing
In the link is included a viewer of that data (Srsdisp.exe), but i wanna process this data not only view it, that's why I'd want to read it in Python.
I know plot using matplotlib, but work with binary files is new for me. I 'd wanna plot something like this (That plot was made using the viewer included in the link)
Try that.
from struct import unpack
# constants from the file spec
RECORD_SIZE=826
RECORD_HEADER_SIZE=24
RECORD_ARRAY_SIZE=401
# verbosity values
VERBOSITY_ALL = 2 # print warnings and errors
VERBOSITY_ERRORS = 1 # print errors
VERBOSITY_NONE = 0 # print nothing
class SRSRecord:
"""Holds one 826 byte SRS Record."""
_site_to_name = {
1: "Palehua",
2: "Holloman",
3: "Learmonth",
4: "San Vito",
# add new site names here ..
}
def __init__(self):
self.year = None
self.month = None
self.day = None
self.hour = None
self.minute = None
self.seconds = None
self.site_number = None
self.site_name = None
self.n_bands_per_record = None
self.a_start_freq = None
self.a_end_freq = None
self.a_num_bytes = None
self.a_analyser_reference_level = None
self.a_analyser_attenuation = None
self.b_start_freq = None
self.b_end_freq = None
self.b_num_bytes = None
self.b_analyser_reference_level = None
self.b_analyser_attenuation = None
# dictionary that maps frequency in mega hertz to level
self.a_values = {}
# dictionary that maps frequency in mega hertz to level
self.b_values = {}
return
def _parse_srs_file_header(self, header_bytes, verbosity = VERBOSITY_ALL):
fields = unpack(
# General header information
'>' # (data packed in big endian format)
'B' # 1 Year (last 2 digits) Byte integer (unsigned)
'B' # 2 Month number (1 to 12) "
'B' # 3 Day (1 to 31) "
'B' # 4 Hour (0 to 23 UT) "
'B' # 5 Minute (0 to 59) "
'B' # 6 Second at start of scan (0 to 59) "
'B' # 7 Site Number (0 to 255) "
'B' # 8 Number of bands in the record (2) "
# Band 1 (A-band) header information
'h' # 9,10 Start Frequency (MHz) Word integer (16 bits)
'H' # 11,12 End Frequency (MHz) "
'H' # 13,14 Number of bytes in data record (401) "
'B' # 15 Analyser reference level Byte integer
'B' # 16 Analyser attenuation (dB) "
# Band 2 (B-band) header information
# 17-24 As for band 1
'H' # 17,18 Start Frequency (MHz) Word integer (16 bits)
'H' # 19,20 End Frequency (MHz) "
'H' # 21,22 Number of bytes in data record (401) "
'B' # 23 Analyser reference level Byte integer
'B', # 24 Analyser attenuation (dB) "
header_bytes)
self.year = fields[0]
self.month = fields[1]
self.day = fields[2]
self.hour = fields[3]
self.minute = fields[4]
self.seconds = fields[5]
# read the site number and work out the site name
self.site_number = fields[6]
if self.site_number not in SRSRecord._site_to_name.keys():
# got an unknown site number.. complain a bit..
if verbosity >= VERBOSITY_ALL:
print("Unknown site number: %s" % self.site_number)
print("A list of known site numbers follows:")
for site_number, site_name in SRSRecord._site_to_name.items():
print("\t%s: %s" % (site_number, site_name))
# then set the site name to unknown.
self.site_name = "UnknownSite"
else:
# otherwise look up the site using our lookup table
self.site_name = SRSRecord._site_to_name[self.site_number]
# read the number of bands
self.n_bands_per_record = fields[7] # should be 2
if self.n_bands_per_record != 2 and verbosity >= VERBOSITY_ERRORS:
print("Warning.. record has %s bands, expecting 2!" % self.n_bands_per_record)
# read the a record meta data
self.a_start_freq = fields[8]
self.a_end_freq = fields[9]
self.a_num_bytes = fields[10]
if self.a_num_bytes != 401 and verbosity >= VERBOSITY_ERRORS:
print("Warning.. record has %s bytes in the a array, expecting 401!" %
self.a_num_bytes)
self.a_analyser_reference_level = fields[11]
self.a_analyser_attenuation = fields[12]
# read the b record meta data
self.b_start_freq = fields[13]
self.b_end_freq = fields[14]
self.b_num_bytes = fields[15]
if self.b_num_bytes != 401 and verbosity >= VERBOSITY_ERRORS:
print("Warning.. record has %s bytes in the b array, expecting 401!" %
self.b_num_bytes)
self.b_analyser_reference_level = fields[16]
self.b_analyser_attenuation = fields[17]
return
def _parse_srs_a_levels(self, a_bytes):
# unpack the frequency/levels from the first array
for i in range(401):
# freq equation from the srs file format spec
freq_a = 25 + 50 * i / 400.0
level_a = unpack('>B', a_bytes[i])[0]
self.a_values[freq_a] = level_a
return
def _parse_srs_b_levels(self, b_bytes):
for i in range(401):
# freq equation from the srs file format spec
freq_b = 75 + 105 * i / 400.0
level_b = unpack('>B', b_bytes[i])[0]
self.b_values[freq_b] = level_b
return
def __str__(self):
return ("%s/%s/%s, %s:%s:%s site: %s/%s bands: %s "
"[A %s->%s MHz ref_level: %s atten: %s dB], "
"[B %s->%s MHz ref_level: %s atten: %s dB]"
)% (
self.day, self.month, self.year,
self.hour, self.minute, self.seconds,
self.site_number, self.site_name,
self.n_bands_per_record,
self.a_start_freq, self.a_end_freq,
self.a_analyser_reference_level, self.a_analyser_attenuation,
self.b_start_freq, self.b_end_freq,
self.b_analyser_reference_level, self.b_analyser_attenuation,
)
def _dump(self, values):
freqs = values.keys()
freqs.sort()
for freq in freqs:
print "%5s %s" % (freq, values[freq])
return
def dump_a(self):
self._dump(self.a_values)
return
def dump_b(self):
self._dump(self.b_values)
return
def read_srs_file(fname):
"""Parses an srs file and returns a list of SRSRecords."""
# keep the records we read in here
srs_records = []
f = open(fname, "rb")
while True:
# read raw record data
record_data = f.read(RECORD_SIZE)
# if the length of the record data is zero we've reached the end of the data
if len(record_data) == 0:
break
# break up the record bytes into header, array a and array b bytes
header_bytes = record_data[:RECORD_HEADER_SIZE]
a_bytes = record_data[RECORD_HEADER_SIZE : RECORD_HEADER_SIZE + RECORD_ARRAY_SIZE]
b_bytes = record_data[RECORD_HEADER_SIZE + RECORD_ARRAY_SIZE :
RECORD_HEADER_SIZE + 2 * RECORD_ARRAY_SIZE]
# make a new srs record
record = SRSRecord()
record._parse_srs_file_header(header_bytes, verbosity = VERBOSITY_ERRORS)
record._parse_srs_a_levels(a_bytes)
record._parse_srs_b_levels(b_bytes)
srs_records.append(record)
return srs_records
if __name__ == "__main__":
# parse the file.. (this is where the magic happens ;)
srs_records = read_srs_file(fname = "K7120127.SRS")
# play with the data
for i in range(3):
print srs_records[i]
r0 = srs_records[0]
r0.dump_a()
r0.dump_b()