I have a list of dictionaries which is coming from Django query set.
Like this:
email_sent_count = [
{
'second_follow_count': 1,
'first_follow_count': 1,
'initial_count': 1,
'third_follow_count': 0
},
{
'second_follow_count': 1,
'first_follow_count': 0,
'initial_count': 1,
'third_follow_count': 1
},
{
'second_follow_count': 1,
'first_follow_count': 1,
'initial_count': 1,
'third_follow_count': 1
}
]
Now, I want the sum of each key separately.
like this:
inital_contact = 3
first_followup = 2
second_followup = 3
third_followup = 2
I am trying the following solution:
initial_contact = sum(map(lambda x: x['initial_count'], email_sent_count))
first_followup = sum(map(lambda x: x['first_follow_count'], email_sent_count))
second_followup = sum(map(lambda x: x['second_follow_count'], email_sent_count))
third_followup = sum(map(lambda x: x['third_follow_count'], email_sent_count))
But now, I'm getting 11 keys in all dictionaries and I'm implementing 11 lambda function so is there any good way to solve this issue rather than calling 11 times lambda function
By following ORM I getting above email_sent_count
i = Q(inital_contact__range=(from_date, to_date))
f1 = Q(first_followup__range=(from_date, to_date))
f2 = Q(second_followup__range=(from_date, to_date))
f3 = Q(third_followup__range=(from_date, to_date))
email_count = campaign_contact.filter(i | f1 | f2 | f3).annotate(initial_count=Count('inital_contact'),
first_follow_count=Count('first_followup'),
second_follow_count=Count('second_followup'),
third_follow_count=Count('third_followup'),
).values('initial_count', 'first_follow_count',
'second_follow_count', 'third_follow_count'
So, is there is a solution which is directly working with ORM ?
if you don't mind getting a dictionary as result you could use collections.defaultdict like this:
from collections import defaultdict
sums = defaultdict(int)
for item in email_sent_count:
for key, value in item.items():
sums[key] += value
which results in
defaultdict(<class 'int'>,
{'second_follow_count': 3, 'initial_count': 3,
'first_follow_count': 2, 'third_follow_count': 2})
and you can access the individual sums just like a dictionary: sums['second_follow_count'].
...or maybe even better with collections.Counter:
from collections import Counter
sums = Counter()
for item in email_sent_count:
for key, value in item.items():
sums[key] += value
# Counter({'second_follow_count': 3, 'initial_count': 3,
# 'first_follow_count': 2, 'third_follow_count': 2})
Or if you prefer do do it yourself without using Counter or DefaultDict:
from pprint import pprint
email_sent_count = [
{
'second_follow_count': 1,
'first_follow_count': 1,
'initial_count': 1,
'third_follow_count': 0
},
{
'second_follow_count': 1,
'first_follow_count': 0,
'initial_count': 1,
'third_follow_count': 1
},
{
'second_follow_count': 1,
'first_follow_count': 1,
'initial_count': 1,
'third_follow_count': 1
}
]
# create empty dict with all keys from any inner dict and initialized to 0
alls = dict( (x,0) for y in email_sent_count for x in y)
pprint(alls)
for d in email_sent_count:
for k in d:
alls[k] += d[k]
pprint(alls)
Output:
{'first_follow_count': 0,
'initial_count': 0,
'second_follow_count': 0,
'third_follow_count': 0}
{'first_follow_count': 2,
'initial_count': 3,
'second_follow_count': 3,
'third_follow_count': 2}
Finally, I changed the ORM query that gets me the exact result:
ORM looks like this:
email_sent_count = campaign_contact.filter(i | f1 | f2 | f3
).annotate(initial_count=Count('inital_contact'),
first_follow_count=Count('first_followup'),
second_follow_count=Count('second_followup'),
third_follow_count=Count('third_followup')
).aggregate(initial_sum=Sum('initial_count'),
first_follow_sum=Sum('first_follow_count'),
second_follow_sum=Sum('second_follow_count'),
third_follow_sum=Sum('third_follow_count'))
output...
{'third_follow_sum': 2, 'second_follow_sum': 3, 'first_follow_sum': 2, 'initial_sum': 3}
So, there is not for loops, no lambda... I think performance wise it will work.
And Thanks to all to provide me the solutions, by looking other solution I'm able to solve this. :)
How can i get the Current Quarter year and then First Date and last Date of Current Quarter Year in Python?
i want by importing datetime
import datetime
People look into Stack overflow need straight forward answer and which should be very simple. Which ever link you provided it having lot of Comments. SO, users has to go through all the comments to find correct answer. I am writing simple and straight forward answer.
I believe that none of the current answers are still valid in Python 3, so since this is the top hit in google for first and last day of quarter, I will provide a solution that works in Python 3 (mostly Ahmet's with // instead of /):
from datetime import date as date_class
from datetime import timedelta, datetime
def get_quarter(p_date: date_class) -> int:
return (p_date.month - 1) // 3 + 1
def get_first_day_of_the_quarter(p_date: date_class):
return datetime(p_date.year, 3 * ((p_date.month - 1) // 3) + 1, 1)
def get_last_day_of_the_quarter(p_date: date_class):
quarter = get_quarter(p_date)
return datetime(p_date.year + 3 * quarter // 12, 3 * quarter % 12 + 1, 1) + timedelta(days=-1)
assert get_quarter(datetime(year=2021, month=10, day=5).date()) == 4
assert get_quarter(datetime(year=2020, month=9, day=25).date()) == 3
assert get_quarter(datetime(year=2020, month=12, day=11).date()) == 4
assert get_quarter(datetime(year=2020, month=1, day=2).date()) == 1
assert get_first_day_of_the_quarter(datetime(2020, 10, 5).date()) == datetime(2020, 10, 1)
assert get_first_day_of_the_quarter(datetime(2020, 9, 25).date()) == datetime(2020, 7, 1)
assert get_first_day_of_the_quarter(datetime(2020, 12, 11).date()) == datetime(2020, 10, 1)
assert get_first_day_of_the_quarter(datetime(2020, 1, 2).date()) == datetime(2020, 1, 1)
assert get_last_day_of_the_quarter(datetime(2020, 10, 5).date()) == datetime(2020, 12, 31)
assert get_last_day_of_the_quarter(datetime(2020, 9, 25).date()) == datetime(2020, 9, 30)
assert get_last_day_of_the_quarter(datetime(2020, 12, 11).date()) == datetime(2020, 12, 31)
assert get_last_day_of_the_quarter(datetime(2020, 1, 2).date()) == datetime(2020, 3, 31)
assert get_last_day_of_the_quarter(datetime(2020, 5, 6).date()) == datetime(2020, 6, 30)
Having the first day is the same with #Karishh's solution. But, for the last date, Python2.7 causes a problem for fourth quarter. Because 12+1=13 and datetime does not accept 13 as a month. So you need to do some tricks to handle it.
import datetime
def get_quarter(date):
return (date.month - 1) / 3 + 1
def get_first_day_of_the_quarter(date):
quarter = get_quarter(date)
return datetime.datetime(date.year, 3 * quarter - 2, 1)
def get_last_day_of_the_quarter(date):
quarter = get_quarter(date)
month = 3 * quarter
remaining = month / 12
return datetime.datetime(date.year + remaining, month % 12 + 1, 1) + datetime.timedelta(days=-1)
Any how i found some simple solution in c# and converted it into python,
from datetime import datetime,timedelta
current_date=datetime.now()
currQuarter = (current_date.month - 1) / 3 + 1
dtFirstDay = datetime(current_date.year, 3 * currQuarter - 2, 1)
dtLastDay = datetime(current_date.year, 3 * currQuarter + 1, 1) + timedelta(days=-1)
Here's a one/two liner to get the start/end date of the current quarter.
from datetime import datetime
import math
from dateutil.relativedelta import relativedelta # requires python-dateutil
start_of_quarter = datetime(year=datetime.now().year, month=((math.floor(((datetime.now().month - 1) / 3) + 1) - 1) * 3) + 1, day=1)
end_of_quarter = start_of_quarter + relativedelta(months=3, seconds=-1)
pendulum has a much more intuitive implementation.
import pendulum
dt = pendulum.datetime(2021, 3, 23)
print(dt.first_of('quarter'))
print(dt.last_of('quarter'))
2021-01-01T00:00:00+00:00
2021-03-31T00:00:00+00:00
Building off of the answer from Krishh, but addressing several issues found:
calculating last day in Quarter 4
Wasae Shoaib's comment about raising a ValueError
TypeError with a float being passed instead of an integer
Using relativedeta instead and shifting the correctly calculated start date by three months, we end up with a much more reliable way to get at the quarter end date.
from datetime import datetime
from dateutil.relativedelta import relativedelta
current_date = datetime.now()
currQuarter = int((current_date.month - 1) / 3 + 1)
dtFirstDay = datetime(current_date.year, 3 * currQuarter - 2, 1)
dtLastDay = dtFirstDay + relativedelta(months=3, days=-1)
I did of a lot of tests to find the solution that fit my need and I will be happy if it helps someone else :
datval = fields.date.today()
if datval.month < 4 :
self.start_date = fields.date.today().replace(month=10, day=1)
self.end_date = fields.date.today().replace(month=12, day=31)
elif datval.month < 7 :
self.start_date = fields.date.today().replace(month=1, day=1)
self.end_date = fields.date.today().replace(month=3, day=31)
elif datval.month < 10 :
self.start_date = fields.date.today().replace(month=4, day=1)
self.end_date = fields.date.today().replace(month=6, day=30)
else :
self.start_date = fields.date.today().replace(month=7, day=1)
self.end_date = fields.date.today().replace(month=9, day=30)
Get start and end points for: week, month, quarter and year
https://gist.github.com/dejurin/236b398dc4b8064685702a27a3df612b
from datetime import date
from dateutil.relativedelta import relativedelta
def start_end_day(sunmon: bool = True):
today = date.today()
curr_quarter = int((today.month - 1) / 3 + 1)
dayofweek = [today.weekday(),today.isoweekday()][sunmon]
week_start = today - relativedelta(days=dayofweek)
week_end = week_start + relativedelta(days=6)
month_start = date(today.year,today.month, 1)
month_end = month_start + relativedelta(months=1, days=-1)
quarter_start = date(today.year, 3 * curr_quarter - 2, 1)
quarter_end = quarter_start + relativedelta(months=3, days=-1)
year_start = date(today.year, 1, 1)
year_end = year_start + relativedelta(years=1, days=-1)
return ((week_start,week_end),(month_start,month_end),(quarter_start,quarter_end),(year_start,year_end))
"""
Current date: 18/02/2022
"""
"""
((datetime.date(2022, 2, 13), datetime.date(2022, 2, 19)),
(datetime.date(2022, 2, 1), datetime.date(2022, 2, 28)),
(datetime.datetime(2022, 1, 1, 0, 0), datetime.datetime(2022, 3, 31, 0, 0))
(datetime.date(2022, 1, 1), datetime.date(2022, 12, 31)))
"""
I'm trying to import a number of text files into Excel using the VBA code below. Whilst the code produces a list of the Transaction Sales Numbers with corresponding date for each file imported, I can't work out how to get the associated Transaction Sales Numbers into seperate columns in each imported file row. I have tried RegEx but struggled with the differing formats of the Sales Numbers (an example of each is in the sample file)... Can anyone help?
Many thanks in advance
Sample text file:
This is sales enquiry response for SER:SS09458GQPBXX201503191300WWPL0933 *********************************************************** Sales record match For SER:SS09458GQPBXX201503191300WWPL0933 **********************Original File********************** File Data Source POS Type of Transaction EFT Date Mar 19 2015 12:00PM Transaction Sales Number LLRUMOLN120150319FLRPLIS08783 Product Name HAIRDRYER ***************Sales File # 1*************** File Data Source POS Type of Transaction EFT Date Apr 23 2015 12:00PM Transaction Sales Number PLVOLMJBD0960807420300 Product Name HAIRDRYER ***************Sales File # 2*************** File Data Source POS Type of Transaction EFT Date May 28 2015 12:00PM Transaction Sales Number 781266HO3 Product Name HAIRDRYER ***************Sales File # 3*************** File Data Source POS Type of Transaction EFT Date May 10 2015 12:00PM Transaction Sales Number CVFORM05061126581000433 Product Name HAIRDRYER ***************Sales File # 4*************** File Data Source POS Type of Transaction EFT Date Jun 28 2015 12:07PM Transaction Sales Number LLB01L32330772427059291FOLM400P00295 Product Name HAIRDRYER
Option Explicit
Sub Sales_File_Extractor()
Dim fName As String, fPath As String, fPathDone As String
Dim LR As Long, NR As Long
Dim wbData As Workbook, wsMaster As Worksheet
Dim TSN_Start As String, TSN_End As String
Dim Date_Start As String, Date_End As String
Dim textline As String, text As String
'Setup
Application.ScreenUpdating = False 'speed up macro execution
Application.EnableEvents = False 'turn off other macros for now
Application.DisplayAlerts = False 'turn off system messages for now
Set wsMaster = ThisWorkbook.Sheets("SALES") 'sheet report is built into
With wsMaster
NR = .Range("A" & .Rows.Count).End(xlUp).Row + 1 'appends data to existing data
'Path and filename (edit this section to suit)
fPath = "C:\Users\burnsr\desktop\sales"
fPathDone = fPath & "Imported\" 'remember final \ in this string
On Error Resume Next
MkDir fPathDone 'creates the completed folder if missing
On Error GoTo 0
fName = Dir(fPath & "*.txt*") 'listing of desired files, edit filter as desired
Do While Len(fName) > 0
Open (fPath & fName) For Input As #1
Do Until EOF(1)
Line Input #1, textline
text = text & textline 'second loop text is already stored -> see reset text
Loop
Close #1
On Error Resume Next
.Cells(NR, "A").Value = fName
Date_Start = InStr(text, "Date ") 'position of start delimiter
Date_End = InStr(text, "Transaction Sales Number") 'position of end delimiter
.Cells(NR, "C").Value = Mid(text, Date_Start + 34, Date_End - Date_Start - 34) 'position number is length of start string
TSN_Start = InStr(text, "Transaction Sales Number ") 'position of start delimiter
TSN_End = InStr(text, "Product Name") 'position of end delimiter
.Cells(NR, "B").Value = Mid(text, TSN_Start + 34, TSN_End - TSN_Start - 34) 'position number is length of start string
'How to get all other successive values in columns?
text = "" 'reset text
Close #1 'close file
NR = .Range("A" & .Rows.Count).End(xlUp).Row + 1 'next row
Name fPath & fName As fPathDone & fName 'move file to IMPORTED folder
fName = Dir 'ready next filename
Loop
End With
ErrorExit: 'Cleanup
Application.DisplayAlerts = True 'turn system alerts back on
Application.EnableEvents = True 'turn other macros back on
Application.ScreenUpdating = True 'refreshes the screen
MsgBox "Import completed"
Rabbie, I have an XLSM file that reads 6 CSV files and adds 6 sheets to inside itself. Text are TAB delimited.
UTF-8 CSV Headers Example:
Customer Number Customer description Cust. Name-Lang 2 Status Phone Number Fax Number E-mail Address Type of Business Cust. Group Code
VBA:
Function IsOpen(File$) As Boolean
Dim FN%
FN = FreeFile
On Error Resume Next
Open File For Random Access Read Write Lock Read Write As #FN
Close #FN
IsOpen = Err
End Function
Public Sub Load_Data()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
allName = Worksheets("START").Cells(6, "B").Value
tmpltName = Worksheets("START").Cells(4, "B").Value
savePath = Worksheets("START").Cells(3, "B").Value
Set currBook = ActiveWorkbook
Set prevsheet = ActiveSheet
'Load all ZOOM files
i = 2
For Each n In Worksheets("START").Range("E2:E8")
On Error Resume Next
currBook.Sheets(n.Text).Select
If Not Err Then
Err.Clear
currBook.Worksheets(n.Text).Delete
End If
Sheets.Add(Before:=Sheets("START")).Name = n.Text
' Checking if file is opened
If Not IsOpen(Worksheets("START").Cells(i, "F").Value) Then
' Loadd CSV file
LoadCSV Worksheets("START").Cells(i, "F").Value, n.Text
End If
' List of combining fields
' Find column with combining field
With Worksheets(n.Text).Columns("A:DZ")
Set result = .Find(What:=Worksheets("START").Cells(i, "G").Value, LookIn:=xlValues)
If result Then
combFields.Add result.Address, n.Text
End If
End With
i = i + 1
Next n
' Find column with combining field in Peoples
combFieldPeople = combFields.Item("peoples")
' Find column with combining field in Companies
combFieldCompany = combFields.Item("companies")
' Find company names field in "companies"
With Worksheets("companies").Columns("A:DZ")
Set result = .Find(What:=Worksheets("START").Cells(3, "I").Value, LookIn:=xlValues)
If result Then
companyNameField = result.Address
End If
End With
' Find column with "CopyToExcel" checkbox for Peolles
With Worksheets("peoples").Columns("A:DZ")
Set result = .Find(What:=Worksheets("START").Cells(2, "H").Value, LookIn:=xlValues)
If result Then
copyUserField = result.Address
End If
End With
' Find column with "CopyToExcel" checkbox for "Companies"
With Worksheets("companies").Columns("A:DZ")
Set result = .Find(What:=Worksheets("START").Cells(3, "H").Value, LookIn:=xlValues)
If result Then
copyField = result.Address
End If
End With
' Remove unnecessary organizations
startBook.Activate
With Worksheets("companies")
.Activate
.AutoFilterMode = False
fldNum = .Range(copyField).Column
.UsedRange.AutoFilter Field:=fldNum, Criteria1:="Y"
ActiveCell.CurrentRegion.Select ' copy unique values
nRow = Selection.Rows.Count
Selection.Copy
'.UsedRange.AutoFilter
Worksheets.Add.Name = "tmp1"
ActiveSheet.Range("A1").Select
ActiveSheet.Paste
Worksheets("companies").Delete
Worksheets("tmp1").Name = "companies"
End With
Worksheets("START").Activate
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Function LoadCSV(fName As String, shName As String)
ActiveWorkbook.Worksheets(shName).Activate
iPath = ThisWorkbook.Path
fullFileName = iPath & "\" & fName
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" + fullFileName, Destination:=Range("$A$1"))
'.CommandType = 0
.Name = fullFileName
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 65001
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
'.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 _
' , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
' 1, 1, 1, 1, 1)
.TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Function
It works fine with Hebrew and Zoom/Priority. MS Office 2010/2013/2016(32/64)
I need help with a function that can return words that have 3 or more characters that are "evenly" spaced, that is the ord() value for consecutive letters left to right are even (same difference value). This is what I have so far... and the output is this:
test_list2 = ['i', 'made', 'an', 'ace', 'today', 'at', 'tennis...yeaah', 'booi', ':d']
for word in test_list2:
if len(word) >=3:
temp_list = []
for chr1 in word:
if word.index(chr1) != (len(word)-1):
chr2 = word.index(chr1)+1
num = ord(word[chr2]) - ord(chr1)
temp_list.append(num)
temp_tup = (word, temp_list)
final_list.append(temp_tup)
final_list = [('made', [-12, 3, 1]), ('ace', [2, 2]), ('today', [-5, -11, -3, 24]),
('tennis...yeaah', [-15, 9, 0, 0, 10, -69, 0, 0, 0, -20, 9, 0, 0]),
('booi', [13, 0, 0])]
But i need to return only the ones that are evenly spaced ('ace'). The output should be like this,
[('ace',2)]
Assuming that you do not need the final_list with non evenly spaced numbers, then you can keep track of the num to see if it stays the same throughout the word. If you find a different num stop and go to the next word. If num stays the same then add a (word, num) tuple to the final_list:
for word in test_list2:
if len(word) >=3:
all_nums_are_same = True
prev_num = None
for chr1 in word:
if word.index(chr1) != (len(word)-1):
chr2 = word.index(chr1)+1
num = ord(word[chr2]) - ord(chr1)
if not prev_num:
prev_num = num
elif prev_num != num:
# different number is found, we can
# stop and move on to next word
all_nums_are_same = False
break
if all_nums_are_same:
# only add tuple if all numbers we the same
temp_tup = (word, prev_num)
final_list.append(temp_tup)
This yields [('ace',2)] as a result.
I banged this out in Python 3.3, compiles and works on my machine :)
There's a bunch of extra debugging junk in there like print statements, if you want to test it with some more complicated data (example: long blocks of text) for bugs.
I made use of enumerate(), rather than your word.index, not sure which is more pythonic?
import sys
### Define variables
test_list = ['i', 'made', 'an', 'ace', 'today', 'at', 'tennis...yeaah', 'booi', ':d']
proc_check = [('made', [-12, 3, 1]),
('ace', [2, 2]),
('today', [-5, -11, -3, 24]),
('tennis...yeaah', [-15, 9, 0, 0, 10, -69, 0, 0, 0, -20, 9, 0, 0]),
('booi', [13, 0, 0])]
final_check = [('ace', [2,2])]
test_list2 = ['ace', 'ace', 'ace']
proc_check2 = [('ace', [2, 2]),
('poo', [3, 3]),
('ace', [2, 2])]
final_check2 = [('ace', [2,2]),('poo', [2,2]),('ace', [2,2])]
### Function definitions
def wordIsEven(word_list, proc_list_check):
final_list = []
procd_list = []
for word in word_list:
temp_list = []
if len(word) >= 3:
for chr1 in word:
if word.index(chr1) != (len(word)-1):
chr2 = word.index(chr1)+1
num = ord(word[chr2]) - ord(chr1)
temp_list.append(num)
temp_tup = (word, temp_list)
procd_list.append(temp_tup)
errors = False
for i, check in enumerate(procd_list):
if check != proc_list_check[i]:
errors = True
print("Word Eval Fail! " + str(check) + " != " + str(proc_list_check[i]))
if errors == True:
print("List compare failed!" )
else:
print("Lists compare equally!")
for tmp_tup in procd_list:
print("Examining Slice: "+str(tmp_tup[1]))
for i, num in enumerate(tmp_tup[1]):
if i + 1 < len(tmp_tup[1]):
num2 = tmp_tup[1][i+1]
if num == num2:
if num != 0:
print("Got one! " + str(tmp_tup))
final_list.append(tmp_tup)
return final_list
### Code execution
my_list = wordIsEven(test_list2, proc_check2)
my_check = final_check2
print("Printing Final list:")
for i, item in enumerate(my_list):
tempStr = str(item)
if item != my_check[i]:
tempStr += " doesn't match check data..." + str(my_check[i])
print(tempStr)
sys.exit()