python - Weight for weight from CodeWars - python

The code works, but at the same time it outputs a string in which the same value can be reversed. Therefore, it gives an error in tests
Here is the code itself:
def order_weight(strng):
weight = strng.split(' ')
t_weight = weight.copy()
answ = ''
t_arr = []
for i in range(len(weight)):
t_min = 2**64
t_index = 0
t_num = 0
for i, num in enumerate(t_weight):
t_sum = 0
for j in num:
t_sum += int(j)
if t_sum <= t_min:
t_min = t_sum
t_index = i
t_num = num
t_arr.append(t_num)
t_weight.pop(t_index)
answ = ' '.join(t_arr)
return answ
enter image description here

Find it's harder to follow your logic, but this will be my simple approach:
Please read and compare with yours. It's passed all tests too.
def count_weight(s):
return (sum(int(c) for c in s), s)
def order_weight(s):
return ' '.join(sorted(s.split(' '), key=count_weight)) # use the *weight* as the sort_key here

Related

google codejam shows python runtime error

This code is for the Google codejam competition. The below code is compiling correctly on my PC and gives the correct result for the sample code. However it is showing runtime error whenever I try to run it on the google website. I have been messing with it for one hour and still have no idea what's wrong with it.
def reversort(reverList):
global totalScore
length = len(reverList)
score = 0
for i in range(length - 1):
minimum = reverList.index(min(reverList[i: ]))
tempList = reverList[i:minimum + 1]
tempList.reverse()
reverList[i: minimum + 1] = tempList
score += minimum - i + 1
totalScore.append(score)
if __name__ == "__main__":
t = int(input())
totalScore = []
rev = []
for i in range(t):
n = int(input())
apen = []
for j in range(n):
apen.append(int(input()))
reversort(apen)
print("Case #{}: {}".format(i+1,totalScore[i]))
rev.append(apen)
try this
reverse = int(input())
for i in range(1, reverse + 1):
a = int(input())
b = list(map(int, input().split()))
out = 0
for index in range(a-1):
min_index = b.index(min(b[index:a]))
b[index: min_index + 1] = reversed(b[index: min_index + 1])
out += (min_index) - (index) + 1
print("Case #{}: {}".format(i, out))

Hash table problem for education perposes

The problem is this:
It is required to create and use the hash table structure in a problem
large number of keys.
Here are the steps:
Creating one million (1,000,000) visits to a department store
and Credit Card Payment.
From the very large number of different cards, a relatively small subset is created
as follows. Credit cards for visits will have
sixteen (16) specific fixed digits eg 1234567890123456,
but in four (4) of the sixteen (16) random positions they will also have
four characters: X, Y, Z, W in random order.
eg 12Y45W789012Z4X6
In the other places the prices are the initial ones.
I have written the codes. Is is supposed to run super fast but it runs super slowly and I don't know why... Currently, I am running my code for 10,000 cards. Could you help me? Please excuse my poor english...
The code is bellow:
import string
import random
import time
random.seed(1059442)
global max_load_factor
max_load_factor = 0.6
def printGreaterThan2(num):
while True:
if num % 2 == 1:
isPrime = True
for x in range(3,int(num**0.5),2):
if num % x == 0:
isPrime = False
break
if isPrime:
return num
num += 1
N = printGreaterThan2(1000)
arr = [ [] for _ in range(N)]
arr = [ None for _ in range(N)]
def CreatNewItem():
letters = "WXZY"
days = ["Mon", "Tue", "Wed" , "Thu" , "Fri", "Sat"]
s = ''
count = 0
num = ['1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6']
list_a = []
while(count!=4):
a = random.randint(0,15)
b = random.choice(letters)
if b not in num and a not in list_a:
num[a] = b
count = count + 1
list_a.append(a)
s = ''.join(num)
d = random.randint(0,5)
day = days[d]
money = random.randint(10,100)
a = [s,day,money]
return a
def hash(key, tablesize):
sum = 0
for pos in range(len(key)):
sum = sum + ord(key[pos])
hash = sum % tablesize
return hash
#--------------------------------------
def rehash(oldhash , tablesize):
rehash = ( oldhash + 1 ) % tablesize
return rehash
#--------------------------------------
def put2 (arr,a,N,lenght,collitions):
if float(lenght)/float(N) >= max_load_factor:
(arr,N,collitions) = Resize(arr,N,lenght,collitions)
key = a[0]
i = hash(key,N)
j =0
while (True):
if arr[i] is None:
arr[i] = a
lenght = lenght + 1
break
elif arr[i][0] == key:
arr[i][2] = arr[i][2] + a[2]
arr[i][1] = arr[i][1] + a[1]
break
else:
if j == 0 :
collitions = collitions +1
j = 1
i = rehash(i,N)
return (lenght,N,arr,collitions )
#----------------------------------------
def Resize(arr,N,lenght,collitions):
print("resize")
N = printGreaterThan2(2*N)
collitions = 0
arr2 = [ [] for _ in range(N)]
arr2 = [ None for _ in range(N)]
for p in arr:
if p is not None:
(lenght,N,arr2,collitions)=put2(arr2,p,N,lenght,collitions)
return (arr2,N,collitions)
#-----------------------------------------
l = 0
cards = []
collitions = 0
t0 = time.time()
i=0
while i!=10000:
b = CreatNewItem()
(l,N,arr,collitions) = put2(arr,b,N,l,collitions)
i=i+1
t1 = time.time() - t0
print('\ntime is {:0.20f}'.format(t1))

Why does my hexadecimal to base64 converter break down on large numbers?

I'm working on a cryptopals problem. Specifically, the first one. I have a, what I feel, decent solution for it, in that it works for given inputs, and for the example they give, but I've been looking at further testing to see if it holds up, and it doesn't seem to. Here's my code:
hex="0123456789abcdef"
base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def hexNumeralToBinary(hexNumeral):
index = hex.index(hexNumeral)
binaryNumber = []
while index > 0:
if (index % 2) == 0:
binaryNumber = ["0"] + binaryNumber
index = index / 2
else:
binaryNumber = ["1"] + binaryNumber
index = (index-1)/2
while len(binaryNumber) < 4:
binaryNumber = ["0"] + binaryNumber
return ''.join(binaryNumber)
def hexToBinary(hexNumber):
length = len(hexNumber) + 1
binaryNumber = []
for i in range(1, length):
hexNumeral = hexNumber[-1*i]
binaryNumeral = hexNumeralToBinary(hexNumeral)
binaryNumber = [binaryNumeral] + binaryNumber
return ''.join(binaryNumber)
def splitString(binaryNumber):
while (len(binaryNumber) % 6) != 0:
binaryNumber = "0" + binaryNumber
binaryNumberSplit = []
while binaryNumber != "":
binaryNumberSplit.append(binaryNumber[0:6])
binaryNumber = binaryNumber[6:]
return binaryNumberSplit
def hexToBase64(hexNumber):
base64Number = []
binaryNumber = hexToBinary(hexNumber)
binaryNumberSplit = splitString(binaryNumber)
for sixBitNum in binaryNumberSplit:
#Convert 6 bit binary number into the base64 index
index = 0
for i in range(1, 7):
index += int(sixBitNum[-1*i]) * (2**(i-1))
base64Digit = base64[index]
base64Number = base64Number + [base64Digit]
return ''.join(base64Number)
hexNumber = input("Please enter a hexadecimal number to convert to base64: ")
print(hexToBase64(hexNumber))
It seems like the hexadecimal number needs to have a number of digits divisible by 3, or it just gets stuck while running. I don't know where, and I'm really stumped. I'm a total beginner to programming, and this is easily the most complex thing I've done, just trying to work it out as I go, and this isn't coming to me.

Implementing Knuth-Morris-Pratt (KMP) algorithm for string matching with Python

I am following Cormen Leiserson Rivest Stein (clrs) book and came across "kmp algorithm" for string matching. I implemented it using Python (as-is).
However, it doesn't seem to work for some reason. where is my fault?
The code is given below:
def kmp_matcher(t,p):
n=len(t)
m=len(p)
# pi=[0]*n;
pi = compute_prefix_function(p)
q=-1
for i in range(n):
while(q>0 and p[q]!=t[i]):
q=pi[q]
if(p[q]==t[i]):
q=q+1
if(q==m):
print "pattern occurs with shift "+str(i-m)
q=pi[q]
def compute_prefix_function(p):
m=len(p)
pi =range(m)
pi[1]=0
k=0
for q in range(2,m):
while(k>0 and p[k]!=p[q]):
k=pi[k]
if(p[k]==p[q]):
k=k+1
pi[q]=k
return pi
t = 'brownfoxlazydog'
p = 'lazy'
kmp_matcher(t,p)
This is a class I wrote based on CLRs KMP algorithm, which contains what you are after. Note that only DNA "characters" are accepted here.
class KmpMatcher(object):
def __init__(self, pattern, string, stringName):
self.motif = pattern.upper()
self.seq = string.upper()
self.header = stringName
self.prefix = []
self.validBases = ['A', 'T', 'G', 'C', 'N']
#Matches the motif pattern against itself.
def computePrefix(self):
#Initialize prefix array
self.fillPrefixList()
k = 0
for pos in range(1, len(self.motif)):
#Check valid nt
if(self.motif[pos] not in self.validBases):
self.invalidMotif()
#Unique base in motif
while(k > 0 and self.motif[k] != self.motif[pos]):
k = self.prefix[k]
#repeat in motif
if(self.motif[k] == self.motif[pos]):
k += 1
self.prefix[pos] = k
#Initialize the prefix list and set first element to 0
def fillPrefixList(self):
self.prefix = [None] * len(self.motif)
self.prefix[0] = 0
#An implementation of the Knuth-Morris-Pratt algorithm for linear time string matching
def kmpSearch(self):
#Compute prefix array
self.computePrefix()
#Number of characters matched
match = 0
found = False
for pos in range(0, len(self.seq)):
#Check valid nt
if(self.seq[pos] not in self.validBases):
self.invalidSequence()
#Next character is not a match
while(match > 0 and self.motif[match] != self.seq[pos]):
match = self.prefix[match-1]
#A character match has been found
if(self.motif[match] == self.seq[pos]):
match += 1
#Motif found
if(match == len(self.motif)):
print(self.header)
print("Match found at position: " + str(pos-match+2) + ':' + str(pos+1))
found = True
match = self.prefix[match-1]
if(found == False):
print("Sorry '" + self.motif + "'" + " was not found in " + str(self.header))
#An invalid character in the motif message to the user
def invalidMotif(self):
print("Error: motif contains invalid DNA nucleotides")
exit()
#An invalid character in the sequence message to the user
def invalidSequence(self):
print("Error: " + str(self.header) + "sequence contains invalid DNA nucleotides")
exit()
You might want to try out my code:
def recursive_find_match(i, j, pattern, pattern_track):
if pattern[i] == pattern[j]:
pattern_track.append(i+1)
return {"append":pattern_track, "i": i+1, "j": j+1}
elif pattern[i] != pattern[j] and i == 0:
pattern_track.append(i)
return {"append":pattern_track, "i": i, "j": j+1}
else:
i = pattern_track[i-1]
return recursive_find_match(i, j, pattern, pattern_track)
def kmp(str_, pattern):
len_str = len(str_)
len_pattern = len(pattern)
pattern_track = []
if len_pattern == 0:
return
elif len_pattern == 1:
pattern_track = [0]
else:
pattern_track = [0]
i = 0
j = 1
while j < len_pattern:
data = recursive_find_match(i, j, pattern, pattern_track)
i = data["i"]
j = data["j"]
pattern_track = data["append"]
index_str = 0
index_pattern = 0
match_from = -1
while index_str < len_str:
if index_pattern == len_pattern:
break
if str_[index_str] == pattern[index_pattern]:
if index_pattern == 0:
match_from = index_str
index_pattern += 1
index_str += 1
else:
if index_pattern == 0:
index_str += 1
else:
index_pattern = pattern_track[index_pattern-1]
match_from = index_str - index_pattern
Try this:
def kmp_matcher(t, d):
n=len(t)
m=len(d)
pi = compute_prefix_function(d)
q = 0
i = 0
while i < n:
if d[q]==t[i]:
q=q+1
i = i + 1
else:
if q != 0:
q = pi[q-1]
else:
i = i + 1
if q == m:
print "pattern occurs with shift "+str(i-q)
q = pi[q-1]
def compute_prefix_function(p):
m=len(p)
pi =range(m)
k=1
l = 0
while k < m:
if p[k] <= p[l]:
l = l + 1
pi[k] = l
k = k + 1
else:
if l != 0:
l = pi[l-1]
else:
pi[k] = 0
k = k + 1
return pi
t = 'brownfoxlazydog'
p = 'lazy'
kmp_matcher(t, p)
KMP stands for Knuth-Morris-Pratt it is a linear time string-matching algorithm.
Note that in python, the string is ZERO BASED, (while in the book the string starts with index 1).
So we can workaround this by inserting an empty space at the beginning of both strings.
This causes four facts:
The len of both text and pattern is augmented by 1, so in the loop range, we do NOT have to insert the +1 to the right interval. (note that in python the last step is excluded);
To avoid accesses out of range, you have to check the values of k+1 and q+1 BEFORE to give them as index to arrays;
Since the length of m is augmented by 1, in kmp_matcher, before to print the response, you have to check this instead: q==m-1;
For the same reason, to calculate the correct shift you have to compute this instead: i-(m-1)
so the correct code, based on your original question, and considering the starting code from Cormen, as you have requested, would be the following:
(note : I have inserted a matching pattern inside, and some debug text that helped me to find logical errors):
def compute_prefix_function(P):
m = len(P)
pi = [None] * m
pi[1] = 0
k = 0
for q in range(2, m):
print ("q=", q, "\n")
print ("k=", k, "\n")
if ((k+1) < m):
while (k > 0 and P[k+1] != P[q]):
print ("entered while: \n")
print ("k: ", k, "\tP[k+1]: ", P[k+1], "\tq: ", q, "\tP[q]: ", P[q])
k = pi[k]
if P[k+1] == P[q]:
k = k+1
print ("Entered if: \n")
print ("k: ", k, "\tP[k]: ", P[k], "\tq: ", q, "\tP[q]: ", P[q])
pi[q] = k
print ("Outside while or if: \n")
print ("pi[", q, "] = ", k, "\n")
print ("---next---")
print ("---end for---")
return pi
def kmp_matcher(T, P):
n = len(T)
m = len(P)
pi = compute_prefix_function(P)
q = 0
for i in range(1, n):
print ("i=", i, "\n")
print ("q=", q, "\n")
print ("m=", m, "\n")
if ((q+1) < m):
while (q > 0 and P[q+1] != T[i]):
q = pi[q]
if P[q+1] == T[i]:
q = q+1
if q == m-1:
print ("Pattern occurs with shift", i-(m-1))
q = pi[q]
print("---next---")
print("---end for---")
txt = " bacbababaabcbab"
ptn = " ababaab"
kmp_matcher(txt, ptn)
(so this would be the correct accepted answer...)
hope that it helps.

Converting string using list in python

I've been trying to rearrange the string by reversing a particular strings consecutively from the given string input and the limit is given as input.
for example
limit is 3
if input is Hellothegamestarts
output must be Heltolhegemastastr
and it is saved in separate array
The code is:
while True:
t = int(input())
if t == 0:
break
string = raw_input()
string = string.encode('utf-8')
leng = len(string)
r = t/leng
m = []
leng = 0
for i in range(r):
if r % 2 == 0:
l = 0
l = leng + t
for i in range(t):
temp = string[l]
m.append(temp)
l = l - 1
r = r + 1
leng = leng + t
else:
l = 0
l = leng
for i in range(t):
temp = string[l]
m.append(temp)
l = l + 1
r = r + 1
leng = leng + t
print m
the output i got is [] and asks for next input for t.
Any help is appreciated.
Take the blocks in chunks of 3s, and reverse the odd ones, eg:
import re
s = 'Hellothegamestarts'
r = ''.join(
el if idx % 2 == 0 else el[::-1]
for idx, el in enumerate(re.findall('.{,3}', s))
)
# Heltolhegemastastr
Maybe you can try -
t = int(input())
if t == 0:
break;
string = raw_input()
m = ''
leng = len(string)
i = 0
while i < leng:
if (i/t) % 2 != 0:
m = m + string[i+t-1:i-1:-1]
else:
m = m + string[i:i+t]
i = i + t
print(m)
Alternatively you can try this
def myfunc(s, count):
return [''.join(x) for x in zip(*[list(s[z::count]) for z in range(count)])]
a='Hellothegamestarts'
lst=myfunc(a,3)
print "".join([i if lst.index(i) in range(0,len(lst),2) else i[::-1] for i in lst])
myfun i didn't write it.It's from here

Categories

Resources