Learning to code with Python 3. I am confused why my else statement keeps executing with the code below:
def countSubStringMatch(target, key):
index = 0
instance_list = []
while index <= len(target):
match = target.find(key,index)
if match > -1:
instance_list.append(match)
index += 1
elif match == -1:
return None
return sorted(set((instance_list)))
target1 = 'mjzzmjzzmjzz'
key1 = 'zz'
print(countSubStringMatch(target1, key1))
The point of this code is to list the indexes at which the key starts. I had the code running fine when there are actual instances of the key within target, but I am trying to edit it to return None when there are no instances. This was my code before the edit:
def countSubStringMatch(target, key):
index = 0
instance_list = []
while index <= len(target):
match = target.find(key,index)
if match > -1:
instance_list.append(match)
index += 1
return sorted(set((instance_list)))
target1 = 'mjzzmjzzmjzz'
key1 = 'zz'
print(countSubStringMatch(target1, key1))
You'll eventually always get -1, as you inclement index. So yes, your elif is going to match and you end up returning None:
>>> target1 = 'mjzzmjzzmjzz'
>>> key1 = 'zz'
>>> target1.find(key1, 0)
2
>>> target1.find(key1, 3)
6
>>> target1.find(key1, 7)
10
>>> target1.find(key1, 11)
-1
So when index = 11, target.find() returns -1 for your sample input. Since len(target) is 12, that is still within your loop.
Only return None when instance_list is empty. Also, increment your index to step past the last-found index, there is no point in incrementing the index by 1 each time; that way you avoid all the duplicate indices and removes the need to use a set:
def countSubStringMatch(target, key):
index = 0
instance_list = []
while index <= len(target) - len(key):
match = target.find(key, index)
if match == -1:
break
instance_list.append(match)
index = match + 1
return instance_list or None
There is no point in searching from an index equal to the length of the target minus the length of the key; you are not going to find the key at index 11.
This returns None if no matches were found, rather than a list. You may want to reconsider this; testing for an empty list is just as easy and makes your API consistent (always returning a list, which may be empty):
>>> target1 = 'mjzzmjzzmjzz'
>>> key1 = 'zz'
>>> countSubStringMatch(target1, key1)
[2, 6, 10]
>>> countSubStringMatch(target1, 'foo') is None
True
Related
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.
i am trying to check whether certain elements are in a list, and to execute numerical update but i keep getting an error (below).
"if h2output[1] not in h1output == True or h2output[2] not in h1output == True:
IndexError: list index out of range"
doublewin = 0
h1output = []
h2output = []
h3output = []
v1output = []
v2output = []
v3output = []
d1output = []
d2output = []
for i in h1:
if i not in h1output:
h1output.append(i)
if len(h1output) == 2:
doublewin += 1
for i in h2:
if i not in h2output:
h2output.append(i)
if len(h2output) == 2:
if h2output[1] not in h1output == True or h2output[2] not in h1output == True:
doublewin += 1
As len(h2output)==2, it has only 2 positions, which in python starts at zero, therefore h2output[2] is out of bounds, index must be 0 or 1
You have hardcoded indexes in h2output[1] and h2output[2]. Either one of them is causing the issue. Please check the size of the list.
Remove True booleans in if condition as it is unnecessary.
Hi I have a list [tag1 tag2], I would like to find out whether the number following tag is incremental.
match_atr_value = re.search('(.+)\~(\w+)',each_line)
tags = match_atr_value.group(1).split('.')
print tag
Input:
[tag1 tag2]
[tag1 tag3]
[tag1 tag2 tag4]
Output:
Incremental
Not
Not
"Consecutive integers are integers that follow each other in order"
Is there a simpler way to do it? All I have to do is check if its incremental and if yes I should use them else I should throw an exception.
Thanks
You can extract all the digits followed by tag via re.findall() and then use enumerate() and all() to check if the numbers are consecutive:
import re
l = [
"[tag1 tag2]",
"[tag1 tag3]",
"[tag1 tag2 tag4]"
]
pattern = re.compile(r"tag(\d+)")
for item in l:
numbers = map(int, pattern.findall(item)) # if Python 3: call list() on that
result = all(index == item for index, item in enumerate(numbers, start=numbers[0]))
print(result)
Prints:
True
False
False
tag1val = int(re.search(r'\D*(\d+)', tag1).group(1))
tag2val = int(re.search(r'\D*(\d+)', tag2).group(1))
(tag1val - tag2val) == -1
True
tag3val = int(re.search(r'\D*(\d+)', tag3).group(1))
(tag1val - tag3val) == -1
False
(tag2val - tag3val) == -1
True
If you wanted to stick with regular expressions, you can go this route. If the difference is -1 then the one on the right is 1 greater than the one on the left.
If I were you, I would avoid a regex and do something like below. I get the number from the string, whether it's beginning, end, etc. and then compare it to the previous value and return False if it's not increasing
def isIncreasing( listy ):
prev = 0
for w in listy:
val = [''.join(s) for s in w if s.isdigit()]
cur = int(val[0])
if cur != prev+1:
return False
prev = cur
return True
I am currently trying to create a code that can scan a string, put the position of each letter found in a list associated to the letter (ex : if you find a S as the 35, 48 and 120 letter of the string, it will put 35, 48, and 120 in a list for the letter S). It will then put this list in a dictionary as a value with S for key.
My problem is simple, I have an IndexError: list assignment index out of range when I try to put the value in the list, but I cant find out why.
string = "Squalalanoussommespartisetjetedteste"
taille = len(string)
dico = dict()
dico = {}
i = 0
for i in range(taille):
if string[i] == "A" or string[i] == "a" :
va = 0
valA = []
valA[va] = i
va = va + 1
print(valA)
I apologize for my poor English, and thank by advance for the help.
You don't need to specify an index while pushing an item to a list in python. Try this:
for i in range(taille):
if string[i] == "A" or string[i] == "a" :
valA = []
valA.append(i)
print(valA)
You are getting this error in these lines
va = 0
valA = []
valA[va] = i
valA is blank list here, with zero elements, so when you try to assign a value to its 0 index, it raises IndexError.
Also to get indexes for each character you can directly loop over string, like
s = "Squalalanoussommespartisetjetedteste"
d = dict()
for i, c in enumerate(s):
d.setdefault(c.lower(), []).append(i)
print d
I found some errors in the code.
The index error is because you tried to call 0th position of an empty list.
valA = []
The list is empty. Then you tried to replace value at the 0th position when there is no 0th position
valA[va] = i
I made some changes to the code. In the ninth line you initialize an empty list. You should do that before for loop. Otherwise for loop initiate it everytime and you lose the value in the previous loop.
here is the modified code.
string = "Squalalanoussommespartisetjetedteste"
taille = len(string)
dico = dict()
dico = {}
i = 0
valA = []
for i in range(taille):
if string[i] == "A" or string[i] == "a":
valA.append(i)
print(valA)
The output i got is
[3, 5, 7, 19]
Though you may use straightforward approach, Python has some usefull modules that may help. For example
import collections
s = "Squalalanoussommespartisetjetedteste"
result = collections.defaultdict(list)
for i,char in enumerate(s):
result[char].append(i)
result would contain a dictionary with string characters as keys and lists if char's indexes as items.
You are redefining variables below everytime. So move them to out of loop.
va = 0
valA = []
Also use insert method for list. (You can use insert for when you need to use define index in list. otherwise append is enough)
so final code :
string = "Squalalanoussommespartisetjetedteste"
taille = len(string)
dico = dict()
dico = {}
i = 0
va = 0
valA = []
for i in range(taille):
if string[i] == "A" or string[i] == "a" :
valA.insert(va, i)
va = va + 1
print(valA)
index error, because array valA is empty array, that means there are no indexes...
use function append and declare array valA outside the loop...
string = "Squalalanoussommespartisetjetedteste"
taille = len(string)
dico = dict()
dico = {}
i = 0
valA = []
for i in range(taille):
if string[i] == "A" or string[i] == "a" :
valA.append(i)
print(valA)
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.