Goal is to find the maximum amount of times you can subtract t from s.
t = ab, s = aabb. In the first step, we check if t is contained within s. Here, t is contained in the middle i.e. a(ab)b. So, we will remove it and the resultant will be ab and increment the count value by 1. We again check if t is contained within s. Now, t is equal to s i.e. (ab). So, we remove that from s and increment the count. So, since t is no more contained in s, we stop and print the count value, which is 2 in this case.
Problem occurs when you have something as s = 'abbabbaa' t = 'abba'.
Now it matters if you take it from the end or beggining, since you will get more steps from the end.
def MaxNum(s,t):
if not t in s:
return 0
elif s.count(t) == 1:
front = s.find(t)
sfront = s[:front] + s[front + len(t):]
return 1 + MaxNum(sfront,t)
else:
back = s.rfind(t)
front = s.find(t)
sback = s[:back] + s[back +len(t):]
sfront = s[:front] + s[front + len(t):]
print (sfront,sback)
return max(1 + MaxNum(sfront,t),1 + MaxNum(sback,t))
def foo(t,s):
return max([0] + [
1 + foo(t,s[:i]+s[i+len(t):]) for i in range(len(s)) if s[i:].startswith(t)])
Should I ask why you care?
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.
Given a string that might have multiple occurrences of the same character, return the closest same character of any indicated character in the string.
Given the string s and n number of queries. In each query, you are given an index a (where 0 <= a <= |s| ) of a character, and you need to print the index of the closet same character. If there are multiple answers, print the smallest one. Otherwise, print -1.
For example, string s = 'youyouy', with a given query 3: there are two matching character at indices 0 and 6, each 3 away, we choose the smallest one which is 0.
Here is my plan:
I put the string in a dictionary, the key is distinct letters in a string, values are letters corresponding indexes. When given a query, find the corresponding letter in the dictionary and return the closest value to the query.
def closest(s, queries):
res = []
dict2={}
#dict2 - letter - indexs
for i in range(len(s)):
if s[i] not in dict2:
dict2[s[i]]=[i]
else:
dict2[s[i]].append(i)
for num in queries:
#closet- denotes closet letter index
closet = math.inf
#num is out of range , append -1
if num > (len(s)-1):
res.append(-1)
continue
#this is the only one letter, append -1
letter=s[num]
if len(dict2[letter])==1:
res.append(-1)
continue
#temp = list for that letters
temp=dict2[s[num]]
index=temp.index(num) . #in the list, letter index's index in list
if index==0:
closet=temp[1]
elif index==(len(temp)-1):
closet=temp[index-1]
else:
distance1=num-temp[index-1] . #left
distance2=temp[index+1]-num . #right
if distance1 <= distance2:
closet=temp[index-1]
else:
closet=temp[index+1]
if closet == math.inf:
res.append(-1)
else:
res.append(closet)
return res
I got two runtime error. I am wondering if you could help me out to maybe reduce some run time ?
Also, I am looking for another suggestions! I have used Python for a while, and I am looking for a job (university new grad). Is java usually running faster than Python? Should I switch to Java?
Im trying to do as simple as i can , but i look like a bit complex. Though you question is avoiding runtime error , i want to present my idea
s='oooyyouoy'
k='0123456789'
def cloest(string,pos):
c = string[pos]
p1 , p2 = s[:pos] , s[pos+1:]
# reserve left part and find the closet one , add 1 because len(p1)=final_position + 1
l = len(p1) - (p1[::-1].find(c) + 1)
# find without reserve and add 1 because s[pos+1:]
r = (p2.find(c) + 1) + pos
# judge which one is closer if same chose left one
result = l if (pos - l) <= (r - pos) else r
if result == pos:
return -1
else:
return result
print(cloest(s,4))
def sumOfStudentDigits():
studentdigit = (studentdigit1 + studentdigit2 + studentdigit3 + studentdigit4 + studentdigit5 + studentdigit6 + studentdigit7)
studentdigit1=3 studentdigit2=6 studentdigit3=9 studentdigit4=3
studentdigit5=1 studentdigit6=0 studentdigit7=0
I need to assign seven digits to seven variables and add them together.
If your confusion is how to get the studentdigits into your function, you can pass them into the function like this:
def sumOfStudentDigits(studentdigit1, studentdigit2, studentdigit3,
studentdigit4, studentdigit5, studentdigit6,
studentdigit7):
studentdigit = (studentdigit1
+ studentdigit2
+ studentdigit3
+ studentdigit4
+ studentdigit5
+ studentdigit6
+ studentdigit7)
My advice would be to have all those digits stored in a list, and then pass merely that list to the function, then iterate over the list:
listofdigits = [studentdigit1,
studentdigit2,
studentdigit3,
studentdigit4,
studentdigit5,
studentdigit6,
studentdigit7]
def sumOfStudentDigits(studentdigitlist):
sum = 0
for digit in studentdigitlist:
sum += digit
return sum
print(sumOfStudentDigits(listofdigits))
We have to set sum = 0 before we can use sum because python wants to know what sum is before it uses it, so we assign it 0 so that we can count up from there.
Notice how studentdigitlist and listofdigits are different?
You can pass a list of any name to the function, all that matters is that you use the variable (ie a list in this case) name that you have used in def myfunction(yourvariable): throughout the function definition. Python with substitute whatever you pass into the function for where you have that placeholder name within the function. Then when you run the function:
eg
def myfunction(yourvariable):
# do stuff with yourvariable
myvariable = myvariable + 7
somenumber = 2
myfunction(somenumber)
# now somenumber will equal 9
You could also pass in the entire student number and break it down inside of your function.
def sum_student_digits(student_id):
running_total = 0
for i in str(student_id):
running_total += int(i)
return running_total
print(sum_student_digits(12345))
Keeping things basic. You need to assign the seven digit student number, one to each variable.
def sumOfStudentDigits():
digit1 = 3
digit2 = 6
digit3 = 9
digit4 = 3
digit5 = 1
digit6 = 0
digit7 = 0
And then add them together:
print(digit1 + digit2 + digit3 + digit4 + digit5 + digit6 + digit7)
Note that the variable assignments can't be on the same line, and need to come before the sum.
I have a text with several occurrences of websites, let's say "www.test.com". I want to replace all these occurrences by "website_NR", where NR should start at 1.
Example:
text = "bbsjsddh www.test.com shduh sudhuhd sjdjsdh wiowqiuedl www.test.de uasuisdhckjdfh www.test.de sudhdhdhfh"
Now, every occurrence of "www.test.com" should be replaced by "website_1", "website_2", and so on...
I tried it with:
n = 0
if 'www.test.com' in text:
n = n+1
text = text.replace('www.test.com', 'website_'+str(n))
But...this method counts only the first occurrence of "www.test.com"
The code function below will replace old with new + '_{}'.format(n) one at a time while old is in your string. It also increases n for each iteration so you get 'website_1', 'website_2', etc.
def func(s, old, new):
n = 1
while old in s:
s = s.replace(old, new + '_{}'.format(n), 1)
n += 1
return s
text = "bbsjsddh www.test.com shduh sudhuhd sjdjsdh wiowqiuedl www.test.com uasuisdhckjdfh www.test.com sudhdhdhfh"
print(func(text, 'www.test.com', 'website'))
# bbsjsddh website_1 shduh sudhuhd sjdjsdh wiowqiuedl website_2 uasuisdhckjdfh website_3 sudhdhdhfh
What is wrong in the method end in the code?
The method end returns always 1 although it should return 0 with the current data.
# return 1 if the sum of four consecutive elements equal the sum over other sum of the other three sums
# else return 0
# Eg the current sums "35 34 34 34" should return 0
data = "2|15|14|4|12|6|7|9|8|10|11|5|13|3|2|16"
arra = data.split("|");
def do_row ( arra, n ):
return arra[4*n:4 + 4*n]
def row_summa (row):
return sum(map(int,row))
def end ( summat ): # problem here!
equality = 1
for i in summat[2:5]:
print "Comparing: ", summat[1], " and ", i, ".\n"
if summat[1] != i:
equality = 0
print equality
for i in range(0,4):
summat = []
summat.append( row_summa( do_row(arra,i) ) )
print row_summa ( do_row(arra,i) )
summa = 0
end(summat)
I can't really tell what you're trying to do here, but I can certainly say why end() returns 1 instead of 0. In your last for loop, you reset summat to [] at the start of the loop, so at the end, summat only contains a single value (the one you most recently appended on). So when you ask for summat[2:5] on a list of a single item, Python returns an empty list (as there are no values in that range) - in which case there are no chances for equality to be set to zero because the loop in end never runs.
I think you may have an off-by-one error. Remember that array indexes in Python start at 0, not 1. So where you do this:
for i in summat[2:5]:
print "Comparing: ", summat[1], " and ", i, ".\n"
if summat[1] != i:
equality = 0
you are not looking at summat[0] at all. Try perhaps:
for i in summat[1:4]:
print "Comparing: ", summat[0], " and ", i, ".\n"
if summat[0] != i:
equality = 0
You should also study this piece of code
data = "2|15|14|4|12|6|7|9|8|10|11|5|13|3|2|16"
arra = map(int,data.split("|"))
summat = [sum(arra[i:i+4]) for i in range(0,len(arra),4)]
print summat
print len(set(summat))==1
First off, end doesn't return 1. It returns None. It prints 1. Kind of deceptive if you're running it from the command line.
Second, when you call end, summat is equal to [34]. So this:
for i in summat[2:5]:
never even executes. It won't do anything unless summat contains at least 3 elements.
You have two problems. Initialising summat to [] inside the loop, also the off by one error Greg mentioned
data = "2|15|14|4|12|6|7|9|8|10|11|5|13|3|2|16"
arra = data.split("|");
def do_row ( arra, n ):
return arra[4*n:4 + 4*n]
def row_summa (row):
return sum(map(int,row))
def end ( summat ): # problem here!
equality = 1
for i in summat[1:]: # 1 <=== IS THE SECOND ELEMENT
print "Comparing: ", summat[0], " and ", i, ".\n"
if summat[0] != i:
equality = 0
print equality
summat = [] # <=== DO THIS BEFORE THE LOOP
for i in range(0,4):
summat.append( row_summa( do_row(arra,i) ) )
print row_summa ( do_row(arra,i) )
summa = 0
end(summat)