Issues calling values above each other in a matrix, python - python

This is my first post so let me know if I need to change anything!
I've created a grid based on the following input:
1;2;12;12;12
11;12;2;12;12
1;2;12;2;12
11;12;2;1;2
To create this grid I used this piece of code:
node = hou.pwd()
geo = node.geometry()
text = node.evalParm('text')
lines = text.splitlines()
numbers = [map(int, line.split(';') ) for line in lines]
geo.addAttrib(hou.attribType.Point, 'instance', -1)
for row, n in enumerate(numbers):
for col, value in enumerate(n):
pos = (col, 0.0, row)
pt_add = geo.createPoint()
pt_add.setAttribValue('instance', value)
pt_add.setPosition(pos)
This works great and creates the grid with points spaced 1 apart and with the correct value.
Now I want to do the following:
if value != 0:
a = #Value of current index
b = #Value of index above
if len(a) < len(b):
if a[-len(a)] == b[-len(a)]:
a = '0'
b = b
else:
pass
else:
if len(a)== len(b):
if len(a) < 2:
pass
else:
a = '0'
b = b + 'x'
else:
if a[-len(a)] == b[-len(a)]:
b = a + 'y'
a = '0'
else:
pass
Now I'm assuming I need to go over the rows and columns again but if I do that with a for loop then it won't allow me to call the value of the index above in that column. Could someone help me figure this out? And I'll need to change the value of "instance" to the new value.
As a brief explanation of what I'm trying to achieve:
Example image
Edit: Adding something other than x or y to the int to differentiate between a "11" with 1 changed to "0" under it and an "11" with 2 or 3 changed to "0" under them.

Related

Given a string move to index of desired characters

With reference to single-row-keyboard.
The problem says:
Given a string keyboard of length 26 indicating the layout of the
keyboard (indexed from 0 to 25), initially your finger is at index 0.
To type a character, you have to move your finger to the index of the
desired character. The time taken to move your finger from index i to
index j is |i - j|.
Input: keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba"
Output: 4
Explanation: The index moves from 0 to 2 to write 'c' then to 1 to write 'b' then to 0 again to write 'a'.
Total time = 2 + 1 + 1 = 4.
This is a fairly simple problem which should not take much time. So I attempted the below solution for it.
def key_front(num, k, word, keyboard):
for x in range(k):
if word[num] == keyboard[x]:
return x
return 0
def calculateTime(keyboard, word):
k = len(keyboard)
count = 0
i = 0
w = len(word)
diff = 0
while i < w:
front = 0
front = key_front(i, k, word, keyboard)
print(front,diff,word[i],count)
if word[i] == word[i-1]:
diff = 0
diff = abs(front-diff)
count += diff
i = i + 1
return count
The point that I am using recusrion here is because there might be a case where each chareacter can appear multiple times in sequential order always.
My code fails for the below test case when such scenario occurs:
keyboard="pyevcountbgjklxfqwimrdhazs"
word="gxafwhexxykisciactyfdyfixqfchwanvmsjwycyyznpkykfkgfwpaajiqftklahgergnyxunfbmvkiyrifljolkkvcmdsimnmmdulqpirbdkhalakgsgomlnxivjqgbamnylecwmnulldjueppxptrjbyrijrqvagqklnglegiqoumqxftarrkhlkxufqhsqeacwzfonupihnjyzzwnrutdkcwtehzyjgvvsgevxewyhzhkwpoxkjjafdivqsabiayrgeytmkxtzhjeynttovyldlhfyfzwbfzaweoghgfyyblrrcqjzajmsjormweeqyzsiuqsgyoddkgzxskwpytbysvroanpplwjnucowvwdhimvjnosezxhrxswxlfyfqmiuyvrbngigbldvbejqlrnqffkhjdftnkgusegtpasapuwldmlmnxzxhckopukczpsbkqjdhonydgjdlfpldqawrzqojjulizkwvaoxykzmrupoaafwpvexihbrjjwxtzbjvdfqwrajuvlnxudwpqqqvzvfmfvesrqqfvugqhtavwemmonxwnmhblutoaafvbvkuhgbjnduwtsckhjnsnlmfaghqejyzmibbwzflskzfcycnjpebsmlihbetehuomyyhnnqthonqtxigfioarksrhwgjiirlwnaqnadbyrvtyxhrsezkdkfgawlfuchsugturgibjozlplqymlczcbmybntqosaxpmqijcljyqrkocsjvaqdqsfqfhmdzxudqvsxbsvgijquzbxktwqgexjiqgkbdowmjypybkprxmmhzhnogjhzpbgrkphqywunzeijgqzreonyrkheeoltbruxndrdnhuwstxsdzhnoqmngtbjynlijjlbopnderookdpcdqeqtkwrqdiplysdjvojhxylxcxqrjtdirwswdtlvrytdxrlwhmdegsqmhaazhdtozzwomgbwppcfbyhwmpzobvpnqbmzvtqworqlnuthhfkshbgpohlhopedlvfuuqcmsgewtkuuxocdzyejbhmihjjgdxaspcthpwtxzzvzxitemwjbquuepgcqpgilpsekkendrpxzfmfdjtelrhjiqbmofjarzywltvbjhjpcitoatpcnhovanuuvlcnhkfedzksmhywcnlslamdztgitssswkbgmdkjzqjioxontjluwfkyaejkvquqcixbcicxbgreyzdkgnxspuxusudyxqlojhifwpfziqjhgyharrsyhqacnlewifrxgggvxhfaqjcthzhspvyrxswmvkwkyqgfaltzgqyoemgqbxquufjalezvvjdurcazdirrljhauabesfkpzkskbwzrluazbovmveecgkwwpzxqrpwxfsiukjpfzxryndoofohvvramxfdbtyqzcstqjesshrcygtctkymeimreyszmddhqxyqurcxlnkksylixnfgrswwvrsrqpknvvcnhimbklsixqmdmcnmzrnbdswtfyuqnzlsqwqgologslbpokjudvvyvzcaxyaepdwtwdndslhswhnbpmphasxkglrukhmbjssdcgkiohelcdvoofvucgqotqiwmgxynjuggscsahqocuutariwloclmwigjbejrxvujxtjvbmgvfhpowxmniruncakpunfhjkunrzzzdteqomdsvjoegijuyggwjjibovzjjeycpvnmupdosrcsdvblhtvrykqljkhtbdboxwfzyhmuyqnaxctkfmiqogqqbvhkourtjahbqnnkvifsxdxqtcolgvqlrujumzgqcoxifwrrfgpyfgmlqpnamcvkjjjwybzgbyooatvnzpxdvloxivkrvtjbnnbqwtbrsfdswtknbaaggqcuclaxwqsoeuxunnnzfbsgmhpcpktiluazzkzaivzgyttccbpptaegucsbvirrafwxrkbconutpwsusseutxrypzhmvttvpftdbjhkfhctphrbzoszatydweonydryatfsibdhjwhegptkcikinentiazxugcdlpzmdayxjsgcjqtkdfvbkpmmiyjzyiwpvqsooucnmpquxbpjhltxmiqxhbcmoesxhdcpbuukosxnzmizsigrzdgtkpuprnpogpmegojfdwvupldjtglnkbszsmhnrhlqpkbtfulyfuqliovvovtcmayoqyxujrpwndfbzsmftpksoyoepkmablhiunnuybawetbvojblrgmenxfpmiomhgpqpyjrpvhrslxgnfhsajnfjslfiuoybumzmbigxkmmobsusdyzzuyrzieoxdrtescnnwxmleriqrbxwimfqqwnakfangowwauvoqtoxklvtvmyyjwvjcfrwtbxwrhvnatndbtvxxmprqkyjltmprfdasdhpgbkpeqmtzbqiuivwvxhpmcsnfgbejwewwilhfutrirbvmxnhsypoqhlptwqouawletsdklwusgyfjrlvrpwnionjtljnehbzyfxgveedbefowrzmnovtpiyfoemirwrfkmilpupmmldkoyjrbwmbjhnwunrmfrgovfwnkrcxkqjxscgpqxrgikqskqzwfqwnpebizmyuzqykoosskuveznhbohhdseshqniuocdxkbpwdkoyozmajyrhnppldvaltuscbhsqowpzsvlqrfjuvsrdsamqqqacxkzsxnbamqeoxnkevrelayinwdaypcxwiycpuktbdhxehpcatddkocanpgjmdglnoamallknslqdmyxilnmsddotlfztmurzmsiebwpgqkmmqyexclykoxawiidaykmalwjyrsmoumrsbhnqxjkqopwqipzqrnxdixqkqjbsbttdddyryccaccfafaqeumjeeryqteenfjmiyyauvgvagltgsndfrsxkasimlveesfxoqlynjabtzryosvhkdnodqnsgezkgrzidceyzisyryrhjkysjnqyswylbejrahoxvvhcscnqgdsaahvmldnphmwogikjyrauonlztpgyqcwylhzmbwdztdpahusbysqplhimbltdvtycqxisnipapxeoqtlhtkvivnwbhfgmxhdcaiqdmpxfuqoxtxakwswdnqycjwqwryirnxqgohnbbqogobroifsmwjtjzdzrtulkjynqxbnoyjbwosfodnbcdauosglhsjqfcnnbsarxxgkhbtxbdloukycpcoypvxogmfcerljogtrlzcqrlogulbiyfsesjybmmdytlmkbwefuvsmtjcojfxpapkqjwvhtyqwmzxdystgozdgogqbdqhvlkspuxxqfiacdvnzhibgfzuzakqqswoacytfsdhzesxksgimhwkvddzfyakjmzlgknmndytphqaunghtuhjkkjyicqgmjvxcutwoiqvqxfawzwuuikgjqrfdnfcqqwvwgvjffetmwcfemyuhzyvicqkezagbtrqvlsircpmaeczdujtqnlsyfumbqfouxhpmwrzaciqzfpkzkcscjaichjjsyftwjltcsnmbxsozyltyuyjbujgvsahibnagwwwkacqyrjkiftcpklkxnysytqoyhibqqpdgzmkynbwpndnsnxmarnhtwhunedneftdpenrykljvcdkknvitlyjznvaeqgdozvrxooqfgmvhnqxgrfravsxlkwlenrruibwrjoupgsqpvreryybmcuujimjqzidssolfevezfnsqmmixzsnhifjjmyjxoqzzfmmqdmomfayoguaqqhbzershztalosxventouwznjxohsekrtypunhlhhatckxnkqeujlgnoftnsteuxbdgpfwywhfmwszecborzrhgbeymiluidtrksraewipnjlcsngbjfxsjrofyroxdfcxsorakmefkdngohelizojjjncebhvvvphikvgippueimhwtfuedgloidjuyswvmqfvvphffxhoebbsatwswvsabbwrdbpfmvoegjlxzsguvetalhonbbsmnfafxxniadcjrmihctihttueaaumhoqivnkihelnjgntspgikzeysmiwdwwkkroblisdaddfshrcnjveeijvqdkmltmblbaifgzswboznvbmqeeqxjxlnizyydokojyrbdmmyzhdyebqzxqkohofgrvemrxorljvnfztnriartlzzikkzhbkjmpygeqpxbemnivpslvmcdrfekyrgofwcenkqtlogdptigkrgpthxiitjdsuxmlghvdsitwcuuoiaywzzdabarxouicuftepjydddlqtrcthrysgxlqebjnkreedlfqdezlkltuyhkcqguwtlzdmfdmaueafwjmrvzopqqszoluiokyoleadpgncpbbjbowtwxvfhtktqdtpuavgapekgogugcoidveqfatsnknvzsnzdijfagdvyskkaowwlacxtvynmkgckusacwbimgrlmpzfahdpkznmgapxomjqkawrtnzojjnihfjjwjvrsppiksqhqlgusmuwlomatlqpveqnmvazrwuadfiluktpsuzynmkngwwhakouaqxhohryfncgweyagjdwqkgfunhvxztdevtuioqzmepdniiysbzbkxivvpzqbyftzkakvdsconhnmycksledkiubhnvifliekqsucxivrxmpjeorrenthlfvawdnnmnujdsxdibtvvjqghxaklrubelvpufrzmshnuvmbvdbskaozdzszxuimsmjgwfexpvzqvfvbatcyyudkfmbyxdcayraydfogvmomqqriamcipkhoohvenkbcieqbzohqoejnujduwwbkmpnuzqyxnlzvbopeoasepgxgtxfimxsvzkohluzjqykzfnkdiaradcbhpqlcjqhmmuuwawynzyvzjulbkikvuerljdfrxquljjzlcjoxpgsqznuxykghydkqaybghxixeqnhtmnxlrgkcctjvnktcppnbeoocegxnwavtxxnyyqoiwihxmusviqumficjvsbsfqxszdcgboppsipnmghyaxcbzqaqfyitatqxantamritaynlahfnivgdvwexltgvpyuyqmdvhaglcbkqqbnerkwodjaniwuvippzuxambcvnjhyjngbfdctfzmdzydrhiinbzwrdjfiqjiehjexbqqdzvsqoitdfrfjauebfgklzkhrwrdcnxptrbaqzrwhlclzozixzqtsdploalrpkcbfecwakawamxqgfgxqtozyxswtpxeubtxjbcpqdxbegdjzxyqpmynsoeizdgrusdjfwxdqpgagxivuhnvbfkzyedcvuvviqdwoogjiohedhkjtmvolohkwdxivkpknrzwybvyvzgwpfmphhyikahqhcmqfgjlqtfxsmlcwityahsbscpqeizuvovzhkgjsszdnibvmkjpsgoxedclcrlvvmbuuomodgdwxlgurerxiovfdifofvohbeaqhzxlccyqopjcaiiawzqggqhiibhtcicxxnygdtimeoiiegnesserbrmczmvsctcmxtbpuuotcgilvampmbvtmocbwqbqqweanmqosttoczdmfkdtdsefeirypczqmegpzqfgiwmmvtggaggbgzsdjjupnipffyyabftxuckdcebapbhkjycdavlfgkiititnqgmykosvgfgvpienqvbftjsfhvsxnjklycalqxskwdoizdffwrszljkkvugggvicbxhslpvygssebblxugnsnwgqrsmboqtqzfjuaiyleuxycwedmjiovyzyvzsoypoohcufxftbkiffowxwhjtlnztbvwimhofnvcibzvkoneuszylbmaydsrbqaygtzqevtsufxpzijztftwniizuccexlrcfbyiiyohtbrbnlccmhmbpoxcfeeakndsllmjfazugxubpwbjqtkwuzkkjzdkwacxwosljycxfuffzbzknnbspidtbzasxlrhaeylslczfszgdrqkvcfwmuweqmoctzuyicbqpvzomtfaienpkcitijxymixqsujyovmhavxjxzckbvvemxcobkjajmqhjqxtnjhrxvefgyrowbsgizzckgbhgatqyxptdzumtgnhtevrzowkdwlleuohcceqoblzsmtnucshmwyrzvsdlgvwuxamjwyfhmxiyrlztlgzbzrgtlcohwytbrnsuftirarmubqjrmxnmkudptiaxfnwrfmiuqvyiljtjmlunchelckaigvfokttwvlnchbtpsinfvpsdzmkgfeigraosyfleiorumsaeqvgzncofcltgowmjoccnqpezjeonxghbxccldtcoykrntkyztgtspzhmenviunitoazwlvktdbgiadocnuvgxdwpwnpkrfasajtpcgeyjkbyjlgscejedhighludhpaznvgwmwzdtidotzjxisjkzprqmnwdrcqjdudzmivrkxgugcogtmaafupjqvhsagspwkdazjdjjmilpjhooubrvwxmwctgplgdsaujxdpgzhohffyafgkfxdkqsqadkwwdxjptryzjhsseqpgfdpefpbskvnfuvmtynsdzavupcdfecspnpqgfdkcnnpeoisojpftrhdppnjuloqoqrfhctrgtkmeqlzltnexeivpbfomrnftrzpaqnxpbthuqlihnoytwhelrhuhvcmiocyscxdsfqbqsfompvaxseoykbsknritjybarukxembzoowynkjxuporusjhezzwbdprmpgyxbzktiwubotwbleyzrqhnpajopklqksbfeixtvrebzrokoojpegdnrrtwlrcyfiabfauohrkeweyepfrjntxouxxghkabjbucnhzkstaafsgugjtxtzwdcvvgbwlseiqaxjissvhhxpxxarnfpwkcfbvecnlzlsomadlfabgxckuqjatvbfrddxcovnigerkzdavogizmqhyjmiyzttfxvscaaqjnjtlknyyyihfpvtierrjdybjfibvcfrpttuidtctpkaxvljturvmylgihazgtusycfgkqwmacpspiarqyumgstdbqntouptvjqmysdghtmgflzhjzwoyoxvpmaoeepzavnqpmzsszlkeiqmmhufoxahkiqvbvovdqqgojutqmrutguvusosdtfkzkmrcdeslqukzqncyfcpxsrgyzkkzemqmitqmdlfwmdvgeercsdtsmzjmnyewzmgkxncutuvfwozlifxxtxdwzufgevzrunqdhuoicvdueudxocnyruuqwylaujftanbaidzwaiaqzxcrmkshazhbaelzwnaqtkrjtexiskzrofqjzxtsjceiqldhsedyewqczqslccsrrijevqchauzkopwnmzsbjrypfdtaeycgidfhqggewingnihrnwbnmuhtayqqhlwnmmyuibwfhqgemkxgyoumtorkanclrhtupsklvhsolcejvhixmnblugbxciifmvkwauhuywvbuutzktocgcngzkvnwvrjdmoibalwxgxfbubupwisbajtuuxoxpdouqmdaezocfbpkeqezkmrugupulxgtpnlwlfunjuaatfzrggrotfsehswepguoapdpvtfgkyheqwbnpoowafotdzzowxyhxehfrekejjhzctdtqssthcmvmaznatprnjitwflwytwuwlknzwrnpnrymjeeljhyypokdjgiszpozrhojjebxjfrfoxatxhi"
Output = 66042
I've changed your code a little bit, but only to the point that it is giving correct result. If you want to optimize your code, #hiro protagonist's answer is a pretty good example to start with.
# this function is working fine
def key_front(num, k, word, keyboard):
for x in range(k):
if word[num] == keyboard[x]:
return x
return 0
def calculateTime(keyboard, word):
k = len(keyboard)
count = 0
i = 0
w = len(word)
diff = 0
# I've added a new variable here to store "your finger's" previous position:
prev_front = 0
while i < w:
# there is no need to initialize "front" here
front = key_front(i, k, word, keyboard)
print(front,diff,word[i],count)
#if word[i] == word[i-1], front and prev_front would be the same, resulting diff == 0
diff = front - prev_front
# assigning our new variable prev_front
prev_front = front
# diff might be negative so we only need it's absolute value
count += abs(diff)
i = i + 1
return count
this seems to work:
keyboard = "pyevcountbgjklxfqwimrdhazs"
word = "gxafwhexxykisc...jebxjfrfoxatxhi"
keys = {char: index for index, char in enumerate(keyboard)}
index = 0
s = 0
for char in word:
i = keys[char]
s += abs(index - i)
index = i
print(s) # 66042
i create the look-up table keys for the keyboard first, then i loop over the characters of your word, update the index i currently am and sum the absolute difference between the new ald the old index in the running sum s.
in your solution diff is always assigned to 0 and will never be any other value: you only handle the case where the current and the previous letters are the same.
also you do not seem to keep the current index you are at.

How to find duplicates in a python list that are adjacent to each other and list them with respect to their indices?

I have a program that reads a .csv file, checks for any mismatch in column length (by comparing it to the header-fields), which then returns everything it found out as a list (and then writes it into a file). What I want to do with this list, is to list out the results as follows:
row numbers where the same mismatch is found : the amount of columns in that row
e.g.
rows: n-m : y
where n and m are the numbers of rows which share the same amount of columns that mismatch to header.
I have looked into these topics, and while the information is useful, they do not answer the question:
Find and list duplicates in a list?
Identify duplicate values in a list in Python
This is where I am right now:
r = csv.reader(data, delimiter= '\t')
columns = []
for row in r:
# adds column length to a list
colm = len(row)
columns.append(colm)
b = len(columns)
for a in range(b):
# checks if the current member matches the header length of columns
if columns[a] != columns[0]:
# if it doesnt, write the row and the amount of columns in that row to a file
file.write("row " + str(a + 1) + ": " + str(columns[a]) + " \n")
the file output looks like this:
row 7220: 0
row 7221: 0
row 7222: 0
row 7223: 0
row 7224: 0
row 7225: 1
row 7226: 1
when the desired end result is
rows 7220 - 7224 : 0
rows 7225 - 7226 : 1
So I what I essentially need, the way i see it, is an dictionary where key is the rows with duplicate value and value is the amount of columns in that said mismatch. What I essentially think I need (in a horrible written pseudocode, that doesn't make any sense now that I'm reading it years after writing this question), is here:
def pseudoList():
i = 1
ListOfLists = []
while (i < len(originalList)):
duplicateList = []
if originalList[i] == originalList[i-1]:
duplicateList.append(originalList[i])
i += 1
ListOfLists.append(duplicateList)
def PseudocreateDict(ListOfLists):
pseudoDict = {}
for x in ListOfLists:
a = ListOfLists[x][0] #this is the first node in the uniqueList created
i = len(ListOfLists) - 1
b = listOfLists[x][i] #this is the last node of the uniqueList created
pseudodict.update('key' : '{} - {}'.format(a,b))
This however, seems very convoluted way for doing what I want, so I was wondering if there's a) more efficient way b) an easier way to do this?
You can use a list comprehension to return a list of elements in the columns list that differ from adjacent elements, which will be the end-points of your ranges. Then enumerate these ranges and print/write out those that differ from the first (header) element. An extra element is added to the list of ranges to specify the end index of the list, to avoid out of range indexing.
columns = [2, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 2, 1];
ranges = [[i+1, v] for i,v in enumerate(columns[1:]) if columns[i] != columns[i+1]]
ranges.append([len(columns),0]) # special case for last element
for i,v in enumerate(ranges[:-1]):
if v[1] != columns[0]:
print "rows", v[0]+1, "-", ranges[i+1][0], ":", v[1]
output:
rows 2 - 5 : 1
rows 6 - 9 : 0
rows 10 - 11 : 1
rows 13 - 13 : 1
You can also try the following code -
b = len(columns)
check = 0
for a in range(b):
# checks if the current member matches the header length of columns
if check != 0 and columns[a] == check:
continue
elif check != 0 and columns[a] != check:
check = 0
if start != a:
file.write("row " + str(start) + " - " + str(a) + ": " + str(columns[a]) + " \n")
else:
file.write("row " + str(start) + ": " + str(columns[a]) + " \n")
if columns[a] != columns[0]:
# if it doesnt, write the row and the amount of columns in that row to a file
start = a+1
check = columns[a]
What you want to do is a map/reduce operation, but without the sorting that is normally done between the mapping and the reducing.
If you output
row 7220: 0
row 7221: 0
row 7222: 0
row 7223: 0
To stdout, you can pipe this data to another python program that generates the groups you want.
The second python program could look something like this:
import sys
import re
line = sys.stdin.readline()
last_rowid, last_diff = re.findall('(\d+)', line)
for line in sys.stdin:
rowid, diff = re.findall('(\d+)', line)
if diff != last_diff:
print "rows", last_rowid, rowid, last_diff
last_diff = diff
last_rowid = rowid
print "rows", last_rowid, rowid, last_diff
You would execute them like this in a unix environment to get the output into a file:
python yourprogram.py | python myprogram.py > youroutputfile.dat
If you cannot run this on a unix environment, you can still use the algorithm I wrote in your program with a few modifications.

Python - Finding next element in list matching a condition. Substitute previous entry

I have a list of elements to which I inputted some "identifiable" values that are not to go to my database. I want to find and substitute those values. Code looks like this (tried to be generic and illustrative, the date and time is predefined vars):
A = []
A.append(['Name1',date1,time1,0.00])
A.append(['Name1',date1,time2,0.00])
A.append(['Name2',date1,time1,price1])
A.append(['Name1',date1,time3,price2])
A.append(['Name1',date1,time4,price3])
A.append(['Name1',date2,time5,price4])
and so on. This 0.00 price should be changed by the next price where we have 'Name1' in position 0 and date1 in position 1, i.e.:
print(A[0])
print(A[1])
should yield
['Name1',date1,time1,price1]
['Name1',date1,time2,price1]
Appreciate your help.
Try this code for printing, pass the list and index for the same.
def print1(lists, index):
if lists[index][3] == 0:
try:
name=lists[index][0]
val = next(l[3] for l in lists[index:] if l[3]>0 and l[0]==name)
print lists[index][:-1] + [val]
except:
print "No value found with same name where price>0"
else:
print lists[index]
A=[]
A.append(['Name1','date1','time1',0.00])
A.append(['Name1','date1','time2',0.00])
A.append(['Name2','date1','time1',10])
A.append(['Name1','date1','time3',20])
A.append(['Name1','date1','time4',30])
A.append(['Name1','date2','time5',40])
print1(A,1)
you can return the values in place of printing them in case you need them to.
May be you need a method like this:
A = []
def insert_or_update_by_name_and_date(x):
if not isinstance(x, list) or len(x) < 2:
return
for element in A:
if len(element) < 2:
continue
if element[0] == x[0] and element[1] == x[1]:
element[2] = x[2]
element[3] = x[3]
return
A.append(x)
You can use two for loops:
for i in range(len(A)):
for j in range(i, len(A)):
if A[i][3] == 0.0 and A[j]]0] == 'Name1' and A[j][1] == date1:
A[i][3] = A[j][3]
Apart from that, you may find this discussion on when to use a Dictionary, List or Set useful.

Unbroken chain? Python iteration not being processed

So I've written a bit of code to stack integers in a list from the zeroth position. For some reason I cannot decipher, the while loop below is not being processed. I have followed all good style and syntax requirements that I know, and the while loop works when run by itself.
def row(line):
"""
Function that merges a single row or column.
"""
result_length = len(line)
print result_length
# Create a list of zeros the same length as the 'line' argument
pts_alloc = 0
dummy = 0
result = line
result[0:] = [pts_alloc for dummy in range(len(result))]
print result
#Iterate over the 'line' list looking for non-zero entries and
#stack them from 'result[0]'
line_count = 0
result_place = 0
while (line_count <= (len(line)-1)):
if (line[line_count] > 0):
result[result_place] = line[line_count]
print result
result_place += 1
line_count += 1
return result
print row([4, 0, 0, 5])
Is there a major error in this code that I've missed? Is there some syntax requirement that I am unaware of?
The problems seems to be this part:
result = line
result[0:] = [pts_alloc for dummy in range(len(result))]
By replacing a slice of result, with result = line, you are replacing that same slice in line, too, as result is just another reference to the same list, not a copy.
Since the slice is the entire list, anyway, just do:
result = [pts_alloc for dummy in range(len(result))]
Also, you are declaring a lot of unnecessary variables. You could shorten your code to this:
def row(line):
result = [0] * len(line)
result_place = 0
for x in line:
if x > 0:
result[result_place] = x
result_place += 1
return result
Or even this:
def row(line):
non_zero = [x for x in line if x > 0] # take non-zero values
return non_zero + [0] * (len(line) - len(non_zero)) # pad with zeros

when i try to append value in dict its showing key error

I have a css file of this type
col1 col2
AAA
a 1
a1 1
a2 1
b 1
b1 1
b2 1
i am reading first col based on indentation,"AAA" has 0 no of spaces,"a" "b" has 1 space and "a1","a2" "b1" "b2" has 2 space, now i am printing dict as
d={'a':['a1','a2'],'b':['b1','b2']}
But what i want is
d={'AAA':['a','b'],'a':['a1','a2'],'b':['b1','b2']}
i am using code like this
reader=csv.DictReader(open("c:/Users/Darshan/Desktop/sss.csv"),dialect="excel")
for row in reader:
a.append(row['col1'])
for i in range(len(a)):
if a[i].count(' ')==1:
d[a[i]]=[]
k=a[i]
else a[i].count(' ')==2:
d[k].append(a[i])
this print this output
d={'a':['a1','a2'],'b':['b1','b2']}
so can anyone help me,thanks in advance
What if you just change your for loop to this:
# A variable to keep track of the least-nested level of your hierarchy
top_lvl = ''
k = ''
for i in range(len(a)):
# Pre-compute this value so you don't have to do it twice or more
c = a[i].count(' ')
# This case is the topmost level
if c == 0:
top_lvl = a[i]
d[top_lvl] = []
# This case is the middle level
elif c == 1:
d[a[i]]=[]
k=a[i]
d[top_lvl].append(k)
# This case is the most deeply nested level
else: # c==2
d[k].append(a[i])
In fact now that I'm making everything all sweet, you can probably just iterate through the values in a directly, without referring to its values by index. Like so:
# A variable to keep track of the least-nested level of your hierarchy
top_lvl = ''
# More descriptive variable names can make everything easier to read/understand
mid_lvl = ''
for val in a:
# Pre-compute this value so you don't have to do it twice or more
c = val.count(' ')
# This case is the topmost level
if c == 0:
top_lvl = val
d[val] = []
# This case is the middle level
elif c == 1:
d[val]=[]
mid_lvl =val
d[top_lvl].append(mid_lvl)
# This case is the most deeply nested level
else: # c==2
d[mid_lvl].append(val)

Categories